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
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
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(urllib2.urlopen)directly.. - Martijn Pieters♦urllib.urlopenat all; e.g. it would be callingself.urlopen_fnwhose default value isurllib.urlopenbut which you can just set toyour_mock_urlopenduring testing; it can even be a module-level parameter you can set from the outside. - Erik Kaplunurllib2, so bothothermodule.urllib2.urlopenandurllib2.urlopenrefer to the exact same function object. - Martijn Pieters♦