How to test same assertion for large amount of data
Sample code for solution suggested by Bill Gribble could look like this:
import unittest
class DataTestCase(unittest.TestCase):
def __init__(self, number):
unittest.TestCase.__init__(self, methodName='testOneNumber')
self.number = number
def testOneNumber(self):
self.assertEqual(self.number, 33)
def shortDescription(self):
# We need to distinguish between instances of this test case.
return 'DataTestCase for number %d' % self.number
def get_test_data_suite():
numbers = [0,11,222,33,44,555,6,77,8,9999]
return unittest.TestSuite([DataTestCase(n) for n in numbers])
if __name__ == '__main__':
testRunner = unittest.TextTestRunner()
testRunner.run(get_test_data_suite())
As of Python 3.4 you can use unittest.TestCase.subTest(msg=None, **params)
context manager (documentation). This will allow you to achieve what you want by adding just one statement.
Here is your example modified to use subTest()
import unittest
class TestData(unittest.TestCase):
def testNumbers(self):
numbers = [0, 11, 222, 33, 44, 555, 6, 77, 8, 9999]
for i in numbers:
with self.subTest(i=i): # added statement
self.assertEqual(i, 33)