为不同的响应模拟urllib2.urlopen().read()

2024-07-05 14:32:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图模拟urllib2.urlopen库,这样我就可以为传递到函数中的不同url获得不同的响应。

我现在在我的测试文件中这样做

@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进行测试,以便在第一次调用时获得值“response1”,在第二次调用时获得值“response2”,这就是副作用

但是othermodule.function_to_be_tested()接收

<MagicMock name='urlopen().read()' id='216621051472'>

而不是实际的反应。请告诉我哪里做错了,或者用更简单的方法。


Tags: 文件ofto函数urlreadfunctionbe
1条回答
网友
1楼 · 发布于 2024-07-05 14:32:16

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

编辑:哎呀,最初包括了原来的错误。(正在测试以验证它是如何损坏的。)现在应该修复代码。

相关问题 更多 >