如何使用Python的doctestpackage测试dictionaryequality?

2024-05-19 19:28:58 发布

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

我正在为输出字典的函数编写一个doctest。医生看起来像

>>> my_function()
{'this': 'is', 'a': 'dictionary'}

当我运行它时,它失败了

Expected:
    {'this': 'is', 'a': 'dictionary'}
Got:
    {'a': 'dictionary', 'this': 'is'}

对于这个失败的原因,我最好的猜测是doctest没有检查字典的相等性,而是检查__repr__相等性。This post表示有某种方法可以诱使doctest检查字典的相等性。我该怎么做?


Tags: 函数dictionary字典ismy原因functionthis
3条回答

Doctest不检查__repr__相等性,它只检查输出是否完全相同。你必须确保同一本字典所印的东西是一样的。你可以用这一行:

>>> sorted(my_function().items())
[('a', 'dictionary'), ('this', 'is')]

尽管您的解决方案中的这种变化可能更清晰:

>>> my_function() == {'this': 'is', 'a': 'dictionary'}
True

我最后用了这个。很老套,但很管用。

>>> p = my_function()
>>> {'this': 'is', 'a': 'dictionary'} == p
True

另一个好方法是使用pprint(在标准库中)。

>>> import pprint
>>> pprint.pprint({"second": 1, "first": 0})
{'first': 0, 'second': 1}

根据它的源代码,它正在为您排序命令:

http://hg.python.org/cpython/file/2.7/Lib/pprint.py#l158

items = _sorted(object.items())

相关问题 更多 >