Build a Mini Test Runner
Advanced · Write the code · 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 lessonWrite a function called run_tests that takes a list of test functions, runs each one inside a try/except block, and prints a summary at the end. Use the format shown: print PASS: <function_name> or FAIL: <function_name> for each test, then print a blank line followed by <passed> passed, <failed> failed. Use the provided test functions to demonstrate it.
def divide(a, b):
if b == 0:
return None
return a / b
def test_divide_normal():
assert divide(10, 2) == 5.0
def test_divide_by_zero():
assert divide(10, 0) is None
def test_divide_negative():
assert divide(-6, 3) == -2.0
def run_tests(tests):
# Your code here
pass
run_tests([test_divide_normal, test_divide_by_zero, test_divide_negative])
More pytest exercises
- Write Your First TestBeginner
- Fix the Failing TestBeginner
- Predict the Test ResultsIntermediate
- Test the Edge CasesIntermediate
- Refactor Repetitive TestsAdvanced