我是Python的新手。我试图模拟datetime.datetime.now(),但它不起作用:
class Myclass:
def update(self):
time = datetime.datetime.now().strftime("%s")
...上面的函数位于mypackage/my_class.py中
在按如下方式编写测试时,取自本文(Trying to mock datetime.date.today(), but not working)的想法:
@patch('mypackage.my_class.Myclass.datetime')
def test_update(self, datetime_mock):
datetime_mock.datetime.now.return_value=datetime.datetime(2020,1,1,1,1,1,1)我得到的错误如下:
E AttributeError: <class 'mypackage.my_class.Myclass'> does not have the attribute 'datetime'然后我更改了补丁,如下所示:
@patch('datetime')
def test_update(self, datetime_mock):
datetime_mock.datetime.now.return_value=datetime.datetime(2020,1,1,1,1,1,1)现在我得到的错误如下:
venv/lib/python3.6/site-packages/mock/mock.py:1591: in _get_target
target, attribute = target.rsplit('.', 1)
E ValueError: not enough values to unpack (expected 2, got 1)
E TypeError: Need a valid target to patch. You supplied: 'datetime'发布于 2020-03-11 17:48:00
您可以从freezegun模块使用freeze_time。在此测试中,我修改了update()以创建日期时间字符串以提高可读性
class MyClass:
def update(self):
self.time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")from freezegun import freeze_time
class TestMyClass:
@freeze_time("2020-03-01 12:31")
def test_update(self):
my_class = MyClass()
my_class.update()
assert my_class.time == "2020-03-01 12:31"希望这能有所帮助!
发布于 2020-03-11 17:59:05
在您的第一个示例中,您试图模拟不存在的对象。您的Myclass没有datetime。您想要模拟内置的datetime,因此第二种方法是好的,但是您试图模拟整个包,而AFAIK是不可能的。我也不确定你是否可以在测试中模拟一个对象并同时使用它,除非你使用上下文管理器,所以我的解决方案是:
from unittest.mock import patch, MagicMock
def test_update():
expected_datetime = datetime.datetime(2020, 1, 1, 1, 1, 1, 1)
with patch.object(datetime, 'datetime') as datetime_mock:
datetime_mock.now.return_value = expected_datetime
# ...calls to the code you test and assertions...https://stackoverflow.com/questions/60632193
复制相似问题