Editor

Refactor Repetitive Tests

Advanced · Refactor · from Python Testing with pytest: Write Tests That Actually Help

From the lesson: Python Testing with pytest: Write Tests That Actually Help

Imagine you wrote a spell-checker. It works great on the word "hello." But what about "HeLLo"? Or an empty string? Or a number? You won't know until something breaks - unless you write tests.

Read the lesson

The tests below work but are repetitive. Refactor them to use a data-driven approach: store test cases as a list of tuples (input, expected) and loop through them. The function, all assertions, and the final print statement should remain. Print Testing: <input> -> <expected> for each case, then All 5 tests passed! at the end.

def grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# These tests work but are repetitive - refactor them!
def test_grade_a():
assert grade(95) == 'A'
def test_grade_b():
assert grade(85) == 'B'
def test_grade_c():
assert grade(75) == 'C'
def test_grade_d():
assert grade(65) == 'D'
def test_grade_f():
assert grade(45) == 'F'
test_grade_a()
test_grade_b()
test_grade_c()
test_grade_d()
test_grade_f()
print('All 5 tests passed!')

More pytest exercises

All Python exercises · 50 practice problems · Testing quiz