Handling dictionaries and sets in doctest examples
We will look at one small aspect of writing a proper test in this recipe. We'll look at testing overall in Chapter 9, Testing. The data structures in this chapter—dict
and set
—both include some complexity when it comes to writing proper tests.
Since dict
keys (and set
members) have no order, our test results will have a problem. We need to have a repeatable result, but there's no way to guarantee the order of the collection. This can lead to test results which don't properly match our expectations.
Assume that our test expects the set {"Poe", "E", "Near", "A", "Raven"}
. Since there's no defined order to a set, Python can display this set in any order:
>>> {"Poe", "E", "Near", "A", "Raven"}
{'E', 'Poe', 'Raven', 'Near', 'A'}
The elements are the same, but the overall line of output from Python isn't the same. The doctest
package relies on the literal output from the example being identical to the output produced by Python's REPL...