如何使用Python的doctest-package测试字典相等性?

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)

  • 它会很好,但是python devs [不建议这样](https://bugs.python.org/issue20310),因为它们不保证版本之间的pprint稳定性. (8认同)

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)

  • 您的解决方案更清晰,但无法告诉您my_function实际评估的内容. (3认同)

Emm*_*ler 13

我最终使用了这个.哈基,但它的工作原理.

>>> p = my_function()
>>> {'this': 'is', 'a': 'dictionary'} == p
True
Run Code Online (Sandbox Code Playgroud)

  • 为什么不``my_function()== {'this':'是','a':'词典'}`? (5认同)
  • 我不认为那是hacky(虽然我会写'p == {etc}`) - 这是[docs]相关部分中的第一个推荐技术(http://docs.python.org/3 /library/doctest.html#warnings). (3认同)
  • 这里的缺点是一旦断言失败,你不知道哪些键、值到底是错误的。使用“pprint”的解决方案将显示有用的差异。 (2认同)