2013-10-05 25 views
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'> 

,而不是實際的響應。請建議我出錯的地方或更簡單的方法來做到這一點。

+1

您可以直接修補'@patch(urllib2.urlopen)'。 –

+0

我正在嘗試修補在其他模塊中導入的副本。我想這就是它應該完成的方式 – quirkystack

+0

我個人只是重新設計我的代碼,不硬編碼使用'urllib.urlopen';例如它會調用'self.urlopen_fn',它的默認值是'urllib.urlopen',但你可以在測試期間將它設置爲'your_mock_urlopen';它甚至可以是可以從外部設置的模塊級參數。 –

回答

12

的參數patch需要是所述物體的位置的說明,而不是對象本身。所以你的問題看起來像是你需要把你的論點串聯到patch

儘管如此,這裏是一個完整的工作示例。首先,我們在測試模塊:

# mod_a.py 
import urllib2 

def myfunc(): 
    opened_url = urllib2.urlopen() 
    return opened_url.read() 

現在,成立了我們的測試:

# test.py 
from mock import patch, Mock 
import mod_a 

@patch('mod_a.urllib2.urlopen') 
def mytest(mock_urlopen): 
    a = Mock() 
    a.read.side_effect = ['resp1', 'resp2'] 
    mock_urlopen.return_value = a 
    res = mod_a.myfunc() 
    print res 
    assert res == 'resp1' 

    res = mod_a.myfunc() 
    print res 
    assert res == 'resp2' 

mytest() 

運行從shell測試:

$ python test.py 
resp1 
resp2 

編輯:哎呦,最初包括原來的錯誤。 (正在測試以驗證它是如何被破壞的。)現在應該修復代碼。