Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 561
Emmett Butler Avatar asked Mar 21 '13 13:03

Emmett Butler


People also ask

Can doctest be used to test docstrings?

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.

How do I run a doctest from command line?

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.

How does doctest work Python?

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.


1 Answers

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()) 
like image 121
charlax Avatar answered Sep 18 '22 22:09

charlax