Is this the correct way to implement TestSuite?

Robert Brewer fumanchu at amor.org
Wed Mar 24 23:30:52 CET 2004


Lol McBride wrote:
> Hi all,
> I've been using unittest for a while now but only creating 
> test cases for
> individual modules of an application e.g class foo() has a reciprocal
> module called class fooTestCase() class bar() has a reciprocal module
> called class barTestCase()
> 
> Now my app has quite a few modules and I want to run a single 
> test that
> calls all of the xxxTestCase() modules and therefore runs all 
> of the tests
> I have created so far.

I took a slightly different approach, possibly because I tend to code in
packages. Most of my development assumes 1) the module you want to test
is in site-packages or some other point on syspath, and 2) all your
testing modules are somewhere in the same folder or subfolders of it. If
you can assume those two things as well, try my testpkg module (below).
It's invoked like:

prompt> python testpkg.py mypackage

and will then run all files in that package (and its subfolders) whose
names begin with "test_" and end in ".py".


----testpkg.py----

import os
import sys
import imp
import unittest
import xray

def test_module(module):
    test = unittest.TestLoader().loadTestsFromModule(module)
    result = unittest.TextTestRunner().run(test)
    return result.wasSuccessful()

def modules(dir):
    for name in os.listdir(dir):
        fullname = os.path.join(dir, name)
        if os.path.isdir(fullname):
            for mod in modules(fullname):
                yield mod
        elif name.startswith("test_") and name.endswith(".py"):
            yield fullname

def test_package(packageName):
    filename, pathname, descr = imp.find_module(packageName)
    # TODO: provide for subpackages (packageNames containing dots)
    for name in modules(pathname):
        name = name[len(pathname):]
        if name.startswith(u"\\") or name.startswith(u"/"):
            name = name[1:]
        if name.endswith(u".py"):
            name = name[:-3]
        name = name.replace("/", ".").replace(u"\\", ".")
        name = ".".join((packageName, name))
        try:
            mod = xray.modules(name)
        except ImportError, x:
            x.args += (name, )
            raise x
        print "Module: " + name
        test_module(mod)
        del mod

if __name__ == '__main__':
    test_package(sys.argv[1])



This uses my xray module, btw, which you can find at:

http://www.aminus.org/rbre/python/xray.py


HTH!

Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list