【问题标题】:python unit test issues mocking pytz getting local timepython单元测试问题嘲笑pytz获取当地时间
【发布时间】:2020-07-30 09:46:23
【问题描述】:

我目前正在尝试为 this_function 编写单元测试

from unittest.mock import MagicMock, patch, call
from datetime import datetime, timezone, tzinfo

def this_function(utc_current_time):
    cst_time = pytz.timezone("US/Central")
    local_current_time = utc_current_time.astimezone(cst_time)
    return local_current_time

我的单元测试

    def test_get_local_time_for_afterhour_check(self, mock_pytz, mock_datetime):
        utc_current_time = datetime(2020, 4, 16, 16, 22, 32, tzinfo=timezone.utc)

        actual = main.get_local_time_afterhour_emr_check(utc_current_time)
        expected = datetime(2020, 4, 16, 11, 22, 32)

        self.assertEqual(actual, expected)

我遇到的问题是日期是正确的,但实际上还有我从 pytz 猜测的额外内容

  datetime(2020, 4, 16, 11, 22, 32,tzinfo=<DstTzInfo 'US/Central' CDT-1 day, 19:00:00 DST> 

我不知道如何模拟它或至少验证日期时间是否正确。我尝试嘲笑 pytz 但我无法让它发挥作用。另外,不知道如何模拟 timezone.utc

任何帮助都会很棒。谢谢

【问题讨论】:

    标签: python unit-testing datetime mocking pytz


    【解决方案1】:

    为了让您的价值不受时区影响,您可以

    actual = this_function(utc_current_time).replace(tzinfo=None)
    

    或者,您可以设置预期的时区

    expected = datetime(2020, 4, 16, 11, 22, 32)
    cst_time = pytz.timezone("US/Central")
    expected = cst_time.localize(expected)
    

    【讨论】:

      猜你喜欢
      • 2015-06-06
      • 2021-12-15
      • 2010-11-26
      • 2016-09-12
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      相关资源
      最近更新 更多