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?
There are several common ways to use doctest: To check that a module's docstrings are up-to-date by verifying that all interactive examples still work as documented. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.
To run the tests, use doctest as the main program via the -m option to the interpreter. Usually no output is produced while the tests are running, so the example below includes the -v option to make the output more verbose.
The doctest module programmatically searches Python code for pieces of text within comments that look like interactive Python sessions. Then, the module executes those sessions to confirm that the code referenced by a doctest runs as expected.
Another good way is to use pprint
(in the standard library).
>>> import pprint >>> pprint.pprint({"second": 1, "first": 0}) {'first': 0, 'second': 1}
According to its source code, it's sorting dicts for you:
http://hg.python.org/cpython/file/2.7/Lib/pprint.py#l158
items = _sorted(object.items())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With