Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
EXPERIMENT 25 / 101

Make confidence repeatable.

Turn an expectation into a test you can rerun after every change.

BY NAVAN SAMI◷ 8 MIN READPYTHON 3

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.

testing.py
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()}")
↳ EXPECTED OUTPUT
2 tests; success=True

03 Under the hood

  1. 1

    Each method whose name begins with test is discovered as a test. assertEqual records a useful failure if the values differ.

  2. 2

    The first case checks ordinary behaviour. The second checks a boundary where the completed count exceeds the total.

  3. 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

A SMALL MISSION

Write an is_even(number) function and verify its behaviour for 4, 5, and 0.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

Which name is automatically discovered as a unittest test method?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.