Unittest - How do I code lots of simple tests

Peter Hansen peter at engcorp.com
Tue Oct 21 17:32:12 EDT 2003


Paul Moore wrote:
> 
> Can anyone suggest a more reasonable way of running this sort of
> table-driven test via unittest?

Why not just extend self.assertEqual() and use your own check, with
additional logic as required to increment counters or add items
to the list of passing tests.  Then put a final check of the number
of passing tests or something like that at the end to make sure 
things worked overall.
For example:

class KnownValues(unittest.TestCase):
    def setUp(self):
        self.passCount = 0

    def checkValue(self, expected, result):
        if expected == result:
            self.passCount += 1
        else:
            # left as exercise to the reader, but pass would work...

    def testToRomanKnownValues(self):
        for integer, numeral in self.knownValues:
            result = roman.toRoman(integer)
            self.checkValue(numeral, result)
        self.assertEqual(len(self.knownValues), self.passCount)

No, you don't get the psychologically affirming "52 tests passed!"
without changes to the TestRunner, but I assume the non-cosmetic part
of this is more your concern right now...

-Peter




More information about the Python-list mailing list