You are fixing the wrong things: see Where to fix .
In api.py on
from urllib2 import urlopen from urllib2 import Request
you create a local link to urlopen and Request in your file. In mock.patch('urllib2.urlopen') you fix the original link and leave api.py untouched.
So replace your patches with
@mock.patch('api.Request') @mock.patch('api.urlopen')
should fix your problem .... but this is not enough.
In the test case, api.Request not used, but urllib2.urlopen() create Request using the fixed version: this is why Request().get_type() is MagicMock .
For a full fix, you must completely change your test. First code:
@mock.patch('api.urlopen', autospec=True) def test_call_api(self, urlopen): urlopen.return_value.read.return_value = 'mocked' _api = API() self.assertEqual(_api.call_api('https://google.com'), 'mocked') urlopen.assert_called_with('https://google.com')
Now clarification ... In your test, you do not call Request() because you only pass the first parameter, so I removed the useless patch. In addition, you are fixing the urlopen function, not the urlopen object, which means that the read() method you want to taunt is the method to return the urlopen() object.
Finally, I add a check to urlopen and autospec=True , which is always good practice.
source share