问题描述
mock.patch
中的一些自定义补丁程序,我想一遍又一遍地使用,而不会在补丁程序设置的复制粘贴中乱丢我的测试代码.例如 datetime.date
的这一非常方便的补丁,该补丁适用于日期时间,将用我的代码填充
Some customized patches from mock.patch
I want to use over and over without littering my test code with copy-pastes of the patch setup. e.g. this very handy patch of datetime.date
, which, adapted for datetime, would fill my code with
with patch('mymodule.datetime') as mock_datetime:
mock_datetime.datetime.utcnow.return_value = datetime.datetime(2010, 10, 8, 9, 10)
mock_date.datetime.side_effect = lambda *args, **kw: datetime.datetime(*args, **kw)
如何将此功能包装到单线呼叫中?
How can I wrap this functionality into a one-line call?
推荐答案
这里是一个资源管理器类,它将为您完成此任务.由于您可能希望将其放在与测试类不同的文件中,因此它使用inspect
查找调用模块,以便可以将正确限定的目标模块名称传递给mock.patch
.
Here's a resource manager class that will do that for you. Since you might want to put it in a separate file from your test classes, it uses inspect
to look up the calling module, so that it can pass the correctly qualified target module name to mock.patch
.
import datetime
import inspect
# import mock according to your python version
class mock_datetime(object):
def __init__(self, target, new_utcnow):
self.new_utcnow = new_utcnow
self.target = target
def __enter__(self):
calling_module = inspect.getmodule(inspect.stack()[1][0])
target_from_here = calling_module.__name__ + '.' + self.target
self.patcher = mock.patch(target_from_here)
mock_dt = self.patcher.start()
mock_dt.datetime.utcnow.return_value = self.new_utcnow.replace(tzinfo=None)
mock_dt.datetime.side_effect = lambda *args, **kw: datetime.datetime(*args, **kw)
return mock_dt
def __exit__(self, *args, **kwargs):
self.patcher.stop()
然后您可以使用
with mock_datetime('mymodule.datetime', datetime.datetime(2016, 3, 23)):
assert mymodule.datetime.datetime.utcnow() == datetime.datetime(2016, 3, 23)
这篇关于为`mock.patch`做一个包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!