qui*_*ack 11 python unit-testing mocking
我试图以一种方式模拟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
Run Code Online (Sandbox Code Playgroud)
我希望othermodule.function_to_be_tested在第一次调用时获得值"response1",在第二次调用时获得"response2",这是side_effect将执行的操作
但是othermodule.function_to_be_tested()收到了
<MagicMock name='urlopen().read()' id='216621051472'>
Run Code Online (Sandbox Code Playgroud)
而不是实际的反应.请告诉我出错的地方或更简单的方法.
spi*_*man 19
该参数patch需要描述对象的位置,而不是对象本身.所以你的问题看起来可能只是你需要将你的参数字符串化patch.
但是,为了完整起见,这是一个完全有效的例子.首先,我们正在测试的模块:
# mod_a.py
import urllib2
def myfunc():
opened_url = urllib2.urlopen()
return opened_url.read()
Run Code Online (Sandbox Code Playgroud)
现在,设置我们的测试:
# 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()
Run Code Online (Sandbox Code Playgroud)
从shell运行测试:
$ python test.py
resp1
resp2
Run Code Online (Sandbox Code Playgroud)
编辑:哎呀,最初包括原始错误.(正在测试以验证它是如何被破坏的.)现在应该修复代码.