Basic Unit Test setup

This is a small bit of code I might want to use for unit testing and I thought it might be useful to others too. It just makes it a bit easier (IMHO) to use the python unittest module:

testbase.py:
--------------------------------------------------------------
import unittest

def testmethod(testMethod):
        testMethod._isTest = True
        return testMethod
class BasicTestSet(unittest.TestCase):
    @classmethod
    def suite(cls):
        def isTestMethod(attrname):
            attr = getattr(cls, attrname)
            return hasattr(attr, "_isTest")
        testNames = filter(isTestMethod, dir(cls))
        return unittest.TestSuite(map(cls,testNames))


def make_suite(*args):
    fullSuite = unittest.TestSuite()
    for testSet in args:
        fullSuite.addTest(testSet.suite())
    return fullSuite
--------------------------------------------------------------
I then use it like this for example:

test_sprites.py:
--------------------------------------------------------------
from testbase import *
import unittest

from sprites import *

def suite():
    return make_suite(TowerTests)

class TowerTests(BasicTestSet):
    def setUp(self):
        self.tower = Tower()
    @testmethod
    def testCreate(self):
        self.failIf(self.tower is None)
    @testmethod
    def testGrow(self):
        self.tower.grow()
        self.failUnlessEqual(self.tower.level, 1)

--------------------------------------------------------------
and I have a runtests.py that looks like this (though you could easily use a different test runner):
--------------------------------------------------------------
import unittest
import test_world
import test_sprites

all_tests = unittest.TestSuite()
all_tests.addTests((test_world.suite(), test_sprites.suite()))

unittest.TextTestRunner().run(all_tests)
--------------------------------------------------------------

(log in to comment)

Comments

You'd probably be better-off just using a more intelligent test harness. I believe the "trial" test runner from the Twisted project is very good at finding tests without all that suite malarky. There's other test runners that are stand-alone but I've not tried them.