谁能告诉我为什么这行不通?
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
也许有人能提出一个更好的办法?
谁能告诉我为什么这行不通?
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
也许有人能提出一个更好的办法?
当前回答
几天前我遇到了同样的情况,我的解决方案是在模块中定义一个函数来测试和模拟:
def get_date_now():
return datetime.datetime.now()
今天我发现了《FreezeGun》,它似乎很好地解决了这个问题
from freezegun import freeze_time
import datetime
import unittest
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
其他回答
monkeypatch的最小工作示例
这个解决方案使用https://pypi.org/project/pytest-mock/包中的monkeypatch。
特点:
仅模拟datetime.today(),但datetime.now()仍然可以正常工作 仅在特定范围内模拟(即块)
import sys
from datetime import datetime
MOCKED_DATETIME_TODAY = datetime(1900, 1, 1, 0, 0, 0)
class MockedDatetime(datetime):
@classmethod
def today(cls):
return MOCKED_DATETIME_TODAY
def test_mock_datetime_today(monkeypatch):
"""Only datetime.today() is mocked and returns some date in 1900. datetime.now() returns still the current date."""
with monkeypatch.context() as mpc:
mpc.setattr(sys.modules[__name__], 'datetime', MockedDatetime)
assert datetime.today() == MOCKED_DATETIME_TODAY # datetime.today() mocked
assert datetime.now() > MOCKED_DATETIME_TODAY # datetime.now() not mocked
assert datetime.today() > MOCKED_DATETIME_TODAY # not mocked anymore
对我来说最简单的方法是:
import datetime
from unittest.mock import Mock, patch
def test():
datetime_mock = Mock(wraps=datetime.datetime)
datetime_mock.now.return_value = datetime.datetime(1999, 1, 1)
with patch('datetime.datetime', new=datetime_mock):
assert datetime.datetime.now() == datetime.datetime(1999, 1, 1)
注意:target_module中的datetime模块中的所有功能都将停止工作。
我通过将datetime导入为realdatetime并将我在模拟中需要的方法替换为实际方法来完成这项工作:
import datetime as realdatetime
@mock.patch('datetime')
def test_method(self, mock_datetime):
mock_datetime.today = realdatetime.today
mock_datetime.now.return_value = realdatetime.datetime(2019, 8, 23, 14, 34, 8, 0)
另一种选择是使用 https://github.com/spulec/freezegun/
安装:
pip install freezegun
并使用它:
from freezegun import freeze_time
@freeze_time("2012-01-01")
def test_something():
from datetime import datetime
print(datetime.now()) # 2012-01-01 00:00:00
from datetime import date
print(date.today()) # 2012-01-01
它还会影响其他模块的方法调用中的其他datetime调用:
other_module.py:
from datetime import datetime
def other_method():
print(datetime.now())
main.py:
from freezegun import freeze_time
@freeze_time("2012-01-01")
def test_something():
import other_module
other_module.other_method()
最后:
$ python main.py
# 2012-01-01
对于那些在测试类中使用补丁程序的人,下面是我如何成功地修补datetime功能:
from datetime import datetime
import unittest
from unittest.mock import Mock, patch
# Replace with the proper path to the module you would
# like datetime to be mocked
from path.to.my_module
class MyTestCases(unittest.TestCase):
def setUp(self):
"""execute on class instantiation"""
# Record both times at the same moment
self.dt_now, self.dt_utcnow = datetime.now(), datetime.utcnow()
# After retrieving real (or hardcoded datetime values),
# proceed to mock them in desired module
self.patch_datetime_functions()
def patch_datetime_functions(self) -> None:
"""
Patch datetime.now() and datetime.utcnow() to prevent issues when
comparing expected dates
"""
# Create a patcher
self.patcher_dt = patch(
'path.to.my_module'
)
# Start but make sure cleanup always occurs
self.patcher_dt.start()
self.addCleanup(self.patcher_dt.stop)
# Perform the actual patch – use lambdas as mock functions
datetime_mock = Mock(wraps=datetime)
datetime_mock.now.return_value = self.dt_now
datetime_mock.utcnow.return_value = self.dt_utcnow
my_module.datetime = datetime_mock
# Here's what it will look like when testing:
def some_test(self):
curr_dt = self.dt_now
returned_dt = my_module.datetime.utcnow()
# Compare the dates
self.assertEqual(curr_dt, returned_dt,
'Datetime values should be equal'
)