【问题标题】:Python: How I mock datetime.utcnow().isoformat()?Python:我如何模拟 datetime.utcnow().isoformat()?
【发布时间】:2020-03-17 10:54:44
【问题描述】:

我想模拟 datetime.utcnow().isoformat() 以对 python3 烧瓶应用程序进行单元测试。

我已经查看了 Python: How do I mock datetime.utcnow()? 的 StackOverflow 帖子,但无法将其改编为 utcnow().isoformat.()

我尝试编辑以下代码,但没有成功。

import pytest
import unittest
from unittest import mock

def fake_datetime(*args, **kwargs):
    class FakeTime:
        @classmethod
        def utcnow(self):
            return "2020-03-17T10:02:01.285418"
    return Faketime

@mock.patch('app.utils.datetime', side_effect=fake_datetime)
class FlaskRoutesTest(unittest.TestCase):
    def setUp(self):
        self.app = app.create_app().test_client()

    def test_app_route_recovered(self, mock_datetime):
        print(mock_get.utcnow().isoformat())

【问题讨论】:

    标签: python unit-testing datetime mocking


    【解决方案1】:

    您可以使用pytest-freezegun

    代码示例:

    @pytest.mark.freeze_time('2017-05-21')
    def test_current_date():
        assert date.today() == date(2017, 5, 21)
    

    输出

    True
    

    如果您正确配置时间,它应该会显示正确的 ISO 格式时间

    【讨论】:

    • 谢谢,但如果可能的话,我不想调用其他依赖项(pytest-freezegun)。
    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多