Categories
python python-3.x refactoring unit-testing

Repetitive code in unittest testcase

I have a testcase that looks like this:

def MyTestCase(unittest.Testcase):
def test_input01(self):
input = read_from_disk('input01')
output = run(input)
validated_output = read_from_disk('output01')
self.assertEquals(output, validated_output)
def test_input02(self):
input = read_from_disk('input02')
# ...
# and so on, for 30 inputs, from input01 to input30

Now, I understand that test code can be a bit repetitive, since simplicity is more important than conciseness. But this is becoming really error-prone, since when I decided to change the signature of some functions used here, I had to make the change in all 30 places.

I could refactor this into a loop over the known inputs, but I do want each input to remain a separate test, so I thought I should be making the test_inputxx methods.

What am I doing wrong?

Write a helper function to remove the repetition from the test cases:

def MyTestCase(unittest.Testcase):
def run_input_output(self, suffix):
input = read_from_disk('input'+suffix)
output = run(input)
validated_output = read_from_disk('output'+suffix)
self.assertEquals(output, validated_output)
def test_input01(self): self.run_input_output('01')
def test_input02(self): self.run_input_output('02')
def test_input03(self): self.run_input_output('03')