Skip to content Skip to sidebar Skip to footer

Python Mock With `from X Import Y`

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

Solution 1:

According to Where to patchunittest.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').

Post a Comment for "Python Mock With `from X Import Y`"