@pytest.mark.parametrize("test_input,expected_output", data)
def test_send_email(test_input, expected_output):
emails = SendEmails(email_client=MagicMock())
emails.send_email = MagicMock()
emails.send_new_email(*test_input)
emails.send_email.assert_called_with(*expected_output)
我正在寻找在 send_new_email 方法中调用的模拟 datetime.datetime.now()。但是我不确定该怎么做。
我尝试创建一个新的日期时间对象
datetime_object = datetime.datetime.strptime('Jun 1 2017 1:33PM',
'%b %d %Y %I:%M%p')
然后覆盖 datetime.datetime.now
datetime.datetime.now = MagicMock(return_value=datetime_object)
但是,我得到了错误
TypeError: can't set attributes of built-in/extension type 'datetime.datetime'
这个问题被标记为 Python 的副本:Trying to mock datetime.date.today() but not working
Python: Trying to mock datetime.date.today() but not working
我已经尝试过这个解决方案,但我无法让它发挥作用。由于项目要求,我无法安装 freezegun。
我在测试文件中创建了一个新类
class NewDate(datetime.date):
@classmethod
def today(cls):
return cls(2010, 1, 1)
datetime.date = NewDate
但我不知道如何让 SendEmails 类使用它。
最佳答案
你可以替换整个类(class):
_FAKE_TIME = 0
class _FakeDateTime(datetime.datetime):
@staticmethod
def now():
return _FAKE_TIME
然后使用它:
_FAKE_TIME = whatever
datetime.datetime = _FakeDateTime
该类需要一些改进,例如比较运算符,以使 FakeDateTime 可与日期时间进行比较,但它应该可以工作。
关于python - 单元测试时模拟 datetime.datetime.now(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413871/