python单元测试问题模拟pytz获取本地时间

2024-03-29 10:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图为这个函数编写一个单元测试

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> 

我不知道如何模拟它,或者至少验证datetime是否正确。我试着模仿皮茨,但没能成功。此外,无法理解如何模拟timezone.utc

任何帮助都会很好。谢谢


Tags: fromimportdatetimetimelocaldef单元测试current
1条回答
网友
1楼 · 发布于 2024-03-29 10:45:57

要使您的价值不受时区的影响,您可以

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)

相关问题 更多 >