gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:23:12 37 4
gpt4 key购买 nike

我正在尝试以某种方式模拟 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_to_be_tested 在第一次调用时获得值“response1”,在第二次调用时获得值“response2”,这就是 side_effect 的作用

但是 othermodule.function_to_be_tested() 接收

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

而不是实际响应。请建议我哪里出错了或更简单的方法。

最佳答案

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

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

关于python - 为不同的响应模拟 urllib2.urlopen().read(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203627/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com