Python Self-testing Code

From Digi Developer

Jump to: navigation, search

How to create self-testing code

A common best-practice under Python is to include a self-test at the end every module - especially if the module is largely standalone. Thus the code "import bool_any" only brings in the routines, while running the module with "python bool_any.py" runs the self tests.

This self-test code does make your files larger in both .PY and .PYC format. For small projects the added 30-50% bulk won't matter, but for larger projects you should consider using a simple python script to parse through all your files, creating temporary copies which are truncated at an embedded text string

Simple example

Here is a simple example - the def module is of course fake, but the test is a very powerful example of solving a problem as Python likes to solve it.

# file is bool_any.py
 
import traceback
 
def bool_any(data):
    # this is dummy routine; any tests expecting True will fail
    return False
 
# put auto-cutting pattern here
 
if __name__ == '__main__':
 
    # here are our list of test-lists, of the form [input,output]
    # of course include as any inputs or outputs as required
    tsts = [["true",True],["false",False],["tRUe",True],["faLSe",False],
            ["t",True],["f",False],["T",True],["F",False],
            ["1",True],["0",False],["on",True],["OfF",False],
            ["23",-1],["O",-1],
            ]
 
    # run through all of the tests; notice use of try/except
    for tst1 in tsts:
        try: 
            x = bool_any(tst1[0])
        except: 
            traceback.print_exc()
            x = -1
        if( x != tst1[1]):
            print "\tError: bool_any('%s') failed" % tst1[0]
            # put an exit here; return or sys.exit(-1) as required
 
    print "\tTest was Good"
Personal tools
Wiki Editing