简体   繁体   中英

Mock module.__dict__ using Python Mock

If instead of mocking a function from a module, I want to mock the __dict__ attribute of the module, how would I go about doing that? Obviously something like

@patch(my_module.__dict__)
test_something(my_module_dict):
    my_module_dict.return_value = "something"

does not work

You should be able to use patch.dict

patch.dict(my_module.__dict__, {'new': value})

This can be used as a decorator, context manager or as a stand-alone object just like any other patch call.

>>> # Use `os` as a demo module to patch.
>>> import os
>>> import mock
>>> p = mock.patch.dict(os.__dict__, {'foo': 'bar'}, clear=False)
>>> p.start()
>>> # Look mom, we've added a "foo" object.  We could also overwrite
>>> # functions already in `os` this way.
>>> os.foo
'bar'
>>> # os.path should still exist since we didn't pass clear=True
>>> os.path
<module 'posixpath' from '/Users/mgilson/anaconda/envs/tensorflow-source/lib/python2.7/posixpath.pyc'>
>>> # Stop the patch.
>>> p.stop()
False
>>>
>>>
>>> # Let's try "clear=True" and see what that does.
>>> p = mock.patch.dict(os.__dict__, {'foo': 'bar'}, clear=True)
>>> p.start()
>>> os.foo
'bar'
>>>
>>> # This will fail with an AttributeError because `clear=True`
>>> # removes any attributes that were in the dictionary when you
>>> # started the patch.  Don't worry, they'll get put back when you
>>> # stop the patch...
>>> os.path
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'path'
>>> p.stop()
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM