【发布时间】:2013-03-21 13:51:16
【问题描述】:
我正在为输出字典的函数编写文档测试。 doctest 看起来像
>>> my_function()
{'this': 'is', 'a': 'dictionary'}
当我运行它时,它失败了
Expected:
{'this': 'is', 'a': 'dictionary'}
Got:
{'a': 'dictionary', 'this': 'is'}
我对这次失败原因的最佳猜测是 doctest 不是检查字典相等性,而是检查__repr__ 相等性。 This post 表示有某种方法可以欺骗 doctest 检查字典是否相等。我该怎么做?
【问题讨论】:
-
因为 dict 是无序的,所以不能按原样使用 dict。您必须将其转换为有序对象
-
下面列出的答案都在doctest文档中:docs.python.org/2/library/doctest.html#warnings
-
@ornoone 但是为什么呢?它们是相等的对象,这就是 doctest 应该检查的内容。
-
正如在接受的答案中所说,检查的是您的两个对象的 repr,而不是它们的内容。因为
repr(a) != repr(b)doctest 认为你的对象是不同的。如果a == b正常,则事件。我认为之所以如此,是因为 doctest 在 doc 中,并且应该易于阅读,并且通过 repr 检查,它是可读的。
标签: python dictionary doctest