I need to test two almost identical functions, and don't see much point copy-pasting the tests that I have written for function1. Can I somehow pass the function name to a class derived from unittest.TestCase and set up the function that needs to be tested in setUp?
1 Answer
There's no trick to this. Functions are first-class objects in Python and can be passed around just like any other parameter. So this would work, assuming the functions under test are 'func_one' and 'func_two':
class MyTestCase(unittest.TestCase):
def generic_test(self, func):
result = func()
... assertions about result....
def test_func_one(self):
self.generic_test(func_one)
def test_func_two(self):
self.generic_test(func_two)