Unittest - How do I code lots of simple tests

Peter Otten __peter__ at web.de
Wed Oct 22 04:29:07 EDT 2003


Miki Tebeka wrote:

> 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):

Change the above line to

     def test(self, a=a, r=r):

or you will perform the test five times with (5, "V").

>         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 ---


I like the idea, once the little error is removed. In general, I think the
unit test code should be as simple as possible. Otherwise we would need
unit tests for unit tests for...

Peter





More information about the Python-list mailing list