I am trying to use Python's mock
library in my unit testing but I am seeing inconsistent results depending on how I import the target that I am trying to patch. I would expect that both of these print statements should return False
but it appears that only the second statement returns False
:
from requests import get
import requests
with mock.patch('requests.get') as get_mock:
get_mock.return_value.ok = False
print get('http://asdf.com').ok
print requests.get('http://asdf.com').ok
According to Where to patch
unittest.mock
documentation you should pay some attention about what you patch.Use
create a local reference (a copy) of the original method. By
you patch just the reference in
requests
module that give to you so called inconsistent results because the local reference created byfrom
sentence remain untouched.The local reference can be patched by
patch.object(get)
orpatch('__main__.get')
.