Emmett J. Butler Emmett J. Butler - 1 year ago 101
Python Question

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

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

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

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

Answer Source

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'}