6
我試圖嘲笑urllib2.urlopen庫,我應該爲我傳入函數的不同響應獲得不同的響應。對不同的響應嘲諷urllib2.urlopen()。read()
我做它在我的測試文件,現在的方式是這樣的
@patch(othermodule.urllib2.urlopen)
def mytest(self, mock_of_urllib2_urllopen):
a = Mock()
a.read.side_effect = ["response1", "response2"]
mock_of_urllib2_urlopen.return_value = a
othermodule.function_to_be_tested() #this is the function which uses urllib2.urlopen.read
我期望的othermodule.function_to_be_tested以獲得第二呼叫第一個電話的價值「響應1」和「響應2」的是什麼side_effect會做
但othermodule.function_to_be_tested()接收
<MagicMock name='urlopen().read()' id='216621051472'>
,而不是實際的響應。請建議我出錯的地方或更簡單的方法來做到這一點。
您可以直接修補'@patch(urllib2.urlopen)'。 –
我正在嘗試修補在其他模塊中導入的副本。我想這就是它應該完成的方式 – quirkystack
我個人只是重新設計我的代碼,不硬編碼使用'urllib.urlopen';例如它會調用'self.urlopen_fn',它的默認值是'urllib.urlopen',但你可以在測試期間將它設置爲'your_mock_urlopen';它甚至可以是可以從外部設置的模塊級參數。 –