简体   繁体   English

带有时间戳的函数的Python单元测试

[英]Python unit test for a function that has timestamp

In a unit test for a function that outputs timestamp and say hostname on it along with other values. 在对输出时间戳并在其上说出主机名以及其他值的功能的单元测试中。 In the unit test if i add some timestamp and a hostname in expected output it will fail as the timestamp from the function will change every time the function is called and the hostname will change every time it is run in a different machine. 在单元测试中,如果我在预期输出中添加一些时间戳和主机名,它将失败,因为每次调用该函数时函数的时间戳都会更改,并且每次在不同的机器上运行时主机名都会更改。 What is the workaround for this? 解决方法是什么? I'd appreciate your input. 非常感谢您的投入。

output from a function: 函数的输出:

{'datetime': '09-10-2018 23:23:23', 'hostname': 'abc.xyz.com',...}
# and it can change every time we run it

but this datetime and hostname changes depending on time, of course, and machine 但是此日期时间和主机名会根据时间,当然和机器而变化

expected output that i think i will use in unit test to assertEqual or assertDictEqual: 我认为我将在单元测试中使用assertEqual或assertDictEqual的预期输出:

{'datetime': '09-10-2018 23:23:23', 'hostname': 'abc.xyz.com',...}

Is some other assertion check better suited for this situation? 其他断言检查是否更适合这种情况?

You should mock the datetime.now() call, wherever it happens, so that the creation datetime is always some canned value which you can assert against during the test. 无论发生在何处,都应该模拟datetime.now()调用,以便创建datetime始终是一些固定值,您可以在测试期间对其进行断言。

This is a common requirement, so there is some library support for it already - I can recommend freezegun : 这是一个常见的要求,因此已经有一些库支持-我可以推荐Frozengun

@freeze_time("09-10-2018 23:23:23")
def test_something():
    data = something()
    assert data == {'datetime': '09-10-2018 23:23:23', 'hostname': 'abc.xyz.com',...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM