How do I test dictionary-equality with Python's doctest-package?

前端 未结 7 1498
眼角桃花
眼角桃花 2020-12-09 07:15

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

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


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 08:13

    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
    

提交回复
热议问题