Mocking urllib2.urlopen (). Read () for different answers

I am trying to make fun of the urllib2.urlopen library in such a way that I need to get different answers for different URLs that I pass to the function.

The way I do this in my test file is as follows

@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 

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

but othermodule.function_to_be_tested () gets

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

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

+6
source share
1 answer

The patch argument must be a description of the location of the object, not the object itself. So your problem looks like you just need to argue for the patch argument.

Just for completeness though, here is a complete working example. Firstly, our test module:

 # mod_a.py import urllib2 def myfunc(): opened_url = urllib2.urlopen() return opened_url.read() 

Now configure 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() 

Running a test from the shell:

 $ python test.py resp1 resp2 

Edit : Oops, originally including the original error. (Checked how it was broken.) The code should be fixed.

+12
source

Source: https://habr.com/ru/post/955324/


All Articles