Python:如何模拟 datetime.utcnow()?

2022-01-08 00:00:00 python mocking unit-testing

问题描述

我有以下内容:

from datetime import datetime

def get_report_month_key():
    month_for_report = datetime.utcnow()
    return month_for_report.strftime("%Y%m") 

我如何模拟 datetime.utcnow() 以便我可以在这个函数上编写单元测试?

How do I mock datetime.utcnow() so that I can write unit test on this function?

尝试阅读此一个但是我无法让它在 utcnow() 上为我工作

Tried reading this one but I am unable to get it working for me on utcnow()


解决方案

在你的测试文件中:

from yourfile import get_report_month_key
import mock
import unittest
from datetime import datetime

class TestCase(unittest.TestCase):

    @mock.patch('yourfile.datetime')
    def test_dt(self, mock_dt):
        mock_dt.utcnow = mock.Mock(return_value=datetime(1901, 12, 21))
        r = get_report_month_key()
        self.assertEqual('190112', r)

相关文章