我需要为返回字典的函数编写单元测试。此字典中的值之一是 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/