[TIP] Test Parameterization with unittest

Michael Foord fuzzyman at voidspace.org.uk
Sun May 10 16:27:15 PDT 2009


Michael Foord wrote:
> Hello guys,
>
> There was a recent discussion on test parameterisation. I didn't follow 
> the discussion very closely to gather your requirements, but spurred on 
> my Brandon Rhodes I've hacked together a simple technique:
>
> http://code.google.com/p/unittest-ext/source/browse/trunk/params.py
>
> It actually uses a metaclass, but to use it you inherit from 
> TestCaseWithParams and provide a 'params' (list or iterable) class 
> attribute and an 'assertWithParams' method.
>   

And because it uses a metaclass it only works when TestCase is a new 
style class - which unbelievably only became true around Python 2.6 or so!

(Just in case anyone is trying it with Python 2.5 and wondering why it 
isn't working...)

Michael
> A new test method is generated for each member of the params list. This 
> test:
>
>
> class Test(TestCaseWithParams):
>     params = [(1, 1), (2, 3), (2, 2), (3, 5)]
>    
>     def assertWithParams(self, a, b):
>         self.assertEqual(a, b)
>
> Produces the following output:
>
> C:\compile>python test.py
> Test with args: (1, 1) ... ok
> Test with args: (2, 3) ... FAIL
> Test with args: (2, 2) ... ok
> Test with args: (3, 5) ... FAIL
>
> ======================================================================
> FAIL: Test with args: (2, 3)
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>   File "test.py", line 17, in test
>     self.assertWithParams(*args)
>   File "test.py", line 38, in assertWithParams
>     self.assertEqual(a, b)
> AssertionError: 2 != 3
>
> ======================================================================
> FAIL: Test with args: (3, 5)
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>   File "test.py", line 17, in test
>     self.assertWithParams(*args)
>   File "test.py", line 38, in assertWithParams
>     self.assertEqual(a, b)
> AssertionError: 3 != 5
>
> ----------------------------------------------------------------------
> Ran 4 tests in 0.016s
>
> FAILED (failures=2)
>
> All the best,
>
> Michael
>
>   


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog





More information about the testing-in-python mailing list