如何使用Python的doctest包来测试字典平等? [英] How do I test dictionary-equality with Python's doctest-package?

查看:147
本文介绍了如何使用Python的doctest包来测试字典平等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当我运行它,它失败与

 预期:
{'this':'is' 'a':'dictionary'}
得到:
{'a':'dictionary','this':'is'}

我最好的猜测这个失败的原因是doctest没有检查字典平等,但是 __ repr __ 这篇文章表明有一些方法来欺骗doctest进入检查字典平等。我该怎么做?

解决方案

Doctest不检查 __ repr __ 平等本身,它只是检查输出是完全一样的。您必须确保打印的任何内容与同一个字典相同。您可以使用此单行方式:

 >>> sort(my_function()。items())
[('a','dictionary'),('this','is')]

尽管您的解决方案中的这种变化可能更为简单:

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


I'm writing a doctest for a function that outputs a dictionary. The doctest looks like

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

When I run it, it fails with

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

My best guess as to the cause of this failure is that doctest isn't checking dictionary equality, but __repr__ equality. This post indicates that there's some way to trick doctest into checking dictionary equality. How can I do this?

解决方案

Doctest doesn't check __repr__ equality, per se, it just checks that the output is exactly the same. You have to ensure that whatever is printed will be the same for the same dictionary. You can do that with this one-liner:

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

Although this variation on your solution might be cleaner:

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

这篇关于如何使用Python的doctest包来测试字典平等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆