Emm*_*ler 37 python doctest dictionary
我正在为输出字典的函数编写doctest.doctest看起来像
>>> my_function()
{'this': 'is', 'a': 'dictionary'}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它失败了
Expected:
{'this': 'is', 'a': 'dictionary'}
Got:
{'a': 'dictionary', 'this': 'is'}
Run Code Online (Sandbox Code Playgroud)
我对这个失败原因的最好猜测是doctest不是检查字典的平等,而是检查__repr__平等.这篇文章表明有一些方法可以欺骗doctest来检查字典的相同性.我怎样才能做到这一点?
cha*_*lax 39
另一个好方法是使用pprint(在标准库中).
>>> import pprint
>>> pprint.pprint({"second": 1, "first": 0})
{'first': 0, 'second': 1}
Run Code Online (Sandbox Code Playgroud)
根据其源代码,它为您排序:
http://hg.python.org/cpython/file/2.7/Lib/pprint.py#l158
items = _sorted(object.items())
Run Code Online (Sandbox Code Playgroud)
Cla*_*diu 24
Doctest不检查__repr__相等性,它本身只是检查输出是否完全相同.您必须确保打印的内容与同一字典的内容相同.你可以用这个单线程做到这一点:
>>> sorted(my_function().items())
[('a', 'dictionary'), ('this', 'is')]
Run Code Online (Sandbox Code Playgroud)
虽然您的解决方案的这种变化可能更清晰:
>>> my_function() == {'this': 'is', 'a': 'dictionary'}
True
Run Code Online (Sandbox Code Playgroud)
Emm*_*ler 13
我最终使用了这个.哈基,但它的工作原理.
>>> p = my_function()
>>> {'this': 'is', 'a': 'dictionary'} == p
True
Run Code Online (Sandbox Code Playgroud)