Python Test Collector

I accidentally "discovered" the TestCollector idea independently in Python. My tests all end in "Test.py", and I set them up so I can run each of them independently from the command line, or all at once with this script. I have this in "runAllTests.py" and invoke it so that the current directory is the top of the program. (Unlike most Python programmers I actually have a lot of separate directories and modules.) It recursively searches the current directory for things to test and runs them all at once.

No guarantees, etc.


 #!/bin/python

import sys import os import re import unittest import imp

filesList = []

def collector(arg, dirname, names): filesList.extend([dirname + os.sep + n for n in names])

def returnTests(): p = os.path.abspath(os.path.dirname(sys.argv[0])) os.path.walk(p, collector, None) fList = [x for x in filesList if x[-7:] == "Test.py" and '#' not in x] # '#' is for temp files in emacs, extend as needed fileList = [file(x, "r") for x in fList] modules = [] for i in range(len(fList)): modules.append(imp.load_source(os.path.split(fList[i])[1][:-3], fList[i], fileList[i]))

l = unittest.defaultTestLoader.loadTestsFromModule return unittest.TestSuite(map(l, modules))

if __name__ == "__main__": unittest.main(defaultTest="returnTests")


There's about a billion ways to extend this, make it more robust, etc., but it's a start. -- JeremyBowers


EditText of this page (last edited April 9, 2004) or FindPage with title or text search