unittests with different parameters

Roy Smith roy at panix.com
Mon Nov 22 15:11:12 CET 2010

In article <q91qr7-i9j.ln1 at satorlaser.homedns.org>,
 Ulrich Eckhardt <ulrich.eckhardt at dominolaser.com> wrote:

>   def test_invert_flags(self):
>       """test flags to invert coordinates"""
>       tests = [((10, 20), INVERT_NONE, (10, 20)),
>                ((10, 20), INVERT_X, (-10, 20)),
>                ((10, 20), INVERT_Y, (10, -20))]
>       for input, flags, expected in tests:
>           res = do_invert(input, flags)
>           self.assertEqual(res, expected,
>                            "%s caused wrong results" % (flags,))
> So, what I do that I test the function 'do_invert' for different input
> combinations and verify the result. The ugly thing is that this will abort
> the whole test if one of the tests in the loop fails. So, my question is
> how do I avoid this?

Writing one test method per parameter combination, as you suggested, is 
a reasonable approach, especially if the number of combinations is 
reasonably small.  Another might be to make your loop:

       failCount = 0
       for input, flags, expected in tests:
           res = do_invert(input, flags)
           if res != expected:
               print "%s caused wrong results" % (flags,)
               failCount += 1
       self.assertEqual(failCount, 0, "%d of them failed" % failCount)

Yet another possibility is to leave it the way you originally wrote it 
and not worry about the fact that the loop aborts on the first failure.  
Let it fail, fix it, then re-run the test to find the next failure.  
Perhaps not as efficient as finding them all at once, but you're going 
to fix them one at a time anyway, so what does it matter?  It may also 
turn out that all the failures are due to a single bug, so fixing one 
fixes them all.

More information about the Python-list mailing list