Testing in Python

In this post I’ll cover testing with unittest and nose. A really good overview of testing and testing tools is provided at the Hitchhiker’s Guide to Python.


The unittest module requires that you create a class that imports unittest.TestCase whose methods, beginning with the word test_ will be called to test parts of your code. The setUp() and tearDown() methods are provided to the tester to create pre-conditions and then clean them up before and after each test_...() method.

import unittest

class TestClass( unittest.TestCase ):
    def setUp( self ):
    def test_some_part( self ):
    def tearDown( self ):

if __name__=="__main__":

After your testing module has been written, you simply call it from the command line and then wait for the dots, or start debugging.


If you can use unittest you can for sure use nose. Simply start any script you want tested with “test,” and then name any function within that script that you want tested similarly, beginning with “test”. That’s it. A call to nosetests will perform a regex search on your working directory to find your test modules, and the test functions within them.

Like unittest, nose provides function names setup_module() and teardown_module() functions for setting up (and tearing down) things for the testing environment. Each test should end with an assert statement checking a boolean expression. If you’re committed to using nose for your testing, you may replace the assert statement with a call to nose.tools.assert_equals(*,*) where *,* are the two parts of the boolean expression that you’d like to test or assert. This technique improves the readability of the debugging messages provided by nose.

To use nose after setting up your tests, run the following from the command line

$ nosetests

You may also perform doctest testing! Just add the switch --with-doctest. To add verbosity to the testing output, include a -v flag.

3 thoughts on “Testing in Python”

    1. Hi Anders, I do not know what code-coverage analysis is, but I appreciate your question as it has given me something new to look into. Thanks!

Comments are closed.