──────────────────────────────────────

7. Make Code You Can Trust · Turn Examples into Unit Tests

Write a test suite with meaningful normal and boundary cases.

Lesson files · lessons/design-and-testing/unit-tests

Before you start
- Call a calculation with fixed values and compare its return value.
- Use assert to check a normal result and a result at zero.

By the end
- Add a test for zero wins alongside the regular points test.
- Use the runner output to report how many tests ran and whether they passed.

Where you can use it
Before changing a points rule, put a typical win count and a zero-win case into a suite you can rerun after each edit.

A unit test exercises one piece of behaviour. Write each test as a function with an assertion. Give unittest.FunctionTestCase the function name without parentheses so the runner can call it later. The suite runs both cases even when one fails. StringIO collects the report so you can read it when you need it.

Predict
What would a test for zero wins check?
- That the result can legitimately be 0.
- How many tests run.

Worked example (example.py)

import io
import unittest

def points(wins):
    return wins * 3

def test_regular():
    assert points(2) == 6, "Two wins should score six"

suite = unittest.TestSuite([unittest.FunctionTestCase(test_regular)])
report = io.StringIO()
result = unittest.TextTestRunner(stream=report).run(suite)
print(f"Ran {result.testsRun}. Passed: {result.wasSuccessful()}")


Example result
Ran 1. Passed: True

Add a test_zero function that checks zero wins gives zero points. Keep the regular test and add the new test to the same suite. One run should report that both tests passed.

Starter program (starter.py)

import io
import unittest

def points(wins):
    return wins * 3

def test_regular():
    assert points(2) == 6, "Two wins should score six"

suite = unittest.TestSuite([unittest.FunctionTestCase(test_regular)])
report = io.StringIO()
result = unittest.TextTestRunner(stream=report).run(suite)
print(f"Ran {result.testsRun}. Passed: {result.wasSuccessful()}")


Hint
Write a second function with assert points(0) == 0. Add unittest.FunctionTestCase(test_zero) to the suite list.

Case 1. Try the sample
Input
(No input.)
Expected output
Ran 2. Passed: True

Stretch
Break points on purpose and add print(report.getvalue()) to inspect the failure.

Reflect
What useful clue do the test name and assertion message give you?

Check your prediction
That the result can legitimately be 0. Zero is an important boundary for the points function.
