当使用变量引用时间时,冻结时间测试用例失败

2024-04-26 13:52:30 发布

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

我正在使用freeze-time运行我的python unittest测试用例

虚拟测试用例:

@freeze_time('2020-01-01')
def test_something(self):
  expected_output = {'time': '2020-01-01'}

  output = call_tested_code()

  self.assertEqual(expected_output, output)

主代码/正在测试的代码:

GET_CURRENT_TIME = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')

def call_tested_code():
  return {'time': GET_CURRENT_TIME}

这是失败的,因为输出给出的是当前_日期而不是冻结日期。 它在GET_CURRENT_TIME是lambda时工作,但这会导致代码的时间戳不同,这是我不想要的

如果需要任何其他信息,请随时发表评论。谢谢


Tags: 代码selfoutputgettimedef测试用例code
1条回答
网友
1楼 · 发布于 2024-04-26 13:52:30

测试代码是在测试函数之前导入的,因此GET_CURRENT_TIME是在freeze_time之前计算的,这就是问题所在

要解决是在测试函数中导入call_tested_code,还是将其放入lambda或其他可调用函数中,如您所述

@freeze_time('2020-01-01')
def test_something(self):
    from package import call_tested_code # edit here with your correct import
    expected_output = {'time': '2020-01-01'}
    output = call_tested_code()
    self.assertEqual(expected_output, output)

另外,我认为您应该将预期的输出更改为datetime字符串,而不仅仅是date,因为您的GET_CURRENT_TIME使用这种格式'%Y-%m-%d %H:%M:%S'

相关问题 更多 >