February 2, 2011

how to run the whole testsuite in a Python project/module

I can't believe Google doesn't have anything to say about this...

The situation is usual: you have a python module, let's call it bravo, and a set of unittest-based unit tests in bravo.test. Now, there's nothing like "runtest" or whatever to run the test suite. Of course, you could run each of the tests individually, but maybe there's twenty of them and you're lazy, or maybe they don't even contain the magical "if name=main then runtest" spell.

Twisted to the rescue! Just run this:
trial modulename
or
trial modulename.test

If you don't have Twisted (of which trial is a part), you can use the following snippet:


import glob, unittest, os, imp
suite = unittest.TestSuite()
testloader = unittest.TestLoader()

for test in glob.glob("bravo/tests/test_*.py"):
name = os.path.splitext(os.path.basename(test))[0]
module = imp.load_source(name, test)
tests = testloader.loadTestsFromModule(module)
suite.addTest(tests)

unittest.TextTestRunner().run(suite)

1 comment:

pfalcon said...

The general way to run testsuite for an entire project/module is to execute:

python setup.py test

But that requires some care from module author - setting test interpreter to use, and listing test dependencies. It's done this way to allow pluralism regarding selection of testing framework (in particular, few people have fun writing tests with standard unittest framework).

And regarding good test framework and runner, nosetests (http://code.google.com/p/python-nose/) is close to being de-facto standard. With it, you can write tests as easily as using assert statements, and simple "nosetests" command will discover and run all tests for a project (simple naming rules to follow).

P.S. Thanks for hint on stopping Android system services, I also thought Google doesn't know how to do that ;-).