Python Mock with `from X import y`

瘦欲@ 提交于 2019-12-20 05:51:33

问题


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').



来源:https://stackoverflow.com/questions/28546137/python-mock-with-from-x-import-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!