We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I test a Python program or component?

Python comes with two testing frameworks.

The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring. You can use this for more extensive testing either by writing separate test programs, and using doctest to verify that the test programs behave properly, or by putting the tests in separate text files.

The unittest module is more traditional testing framework modelled on Java and Smalltalk testing frameworks.

Additional tools include Nose and py.test.

For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods — and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.

The “global main logic” of your program may be as simple as

if __name__=="__main__":
     main_logic()

at the bottom of the main module of your program.

Once your program is organized as a tractable collection of functions and class behaviours you should write test functions that exercise the behaviours. A test suite can be associated with each module which automates a sequence of tests. This sounds like a lot of work, but since Python is so terse and flexible it’s surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier.

“Support modules” that are not intended to be the main module of a program may include a self-test of the module.

if __name__ == "__main__":
   self_test()

Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python.

CATEGORY: library