我有一个模拟这样的测试:
@mock.patch('sources.segment.handler.datetime')
def test_prepare_data(self, mock_datetime):
utc_time_now = datetime(2019, 1, 1, 1, 1, 1, 1)
mock_datetime.utcnow.return_value = utc_time_now
和handler.py
中执行此操作的方法:
def prepare():
....
data["received_at"] = datetime.utcnow().strftime(time_format)[:-3]
data["created_at"] = datetime.strptime(record["receivedAt"], utc_offset_format).strftime(time_format)[:-3]
问题在于数据中有一个带有MagicMock对象而不是日期字符串的created_at
字段。如何模拟utcnow
方法,而不模拟strptime
和strftime
方法?
答案 0 :(得分:1)
您可以创建datetime.datetime
的子类来覆盖utcnow
:
class mock_datetime(datetime):
@classmethod
def utc_now(cls):
return datetime(2019, 1, 1, 1, 1, 1, 1)
以便您可以使用此子类来修补datetime
:
@mock.patch('sources.segment.handler.datetime', mock_datetime)
def test_prepare_data(self):
...