Testing Python Functions
Python unittest and xUnit Testing
BOTIE
Python's unittest documentation identifies its connection to JUnit. A runner can execute a collection of tests and report failures separately. We use that organization to preserve the alert rule while its implementation changes. Passing a finite case set remains evidence about those cases, rather than proof about every possible input.
Sources for this history
The Alert Count Changed After a Cleanup
Botie counts greenhouse readings at or above a limit. A cleanup changes one comparison. The program still runs, but a reading exactly on the limit no longer creates an alert.
We need a case that distinguishes the intended rule from that plausible mistake. Keeping its expectation executable lets us check the next change too.
These are recorded Python test results. The blocks compare their counts; the coding challenge runs the actual report and its tests.
Step 1 of 1
The boundary belongs to the rule
Each expectation follows from the inclusive alert rule, independently of the tested implementation.
| Case | Readings | Limit | Expected count |
|---|---|---|---|
| Below | [19] | 20 | 0 |
| Boundary | [20] | 20 | 1 |
| Empty | [] | 20 | 0 |
Below
- Readings
- [19]
- Limit
- 20
- Expected count
- 0
Boundary
- Readings
- [20]
- Limit
- 20
- Expected count
- 1
Empty
- Readings
- []
- Limit
- 20
- Expected count
- 0
State observable behavior
A passing boundary case does not clear a failing empty batch or above-limit case. Comparing each row keeps the failure beside the input that exposed it.
Find the failed alert tests
The greenhouse report should count every reading at or above 25 C. A code change stopped counting the boundary reading. Each row below keeps a test input, its expected count and the count the program returned together.
BOTIE
Failed test rows, including inputs and both counts
- case
- At the limit
- readings_c
- [25]
- expected
- 1
- actual
- 0
| case | readings_c | expected | actual |
|---|---|---|---|
| At the limit | [25] | 1 | 0 |
Follow the operations
1. Alert tests: inputs and returned counts
- case
- At the limit
- readings_c
- [25]
- expected
- 1
- actual
- 0
- case
- Above the limit
- readings_c
- [28]
- expected
- 1
- actual
- 1
- case
- No readings
- readings_c
- []
- expected
- 0
- actual
- 0
case readings_c expected actual At the limit [25] 1 0 Above the limit [28] 1 1 No readings [] 0 0 2. Read a field from every record
- 00
- 11
- 20
3. Read a field from every record
- 01
- 11
- 20
4. Compare actual with expected
- 0true
- 1false
- 2false
5. Keep flagged entries
- case
- At the limit
- readings_c
- [25]
- expected
- 1
- actual
- 0
case readings_c expected actual At the limit [25] 1 0 6. Result
- case
- At the limit
- readings_c
- [25]
- expected
- 1
- actual
- 0
case readings_c expected actual At the limit [25] 1 0
These are recorded Python test results. The blocks compare their counts; the coding challenge runs the actual report and its tests.
1. State observable behavior
The promise is a count, not a particular loop or variable name. A useful test calls the function with known readings and compares its result with an answer we can establish independently. A refactor can change the implementation while preserving that promise.
An assertion reports a failure when its expectation is false. Assertions are appropriate in tests. Required runtime validation still needs explicit checks and exceptions because Python can omit assert statements under optimization.
Check the equality case
The first check distinguishes >= from >. The second checks an empty report.
def alert_count(readings, limit):
return sum(value >= limit for value in readings)
assert alert_count([19, 20, 24], 20) == 2
assert alert_count([], 20) == 0
print("Boundary and empty report passed.")Boundary and empty report passed.The expected counts come from the rule, rather than another call to the same implementation.
2. Give each failure its own test
unittest supplies TestCase, a class with assertion methods. Methods whose names start with test are individual checks. A runner collects their outcomes so a failure in one test need not hide the others.
A fixture is the data or setup a test needs. Keep fixtures small enough to explain why a failed expectation matters. This example captures the runner's formatted report and prints stable counts instead of variable timing information.
Run independent checks
Each method asks a different question about the same function.
import io
import unittest
def alert_count(readings, limit):
return sum(value >= limit for value in readings)
class AlertTests(unittest.TestCase):
def test_boundary(self):
self.assertEqual(alert_count([20], 20), 1)
def test_empty(self):
self.assertEqual(alert_count([], 20), 0)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(AlertTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(result.testsRun)
print(result.wasSuccessful())2
TrueThe passing run establishes these expectations for these cases. It does not establish complete coverage.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
Which expected count matches the rule?
Question data
Rule: count values >= 20. Readings: [19, 20, 24].3. Choose cases that distinguish mistakes
Typical input shows ordinary use. Boundary cases test the exact place a rule changes. Empty collections, repeated values and invalid inputs need cases when the contract describes them. For an invalid input, check the specific exception promised by the function.
A regression test retains a case that previously failed. Confirm the test exposes the failure, repair the implementation, then keep the case. Changing its expected answer merely to make a test green removes the evidence.
4. Separate unit checks from integrations
A unit test checks a small behavior with controlled inputs. An integration test checks that real components agree, such as a parser reading the format another component actually writes. Replacing a remote client makes arithmetic repeatable but cannot establish real connectivity.
Tests should not depend on their execution order or another test's mutable data. Add meaningful changed inputs rather than repeating a successful demonstration. pytest is another runner: it discovers test functions and supports parameterized cases. In a local project, install it in the project environment and run python -m pytest. The browser exercises use unittest, which is already available.
The practice retains the complete prepare_reports program from the shared-policy lesson. It explicitly introduces a compact per-house adapter and counts-only view, rather than claiming the earlier named-record interface has changed.
Check yourself
Questions on Parts 1 to 4
Question 1 of 4
What does that regression test preserve?
Question data
A repaired input has a permanent test with an independently known answer.Try it with Botie
Build with Botie
Write and run Python