为`mock.patch`制作一个包装器

时间:2016-10-30 23:35:29

标签: python testing mocking python-mock

来自mock.patch的一些自定义补丁我想反复使用,而不会乱丢我的测试代码和补丁设置的副本。例如this very handy patch of datetime.date,适用于日期时间,将用

填充我的代码
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)

如何将此功能包装成单线呼叫?

2 个答案:

答案 0 :(得分:0)

这是一个资源管理器类,可以为您完成这项工作。由于您可能希望将其放在与测试类不同的文件中,因此它使用inspect来查找调用模块,以便它可以将正确限定的目标模块名称传递给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)

答案 1 :(得分:0)

@brandones提供的解决方案非常好!但是我发现如果您省去检查的话,它会更容易使用:

# testhelpers.py
import unittest.mock as mock
import datetime

class MockDatetime():
    def __init__(self, target, utcnow):
        self.utcnow = utcnow
        self.target = target

    def __enter__(self):
        self.patcher = mock.patch(self.target)
        mock_dt = self.patcher.start()
        mock_dt.datetime.utcnow.return_value = self.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()


# testhelpers_test.py
import datetime
from testhelpers import MockDatetime

def test__mock_datetime():
    with MockDatetime('testhelpers_test.datetime', datetime.datetime(2019, 4, 29, 9, 10, 23, 1234)):
        assert datetime.datetime.utcnow() == datetime.datetime(2019, 4, 29, 9, 10, 23, 1234)