Welcome, guest | Sign In | My Account | Store | Cart

The following recipe ensures unit tests are run whenever the code is compiled.

-- See <a href="http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/125385">microtest.py</a>

Python, 33 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# pretest.py
"""
Usage: To execute your tests each time your module is compiled, add this line
at the end of your module.  Be sure to edit pretest to call your favorite test 
runner in place of microtest.test.

pretest.pretest('mymodule')
"""
import os
import microtest
import sys

def pretest(modulename, verbose=None, force=None, deleteOnFail=0, 
            log=sys.stdout):
    # import module
    module = __import__(modulename)

    # only test uncompiled modules unless forced
    if module.__file__[-3:] == '.py' or force:

        # kick off your tests with your favorite test suite
        if microtest.test(modulename, verbose, log):
            pass # all tests passed
        elif deleteOnFail:
            
            # Cream the pyc file so we run the test suite next time 'round
            filename = module.__file__
            if filename[-3:] == '.py':
                filename = filename + 'c'
            try:
                os.remove(filename)
            except OSError:
                pass
        

For frequently changing code, it is reasuring to have code that retests itself whenever it changes. The programmer is relieved of the burden of remembering to run her unittests.

2 comments

Hamish Lawson 20 years ago  # | flag

Use __import__ rather than exec. The line

exec('import %s as module' % modulename)

can be replaced by

module = __import__(modulename)

Using exec can significantly impact the performance of the program.

Justin Shaw (author) 20 years ago  # | flag

Roger that!

Created by Justin Shaw on Sat, 9 Feb 2002 (PSF)
Python recipes (4591)
Justin Shaw's recipes (4)

Required Modules

Other Information and Tasks