Code of the Day
AdvancedTooling & Packaging

Lab: survive the test suite

Write small utilities robust enough to pass strict tests — edge cases and all.

Lab · optionalPythonAdvanced16 min
Recommended first
By the end of this lesson you will be able to:
  • Handle edge cases deliberately, not by accident
  • Read failing checks as a specification
  • Build the test-first instinct from the testing lessons

Optional lab. The testing lessons said good tests are a specification and the awkward cases are where bugs live. Here the tests are written for you — your job is to make code that satisfies all of them, edge cases included. Let the red checks guide you.

The skill this lab drills: writing a function that's correct on the boundaries, not just the happy path. Run, read the failing check, fix exactly that, repeat — the debugging loop in miniature.

Checkpoint 1 — slugify

Turn a title into a URL slug. Sounds trivial; the edge cases are the point — extra spaces, surrounding whitespace, mixed case.

Slugify a titlePython

Write slugify(text): lowercase it, and join the words with single hyphens. Collapse runs of whitespace and ignore leading/trailing spaces. " Hello World " -> "hello-world".

slugify("Hello World")"hello-world"slugify(" ")""

Notice the empty/whitespace case: " ".split() is [], and "-".join([]) is "". The boundary falls out naturally if you use .split() with no argument — exactly the kind of detail a thorough test catches.

Checkpoint 2 — clamp

Constrain a number to a range. Four behaviours to get right: below, above, within, and exactly on the bounds.

Clamp a value to a rangePython

Write clamp(value, low, high) that returns value limited to the range [low, high]: low if it is below, high if above, otherwise value unchanged.

clamp(99, 0, 10)10clamp(-3, 0, 10)0

The clean one-liner is max(low, min(value, high)) — but arriving at it by making each boundary check pass is the real lesson. That's test-driven thinking: the tests define "done," and you write the simplest code that gets there.

Done?

All green? You just practised the most underrated skill in the testing lessons — handling the edge cases on purpose. Wire suites like these into CI and they catch regressions forever.

Finished reading? Mark it complete to track your progress.

On this page