Assertions and Focused Tests
Unit ID: M06-U06 Estimated active time: 25-35 minutes
A test compares actual and expected behaviour
assert parse_hours(8) == 8
assert parse_hours(" 8 ") == 8
If the condition is false, Python raises AssertionError.
Test categories
For hours from 0 to 40:
- normal:
8; - lower boundary:
0; - upper boundary:
40; - wrong type:
True,None,3.5; - malformed text:
"six","8.5",""; - out of range:
-1,41.
Test intended exceptions
A plain helper can check an exception without requiring a framework:
def assert_raises(expected_type, function, argument):
try:
function(argument)
except expected_type:
return
raise AssertionError(f"Expected {expected_type.__name__}")
Use it:
assert_raises(TypeError, parse_hours, True)
assert_raises(ValueError, parse_hours, "six")
A test runner such as pytest provides richer exception checks and reports. The course environment will pin the selected runner before publication.
Keep tests independent
Each test should create its own required input. Do not depend on a previous test changing global state. A test should pass when run alone and in the full suite.
Test the contract, not private steps
Check returned values, raised exceptions, preserved inputs, and intended side effects. Avoid tests that fail merely because a harmless internal variable name changed.
Practice
Write tests for parse_hours() covering two normal values, both boundaries, three wrong types, two malformed strings, and both out-of-range sides.
Takeaway
Focused tests make expectations executable. Include normal, boundary, and invalid cases, and keep each test independent. Next, we will apply the same discipline to code suggested by an AI tool.
