Unittest testing assert*() calls rather than methods?

Terry Reedy tjreedy at udel.edu
Wed Sep 28 18:03:48 EDT 2011

On 9/28/2011 10:16 AM, Tim Chase wrote:

> When performing unittest tests, I have a number of methods of the form
> def test_foo(self):
> data = (
> (item1, result1),
> ... #bunch of tests for fence-post errors
> )
> for test, result in data:
> self.assertEqual(process(test), result)
> When I run my tests, I only get a tick for running one the one test
> (test_foo), not the len(data) tests that were actually performed. Is
> there a way for unittesting to report the number of passed-assertions
> rather than the number of test-methods run?

In my view, unittest, based on JUnit from Java, is both overkill and 
inadequate for simple function testing of multiple input-output pairs. 
So I wrote my own short function test function that does just what I 
want, and which I can change if I change what I want.

Ben has described the combinatorial explosion solution. But if I were 
using unittest, I might do something like the following:

   def test_foo(self):
     data = (
       (item1, result1),
       ... #bunch of tests for fence-post errors
     errors = []
     for input, expected in data:
         actual = process(input)
         if actual != expected: errors.append(input, expected, actual)
       except Exception as e:
         errors.append(input, expected, actual)
     self.assertEqual((0,[]), (len(errors),errors))

except that I would write a functest(func, iopairs) that returned the 
error pair. (This is essentially what I have done for for myself.)  I am 
presuming that one can run unittest so that it prints the unequal items.

Terry Jan Reedy

More information about the Python-list mailing list