ActiveState Code

Recipe 113408: Automatic unittesting - pretest.py


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
 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
        

Discussion

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.

Comments

  1. 1. At 7:12 a.m. on 7 may 2002, Hamish Lawson said:

    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.

  2. 2. At 5:37 p.m. on 7 may 2002, Justin Shaw (the author) said:

    Roger that!

Sign in to comment