0
模擬模塊時可以訪問「真實」對象嗎?我正在試圖做的是模仿一些功能,但拋出的「真實」的例外,像這樣:模擬模塊時Python模擬訪問「真實」對象
@mock.patch('my_project.requests')
def test_foo(self, mock_requests):
mock_requests.post = mock.Mock(side_effect=requests.ConnectionError())
thread = CommandThread("command", 3, 2, 0)
thread.run() #this is were I exercise requests.post
self.assert(thread.was_successful is False)
裏面我CommandThread我有一個像
try:
requests.post(url, data=data)
except (requests.ConnectionError, requests.Timeout):
self.was_successful = False
然而一查,我的測試失敗,因爲異常沒有被捕獲到try/except塊內部(當我喜歡except Exception:
時,它的工作原理) 我想這是因爲我在測試用例中嘲笑了這個「名稱空間」,所以實際上提出了my_project.requests.ConnectionError
異常而不是正確的,requests.ConnectionError
從原始包裝。 是否有可能訪問/拋出「真實」的異常?