Make confidence repeatable.
Turn an expectation into a test you can rerun after every change.
01 The idea
A test compares actual behaviour with an expectation. Python’s unittest module gives you a structure for repeatable tests and helpful failure reports. Start with a small function, test a normal case, and add edge cases that represent real risks.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
import io
import unittest
def remaining(total, completed):
return max(0, total - completed)
class RemainingTests(unittest.TestCase):
def test_open_tasks(self):
self.assertEqual(remaining(8, 3), 5)
def test_never_negative(self):
self.assertEqual(remaining(2, 5), 0)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(RemainingTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(f"{result.testsRun} tests; success={result.wasSuccessful()}")2 tests; success=True
03 Under the hood
- 1
Each method whose name begins with test is discovered as a test. assertEqual records a useful failure if the values differ.
- 2
The first case checks ordinary behaviour. The second checks a boundary where the completed count exceeds the total.
- 3
The example captures the runner’s report to keep the displayed output predictable. In a project, name your test file test_remaining.py and use python -m unittest discover. Keep tests independent and fast enough to run frequently.
04 Your turn, builder
Write an is_even(number) function and verify its behaviour for 4, 5, and 0.
Reveal one possible solution +
def is_even(number):
return number % 2 == 0
assert is_even(4) is True
assert is_even(5) is False
assert is_even(0) is True
print("Three checks passed")05 Check your signal
Which name is automatically discovered as a unittest test method?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.