如何模拟模块而不是Python中的所有方法

时间:2019-09-13 18:18:04

标签: python python-3.x

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

@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方法,而不模拟strptimestrftime方法?

1 个答案:

答案 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):
    ...

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