使用Python Mock模拟模块.__ dict__

时间:2017-05-04 22:03:46

标签: python mocking python-unittest

如果不是模拟模块中的函数,我想模拟模块的__dict__属性,我该怎么做呢?显然像

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

不起作用

1 个答案:

答案 0 :(得分:3)

您应该可以使用patch.dict

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

这可以用作装饰器,上下文管理器或独立对象,就像任何其他补丁调用一样。

>>> # 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