Python Mock with `from X import y`

2020-05-06 12:24发布

问题:

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

回答1:

According to Where to patch unittest.mock documentation you should pay some attention about what you patch.

Use

from requests import get

create a local reference (a copy) of the original method. By

with mock.patch('requests.get') as get_mock:

you patch just the reference in requests module that give to you so called inconsistent results because the local reference created by from sentence remain untouched.

The local reference can be patched by patch.object(get) or patch('__main__.get').