Skip to main content

Test-driven development (TDD) with Python — basic principles

Pytest fixtures from article 149 make experiments cheap; test-driven development formalizes the loop: write a failing test describing missing behavior, implement the smallest change to pass, refactor with confidence.


📚 Prerequisites

  • Ability to run pytest or unittest locally within seconds.

🎯 What you'll learn

  • Apply the red → green → refactor cadence without turning it into dogma.
  • Recognize when TDD helps (pure logic) vs. hinders (unknown UI affordances).

The micro-loop

  1. Red — craft a test that captures the next requirement and watch it fail for the right reason.
  2. Green — write minimal production code to satisfy the test (even if inelegant).
  3. Refactor — improve names, factor duplication, keep the suite green.

The guardrail is the suite: refactors that break behavior should fail immediately.


Where TDD shines

  • Pricing rules, parsers, authentication helpers—deterministic domains with crisp inputs/outputs.
  • Libraries without volatile third-party UI timing.

Where to relax the strictness

  • Spikes exploring unfamiliar APIs—capture learnings, then backfill tests.
  • Machine learning experiments where “correct” is statistical.

💡 Key takeaways

  • TDD is a design feedback tool, not a moral imperative—use it when fast feedback unlocks clarity.

➡️ Next steps

Isolate collaborators with Mocking using unittest.mock.