gpt4 book ai didi

python - 如何模拟Python中的模块但不是所有方法

转载 作者:行者123 更新时间:2023-12-01 07:16:15 24 4
gpt4 key购买 nike

我有一个这样模拟的测试:

@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]

问题是数据有一个 created_at 字段,其中包含 MagicMock 对象而不是日期字符串。如何模拟 utcnow 方法而不是 strptimestrftime 方法?

最佳答案

您可以创建一个 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):
...

演示:https://repl.it/repls/DarkmagentaTwinDebugmonitor

关于python - 如何模拟Python中的模块但不是所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57928564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com