unittest - run the same test for a list of inputs and outputs
Check out DDT (Data-Driven/Decorated Tests).
DDT allows you to multiply a test case by running it with different test data, making it appear as multiple test cases.
consider this example, using DDT:
import unittest
from ddt import ddt, data, unpack
@ddt
class TestName(unittest.TestCase):
# simple decorator usage:
@data(1, 2)
def test_greater_than_zero(self, value):
self.assertGreater(value, 0)
# passing data in tuples to achieve the
# scenarios from your given example:
@data(('Bob', 'Bob'), ('Alice', 'Alice'))
@unpack
def test_name(self, first_value, second_value):
name, expected_name = first_value, second_value
self.assertEquals(name, expected_name)
if __name__ == '__main__':
unittest.main(verbosity=2)
I defined 2 test methods in the above code, but 4 test cases will be run, using the data I supplied in the decorator.
Output:
test_greater_than_zero_1 (__main__.TestName) ... ok
test_greater_than_zero_2 (__main__.TestName) ... ok
test_name_('Alice', 'Alice') (__main__.TestName) ... ok
test_name_('Bob', 'Bob') (__main__.TestName) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.000s
OK
I would use a mixin or a metaclass here, as unittest looks for classes, not instances.
class TestMixin (object):
def test_name ():
print self.name
class TestName (unittest.TestCase, TestMixin):
...