I wish to add dynamic tests to a python unittest class during setup. Is there any way to get this working?
I know that this works based on the answers on this page:
def generate_test(a, b):
def test(self):
self.assertEqual(a, b)
return test
def add_test_methods(test_class):
test_list = [[1, 1, '1'], [5, 5, '2'], [0, 0, '3']]
for case in test_list:
test = generate_test(case[0], case[1])
setattr(test_class, "test_%s" % case[2], test)
class TestScenario(unittest.TestCase):
def setUp(self):
print("setup")
add_test_methods(TestScenario)
if __name__ == '__main__':
unittest.main(verbosity=1)
But this doesn't:
class TestScenario(unittest.TestCase):
def setUp(self):
add_test_methods(TestScenario)
It is unable to find any tests:
Process finished with exit code 5
Empty suite
Empty suite
Any idea why this doesn't work and how could I get it working?
Thanks.
UPDATE:
Tried to invoke add_test_methods from inside the TestScenario in this fashion, but it too doesn't work as it cannot resolve the TestScenario class and throws this error: "ERROR: not found: TestScenario"
class TestScenario(unittest.TestCase):
add_test_methods(TestScenario)
def setUp(self):
pass