Creating unit tests on the fly

Roy Smith roy at panix.com
Fri Apr 8 15:10:49 EDT 2011


I've got a suite of unit tests for a web application.  There's an
(abstract) base test class from which all test cases derive:

class BaseSmokeTest(unittest.TestCase):

BaseSmokeTest.setUpClass() fetches a UR (from a class attribute
"route", which must be defined in the derived classes), and there's a
number of test methods which do basic tests like checking for
reaonable-looking HTML (parsed with lxml), scanning the server log
file to make sure there's no error messages or stack dumps, etc.

Many of the test cases are nothing more than running the base test
methods on a particular route, i.e.

class Test_Page_About(BaseSmokeTest):
    route = 'page/about'

Now, I want to do something a little fancier.  I want to get a
particular page, parse the HTML to find anchor tags containing
additional URLs which I want to test.  It's easy enough to pull out
the anchors I'm interested in with lxml:

        selector = CSSSelector('div.st_info .st_name > a')
        for anchor in selector(self.tree):
            print anchor.get('href')

I can even create new test cases from these on the fly with something
like:

 newClass = type("newClass", (BaseSmokeTest,), {'route': '/my/newly/
discovered/anchor'})

(credit to http://jjinux.blogspot.com/2005/03/python-create-new-class-on-fly.html
for that neat little trick).  The only thing I don't see is how I can
now get unittest.main(), which is already running, to notice that a
new test case has been created and add it to the list of test cases to
run.  Any ideas on how to do that?

I suppose I don't strictly need to go the "create a new TestCase on
the fly" route, but I've already got a fair amount of infrastructure
set up around that, which I don't want to redo.



More information about the Python-list mailing list