python - Python 单元测试中具有可变值的字典?

标签 python unit-testing

我需要为返回字典的函数编写单元测试。此字典中的值之一是 datetime.datetime.now(),它当然会随着每次测试运行而变化。

我想在我的断言中完全忽略那个键。现在我有一个字典比较功能,但我真的想像这样使用 assertEqual:

def my_func(self):
    return {'monkey_head_count': 3, 'monkey_creation': datetime.datetime.now()}

... unit tests

class MonkeyTester(unittest.TestCase):
    def test_myfunc(self):
        self.assertEqual(my_func(), {'monkey_head_count': 3}) # I want to ignore the timestamp!

这样做有什么最佳实践或优雅的解决方案吗?我知道 assertAlmostEqual(),但这只对 float iirc 有用。

最佳答案

在进行比较之前,只需从字典中删除时间戳:

class MonkeyTester(unittest.TestCase):
    def test_myfunc(self):
        without_timestamp = my_func()
        del without_timestamp["monkey_creation"]
        self.assertEqual(without_timestamp, {'monkey_head_count': 3})

如果您发现自己在做很多涉及 datetime.now() 的时间相关测试,那么您可以为单元测试修补 datetime 类。考虑一下

import datetime
constant_now = datetime.datetime(2009,8,7,6,5,4)
old_datetime_class = datetime.datetime
class new_datetime(datetime.datetime):
    @staticmethod
    def now():
        return constant_now

datetime.datetime = new_datetime

现在,每当您在单元测试中调用 datetime.datetime.now() 时,它总是会返回 constant_now 时间戳。如果你想/需要切换回原来的 datetime.datetime.now() 那么你可以简单地说

datetime.datetime = old_datetime_class

一切都会恢复正常。这种事情可能很有用,但在您给出的简单示例中,我建议在比较之前从字典中删除时间戳。

关于python - Python 单元测试中具有可变值的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1049551/

相关文章:

python - 多种选择的列与 pandas 数据框的智能合并

python -mysqldb : How to efficiently get millions/billions of records from database?

Python:如何迭代多个具有相似名称的文件(每个名称的变化是日期)?

python - 在 Numpy 中沿轴减少多维字符串数组

visual-studio - Visual Studio 测试项目

python - python中的正则表达式 *

visual-studio - 确定哪些类最能从单元测试中受益?

c# - 断言字符串数组成员内容

angularjs - Protractor 不从自动完成搜索地址中选择第一个元素

c# - 创建单元测试以确保不变性