Unittest - How do I code lots of simple tests

Miki Tebeka mikit at zoran.co.il
Wed Oct 22 03:40:35 EDT 2003


Hello Paul,

> test_values = ((1, 'I'), ...)
> 
> class KnownValues(unittest.TestCase):
>     pass
> 
> for arabic, roman in test_values:
>     def test(self):
>         result = roman.toRoman(arabic)
>         self.assertEqual(roman, result)
>     setattr(KnownValues, 'test_%s_%s' % (arabic, roman), test)
> 
> But I can't really see that as the "right approach".
On reason that it won't do what you want :-)
All the tests will check the last value in test_values. (Something to
do with binding rules, can't recall how to solve)

Try:
--- i2r.py ---
#!/usr/bin/env python
from unittest import TestCase, makeSuite, main

class Roman:
    def toRoman(self, i):
        return { 1 : "I",
                 2 : "II",
                 3 : "III", 
                 4 : "IV",
                 5 : "V"}[i]
roman = Roman()

class KnownValues(TestCase):
    pass

test_values = ((1, "I"), (2, "II"), (3, "III"), (4, "IV"), (5, "V"))
for a, r in test_values:
    def test(self):
        print a, r
        result = roman.toRoman(a)
        self.assertEqual(r, result)
    setattr(KnownValues, "test_%s_%s" % (a, r), test)

test_suite = makeSuite(KnownValues, "test_")

if __name__ == "__main__":
    main()
--- i2r.py ---

$ python i2r.py
5 V
.5 V
.5 V
.5 V
.5 V
.
----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK


HTH.
Miki




More information about the Python-list mailing list