模拟urllib2.urlopen().read()以获得不同的响应 [英] Mocking urllib2.urlopen().read() for different responses

查看:320
本文介绍了模拟urllib2.urlopen().read()以获得不同的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟urllib2.urlopen库,以便针对传递到函数中的不同网址获得不同的响应.

I am trying to mock the urllib2.urlopen library in a way that I should get different responses for different urls I pass into the function.

我现在在测试文件中执行此操作的方式是这样的

The way I am doing it in my test file now is like this

@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的作用

I expect the the othermodule.function_to_be_tested to get the value "response1" on first call and "response2" on second call which is what side_effect will do

但是othermodule.function_to_be_tested()接收

but the othermodule.function_to_be_tested() receives

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

,而不是实际响应.请提出我要去哪里的错误或更简单的方法来做到这一点.

and not the actual response. Please suggest where I am going wrong or an easier way to do this.

推荐答案

patch的参数必须是对象的位置的描述,而不是对象 itself .因此,您的问题看起来可能只是您需要将参数字符串化为patch.

The argument to patch needs to be a description of the location of the object, not the object itself. So your problem looks like it may just be that you need to stringify your argument to patch.

不过,仅出于完整性考虑,这是一个完整的示例.首先,我们的模块正在测试:

Just for completeness, though, here's a fully working example. First, our module under test:

# mod_a.py
import urllib2

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

现在,设置我们的测试:

Now, set up our test:

# 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()

从外壳运行测试:

$ python test.py
resp1
resp2

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

Edit: Whoops, initially included the original mistake. (Was testing to verify how it was broken.) Code should be fixed now.

这篇关于模拟urllib2.urlopen().read()以获得不同的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆