Test your code: so easy there’s no excuse!
I had heard of unittest and how I really needed to use it to make sure my code is doing what I expect . . . but it just seemed so clunky. Plus, a program would have to reach a certain threshold of complexity before I would make the effort to test with unittest.
Then I ran across doctest. And it is so astoundingly easy to use that I might start writing tests even for one-line scripts.
Here are the three files you need, along with what I’m going to be calling them:
- some code to test, “code.py”
- a text file containing documentation for that code, “tutorial.txt”
- a two line test-runner script, “test.py”
1. code.py
code.py, the stuff I want to test, looks like this:
def addxy(x,y):
return x+y
def sayHi():
print "Hi!"
2. tutorial.txt
tutorial.txt contains what to expect when you type certain things at the prompt, along with text. This is plain text.
This tests the module "code.py".
First, make sure that addxy() works:
>>> from code import *
>>> addxy(4,5)
9
Now make sure sayHi() works:
>>> sayHi()
Hi!
3. test.py
test.py contains these two lines. Note that tutorial.txt is referred to in this file, so make sure it points to whatever you called your testing text.
import doctest
doctest.testfile('tutorial.txt')
Now test!
Run test.py to test everything in the tutorial.txt file:
python test.py
In this case, it tests the stuff in code.py. If all goes well, nothing is returned. If you would like some feedback, then use the -v option at the commandline when running test.py.
python test.py -v
Results
Here’s what you get when all tests pass and you use the -v option:
Trying:
import code
Expecting nothing
ok
Trying:
code.addxy(4,5)
Expecting:
9
ok
Trying:
code.sayHi()
Expecting:
Hi!
ok
1 items passed all tests:
3 tests in tutorial.txt
3 tests in 1 items.
3 passed and 0 failed.
Test passed.
To see what happens when a test fails, try changing the “+” in the definition of addxy() to a “-”. When you run the test again using:
python test.py
then you get something like this:
**********************************************************************
File "tutorial.txt", line 3, in tutorial.txt
Failed example:
code.addxy(4,5)
Expected:
9
Got:
-1
**********************************************************************
1 items had failures:
1 of 3 in tutorial.txt
***Test Failed*** 1 failures.
So it tells you where the testing failed: on line 3 when it tried running code.addxy(4,5). It said it was expecting 9 but instead got -1. After changing that “-” back to a “+”, everything should work again.
Tags: Python