Testing Your Code — The Hitchhiker's Guide to Python (original) (raw)

../../_images/34435687940_8f73fc1fa6_k_d.jpg

Testing your code is very important.

Getting used to writing testing code and running this code in parallel is now considered a good habit. Used wisely, this method helps to define your code’s intent more precisely and have a more decoupled architecture.

Some general rules of testing:

The Basics

unittest

unittest is the batteries-included test module in the Python standard library. Its API will be familiar to anyone who has used any of the JUnit/nUnit/CppUnit series of tools.

Creating test cases is accomplished by subclassing unittest.TestCase.

import unittest

def fun(x): return x + 1

class MyTest(unittest.TestCase): def test(self): self.assertEqual(fun(3), 4)

As of Python 2.7 unittest also includes its own test discovery mechanisms.

Doctest

The doctest module searches for pieces of text that look like interactive Python sessions in docstrings, and then executes those sessions to verify that they work exactly as shown.

Doctests have a different use case than proper unit tests: they are usually less detailed and don’t catch special cases or obscure regression bugs. They are useful as an expressive documentation of the main use cases of a module and its components. However, doctests should run automatically each time the full test suite runs.

A simple doctest in a function:

def square(x): """Return the square of x.

>>> square(2)
4
>>> square(-2)
4
"""

return x * x

if name == 'main': import doctest doctest.testmod()

When running this module from the command line as in python module.py, the doctests will run and complain if anything is not behaving as described in the docstrings.