Learning Python Testing Sample Chapter
Learning Python Testing Sample Chapter
Daniel Arbuckle
Chapter No. 2
"Working with doctest"
Reuse some of the efforts involved in the documentation and test creation
3. We can now run the doctest. At the command prompt, change to the
directory where you saved test.txt. Type the following command:
$ python3 -m doctest test.txt
4. When the test is run, you should see output like this:
[ 12 ]
Chapter 2
Now take a moment to consider before running the test. Will it pass or fail? Should it
pass or fail?
Because we added the new tests to the same file containing the tests from before, we
still see the notification that three times three does not equal 10. Now, though, we
also see that five tests were run, which means our new tests ran and were successful.
Why five tests? As far as doctest is concerned, we added the following three tests to
the file:
The first one says that, when we import sys, nothing visible should happen
The second test says that, when we define the test_write function, nothing
visible should happen
The third test says that, when we call the test_write function, Hello and
True should appear on the console, in that order, on separate lines
[ 14 ]
Chapter 2
Since all three of these tests pass, doctest doesn't bother to say much about them.
All it did was increase the number of tests reported at the bottom from two to five.
Expecting exceptions
That's all well and good for testing that things work as expected, but it is just as
important to make sure that things fail when they're supposed to fail. Put another
way: sometimes your code is supposed to raise an exception, and you need to be
able to write tests that check that behavior as well.
Fortunately, doctest follows nearly the same principle in dealing with exceptions
as it does with everything else; it looks for text that looks like a Python interactive
session. This means it looks for text that looks like a Python exception report and
traceback, and matches it against any exception that gets raised.
The doctest module does handle exceptions a little differently from the way it
handles other things. It doesn't just match the text precisely and report a failure
if it doesn't match. Exception tracebacks tend to contain many details that are
not relevant to the test, but that can change unexpectedly. The doctest module
deals with this by ignoring the traceback entirely: it's only concerned with the first
line, Traceback (most recent call last):, which tells it that you expect an
exception, and the part after the traceback, which tells it which exception you expect.
The doctest module only reports a failure if one of these parts does not match.
This is helpful for a second reason as well: manually figuring out what the traceback
will look like, when you're writing your tests, would require a significant amount of
effort and would gain you nothing. It's better to simply omit them.
The test is supposed to raise an exception, so it will fail if it doesn't raise the
exception or if it raises the wrong exception. Make sure that you have your mind
wrapped around this: if the test code executes successfully, the test fails, because
it expected an exception.
Run the tests using the following doctest:
python3-mdoctesttest.txt
[ 16 ]
Chapter 2
Chapter 2
...
[1,
4,
7,
# doctest: +NORMALIZE_WHITESPACE
2, 3,
5, 6,
8, 9]
spacing.\n")
Skipping an example
On some occasions, doctest will recognize some text as an example to be checked,
when in truth you want it to be simply text. This situation is rarer than it might at first
seem, because usually there's no harm in letting doctest check everything it can. In
fact, usually it's very helpful to have doctest check everything it can. For those times
when you want to limit what doctest checks, though, there's the +SKIP directive.
[ 19 ]
The remaining directives of doctest in the Python 3.4 version are as follows:
<BLANKLINE> feature
Strictly speaking, doctest supports several other options that can be set using
the directive syntax, but they don't make any sense as directives, so we'll ignore
them here.
[ 20 ]
Chapter 2
By doing this, the only thing that ends up in the shared scope is the test function
(named test1 here). The frob module and any other names bound inside the
function are isolated with the caveat that things that happen inside imported
modules are not isolated. If the frob.hash() method changes a state inside the
frob module, that state will still be changed if a different test imports the frob
module again.
The third way is to exercise caution with the names you create, and be sure to set
them to known values at the beginning of each test section. In many ways this is the
easiest approach, but this is also the one that places the most burden on you, because
you have to keep track of what's in the scope.
[ 21 ]
Why does doctest behave in this way, instead of isolating tests from each other?
The doctest files are intended not just for computers to read, but also for humans.
They often form a sort of narrative, flowing from one thing to the next. It would
break the narrative to be constantly repeating what came before. In other words, this
approach is a compromise between being a document and being a test framework,
a middle ground that works for both humans and computers.
The other framework that we will study in depth in this book (called simply
unittest) works at a more formal level, and enforces the separation between tests.
How does doctest recognize the beginning and end of the expected output
of a test?
How would you tell doctest that you want to break the expected output
across several lines, even though that's not how the test actually outputs it?
When you assign a variable in a test file, which parts of the file can actually
see that variable?
Why do we care what code can see the variables created by a test?
How can we make doctest not care what a section of output contains?
[ 22 ]
Chapter 2
I'll give you a hint and point out that the last sentence about the function being slow,
isn't really testable. As computers get faster, any test you write that depends on an
arbitrary definition of "slow" will eventually fail. Also, there's no good way to test
the difference between a slow function and a function stuck in an infinite loop, so
there's not much point in trying. If you find yourself needing to do that, it's best to
back off and try a different solution.
Not being able to tell whether a function is stuck or just slow is
called the halting problem by computer scientists. We know that
it can't be solved unless we someday discover a fundamentally
better kind of computer. Faster computers won't do the trick, and
neither will quantum computers, so don't hold your breath.
The next-to-last sentence also provides some difficulty, since to test it completely
would require running every positive integer through the fib() function, which
would take forever (except that the computer will eventually run out of memory and
force Python to raise an exception). How do we deal with this sort of thing, then?
The best solution is to check whether the condition holds true for a random sample
of viable inputs. The random.randrange() and random.choice() functions in the
Python standard library make that fairly easy to do.
[ 23 ]
When written in docstrings, doctests serve a slightly different purpose. They still let
the computer check that things work as expected, but the humans who see them will
most often be coders who use the Python interactive shell to work on an idea before
committing it to code, or whose text editor pops up docstrings as they work. In that
context, the most important thing a doctest can do is be informative, so docstrings
aren't usually a good place for checking picky details. They're a great place for a
doctest to demonstrate the proper behavior of a common case, though.
The doctests embedded in docstrings have a somewhat different execution scope than
doctests in text files do. Instead of having a single scope for all of the tests in the file,
doctest creates a single scope for each docstring. All of the tests that share a docstring
also share an execution scope, but they're isolated from tests in the other docstrings.
The separation of each docstring into its own execution scope often means that we
don't need to put much thought into isolating doctests when they're embedded
in docstrings. This is fortunate, since docstrings are primarily intended for
documentation, and the tricks required to isolate the tests might obscure the meaning.
Chapter 2
Notice the use of a raw string for the docstring (denoted by the
r character before the first triple quote). Using raw strings for
your docstrings is a good habit to get into, because you usually
don't want escape sequencesfor example, \n for newline to
be interpreted by the Python interpreter. You want them to be
treated as text, so that they are correctly passed on to doctest.
Running these tests is just as easy as running the tests in a doctest document:
python3 -m doctest test.py
Since all the tests pass, the output of this command is nothing at all. We can make it
more interesting by adding the verbose flag to the command line:
python3 -m doctest -v test.py
[ 25 ]
We put the doctest code right inside the docstring of the function it was testing.
This is a good place for tests that also show a programmer how to do something. It's
not a good place for detailed, low-level tests (the doctest in the docstring example
code, which was quite detailed for illustrative purposes, is perhaps too detailed),
because docstrings need to serve as API documentationyou can see the reason for
this just by looking at the example, where the doctests take up most of the room in
the docstring without telling the readers any more than they would have learned
from a single test.
Any test that will serve as good API documentation is a good candidate for including
in the docstrings of a Python file.
You might be wondering about the line that reads 1 items had no tests, and the
following line that just reads test. These lines are referring to the fact that there are
no tests written in the module-level docstring. That's a little surprising, since we didn't
include such a docstring in our source code at all, until you realize that, as far as Python
(and thus doctest) is concerned, no docstring is the same as an empty docstring.
As its name suggests, an AVL tree organizes the keys that are stored in it into a tree
structure, with each key having up to two child keys one child key that is less
than the parent key by comparison, and one that is more. In the following figure,
the Elephant key has two child keys, Goose has one, and Aardvark and Frog both
have none.
[ 26 ]
Chapter 2
The AVL tree is special because it keeps one side of the tree from getting much
taller than the other, which means that users can expect it to perform reliably and
efficiently no matter what. In the following figure, the AVL tree will reorganize to
stay balanced if Frog gains a child:
"Frog"
Lesser
"Aardvark"
"Goose"
Lesser
Greater
"Elephant"
We're going to write tests for an AVL tree implementation here, rather than writing
the implementation itself, so we're going to gloss over the details of how an AVL tree
works, in favor of looking at what it should do when it works right.
If you want to know more about AVL trees, you will
find many good references on the Internet. Wikipedia's
entry on this subject is a good place to start with:
http://en.wikipedia.org/wiki/AVL_tree.
We're going to start with a plain-language specification, and then interject tests
between the paragraphs. You don't have to actually type all of this into a text file;
it is here for you to read and to think about.
English specification
The first step is to describe what the desired result should be, in normal language.
This might be something that you do for yourself, or it might be something that
somebody else does for you. If you're working for somebody, hopefully you and
your employer can sit down together and work this part out.
In this case, there's not much to work out, because AVL trees have been fully
described for decades. Even so, the description here isn't quite like the one you'd find
elsewhere. This capacity for ambiguity is exactly the reason why a plain-language
specification isn't good enough. We need an unambiguous specification, and that's
exactly what the tests in a doctest file can give us.
[ 27 ]
The following text goes in a file called AVL.txt, (that you can find in its final form in
the accompanying code archive; at this stage of the process, the file contains only the
normal language specification):
An AVL Tree consists of a collection of nodes organized in a binary
tree structure. Each node has left and right children, each of which
may be either None or another tree node. Each node has a key, which
must be comparable via the less-than operator. Each node has a value.
Each node also has a height number, measuring how far the node is from
being a leaf of the tree -- a node with height 0 is a leaf.
The binary tree structure is maintained in ordered form, meaning that
of a node's two children, the left child has a key that compares
less than the node's key and the right child has a key that compares
greater than the node's key.
The binary tree structure is maintained in a balanced form, meaning
that for any given node, the heights of its children are either the
same or only differ by 1.
The node constructor takes either a pair of parameters representing
a key and a value, or a dict object representing the key-value pairs
with which to initialize a new tree.
The following methods target the node on which they are called, and
can be considered part of the internal mechanism of the tree:
Each node has a recalculate_height method, which correctly sets the
height number.
Each node has a make_deletable method, which exchanges the positions
of the node and one of its leaf descendants, such that the tree
ordering of the nodes remains correct.
Each node has rotate_clockwise and rotate_counterclockwise methods.
Rotate_clockwise takes the node's right child and places it where
the node was, making the node into the left child of its own former
child. Other nodes in the vicinity are moved so as to maintain
the tree ordering. The opposite operation is performed by rotate_
counterclockwise.
Each node has a locate method, taking a key as a parameter, which
searches the node and its descendants for a node with the specified
key, and either returns that node or raises a KeyError.
The following methods target the whole tree rooted at the current
node. The intent is that they will be called on the root node:
[ 28 ]
Chapter 2
Each node has a get method taking a key as a parameter, which locates
the value associated with the specified key and returns it, or raises
KeyError if the key is not associated with any value in the tree.
Each node has a set method taking a key and a value as parameters, and
associating the key and value within the tree.
Each node has a remove method taking a key as a parameter, and
removing the key and its associated value from the tree. It raises
KeyError if no value was associated with that key.
Node data
The first three paragraphs of the specification describe the member variables of an
AVL tree node, and tell us what the valid values for the variables are. They also tell
us how the tree height should be measured and define what a balanced tree means.
It's our job now to take these ideas, and encode them into tests that the computer can
eventually use to check our code.
We can check these specifications by creating a node and then testing the values,
but that would really just be a test of the constructor. It's important to test the
constructor, but what we really want to do is to incorporate checks that the node
variables are left in a valid state into our tests of each member function.
To that end, we'll define functions that our tests can call to check that the state of
a node is valid. We'll define these functions just after the third paragraph, because
they provide extra details related to the content of the first three paragraphs:
Notice that the node data test is written as if the AVL tree
implementation already existed. It tries to import an avl_tree
module containing an AVL class, and it tries to use the AVL class
in specific ways. Of course, at the moment there is no avl_tree
module, so the tests will fail. This is as it should
be. All that the failure means is that, when the time comes
to implement the tree, we should do so in a module called avl_
tree, with contents that function as our tests assume. Part of the
benefit of testing like this is being able to test-drive your code
before you even write it.
>>> from avl_tree import AVL
>>> def valid_state(node):
...
if node is None:
...
return
...
if node.left is not None:
[ 29 ]
Notice that we didn't actually call these functions yet. They aren't tests, as such, but
tools that we'll use to simplify writing tests. We define them here, rather than in the
Python module that we're going to test, because they aren't conceptually part of the
tested code, and because anyone who reads the tests will need to be able to see what
the helper functions do.
We don't even have to write an expected result, since we wrote the function to
raise an AssertionError if there's a problem and to return None if everything is
fine. AssertionError is triggered by the assert statement in our test code, if the
expression in the assert statement produces a false value.
[ 30 ]
Chapter 2
The test for the second mode looks just as easy, and we'll add it right after the other:
>>> valid_tree(AVL({1: 'Hello', 2: 'World', -3: '!'}))
There's a bit of buried complexity here, though. In all probability, this constructor
will function by initializing a single node and then using that node's set method
to add the rest of the keys and values to the tree. This means that our second
constructor test isn't a unit test, it's an integration test that checks the interaction
of multiple units.
Specification documents often contains integration-level and system-level tests, so
this isn't really a problem. It's something to be aware of, though, because if this test
fails it won't necessarily show you where the problem really lies. Your unit tests will
do that.
Something else to notice is that we didn't check whether the constructor fails
appropriately when given bad inputs. These tests are very important, but the English
specification didn't mention these points at all, which means that they're not really
among the acceptance criteria. We'll add these tests to the unit test suite instead.
Recalculating height
The recalculate_height() method is described in the fifth paragraph of the
specification. To test it, we're going to need a tree for it to operate on, and we don't
want to use the second mode of the constructor to create it after all, we want this
test to be independent of any errors that might exist there. We'd really prefer to make
the test entirely independent of the constructor but, in this case, we need to make
a small exception to the rule, since it's mighty difficult to create an object without
calling its constructor in some way.
What we're going to do is define a function that builds a specific tree and returns it.
This function will be useful in several of our later tests as well:
>>> def make_test_tree():
...
root = AVL(7, 'seven')
...
root.height = 2
...
root.left = AVL(3, 'three')
...
root.left.height = 1
...
root.left.right = AVL(4, 'four')
...
root.right = AVL(10, 'ten')
...
return root
[ 31 ]
tree = make_test_tree()
tree.height = 0
tree.recalculate_height()
tree.height
"Frog"
Lesser
"Aardvark"
"Goose"
Lesser
Greater
"Elephant"
The way around that is to have the node swap places with its largest leaf descendant
on the left side (or its smallest leaf descendant on the right side, but we're not doing
it that way).
We'll test this by using the same make_test_tree() function that we defined
earlier to create a new tree to work on, and then check whether make_deletable()
swaps correctly:
>>> tree = make_test_tree()
>>> target = tree.make_deletable()
>>> (tree.value, tree.height)
('four', 2)
>>> (target.value, target.height)
('seven', 0)
[ 32 ]
Chapter 2
Rotation
The two rotate functions, described in paragraph seven of the specification, perform
a somewhat tricky manipulation of the links in a tree. You probably found the plain
language description of what they do a bit confusing. This is one of those times when
a little bit of code makes a whole lot more sense than any number of sentences.
While tree rotation is usually defined in terms of rearranging the links between
nodes in the tree, we'll check whether it worked by looking at the values rather than
by looking directly at the left and right links. This allows the implementation to swap
the contents of nodes, rather than the nodes themselves, when it wishes. After all, it's
not important to the specification which operation happens, so we shouldn't rule out
a perfectly reasonable implementation choice:
>>> tree = make_test_tree()
>>> tree.value
'seven'
>>> tree.left.value
'three'
>>> tree.rotate_counterclockwise()
>>> tree.value
'three'
>>> tree.left is None
True
>>> tree.right.value
'seven'
>>> tree.right.left.value
'four'
>>> tree.right.right.value
'ten'
>>> tree.right.left.value
'four'
>>> tree.left is None
True
>>> tree.rotate_clockwise()
>>> tree.value
'seven'
>>> tree.left.value
'three'
>>> tree.left.right.value
'four'
>>> tree.right.value
'ten'
>>> tree.right.left is None
True
>>> tree.left.left is None
True
[ 33 ]
Locating a node
According to the eighth paragraph of the specification, the locate() method is
expected to return a node, or raise a KeyError exception, depending on whether
the key exists in the tree or not. We'll use our specially built testing tree again, so
that we know exactly what the tree's structure looks like:
>>> tree = make_test_tree()
>>> tree.locate(4).value
'four'
>>> tree.locate(17) # doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: ...
[ 34 ]
Chapter 2
>>> tree = make_test_tree()
>>> tree.set(10, 'foo')
>>> tree.locate(10).value
'foo'
Each node has a remove method taking a key as a parameter, and
removing the key and its associated value from the tree. It raises
KeyError if no values was associated with that key.
>>> tree = make_test_tree()
>>> tree.remove(3)
>>> tree.remove(3) # doctest: +ELLIPSIS
Traceback (most recent call last):
KeyError: ...
Summary
We learned the syntax of doctest, and went through several examples describing
how to use it. After that, we took a real-world specification for the AVL tree,
and examined how to formalize it as a set of doctests, so that we could use it
to automatically check the correctness of an implementation.
Specifically, we covered doctest's default syntax and the directives that alter it, how
to write doctests in text files, how to write doctests in Python docstrings, and what it
feels like to use doctest to turn a specification into tests.
Now that we've learned about doctest, we're ready to talk about how to use
doctest to do unit testingthe topic of the next chapter.
[ 35 ]
Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and
most internet book retailers.
www.PacktPub.com