Test-Driven Development: Red, Green, Refactor

Test-Driven Development: Red, Green, Refactor in Python: You know how to write tests. TDD is a claim about when to write them: before the code, one small test…

Concept Explanation

You know how to write tests. TDD is a claim about when to write them: before the code, one small test at a time, in a fixed three-step cycle.

StepYou doThe rule
🔴 RedWrite one failing test for the next tiny behaviourIt must fail, and for the reason you expect
🟢 GreenWrite the simplest code that passes itUgly is allowed here. Only correctness matters
🔵 RefactorClean it upTests stay green the entire time

Then repeat. Each loop is minutes, not hours.

Why Write the Test First?

The ordering is not ceremony — it changes four things:

  • It forces a decision about the interface. You cannot write assert parse(text) == expected without deciding what parse is called, what it takes, and what it returns. You design the API from the caller's side, which is the side that matters.
  • It proves the test can fail. A test written after working code has never been observed failing. Plenty of them cannot fail — a typo'd assertion or an over-eager mock — and you would never know.
  • It defines "done". The test passing is the finish line. This is the main antidote to speculative code nobody asked for.
  • It makes refactoring safe. You accumulate a safety net as a side effect, so the third step is genuinely available rather than aspirational.

The Discipline That Makes It Work

Two rules do most of the heavy lifting, and both feel wrong at first:

  1. Watch the test fail before making it pass. If it passes immediately, either the behaviour already existed or your test is broken. Both are worth knowing now.
  2. Write the dumbest possible Green. Returning a hardcoded value is a legitimate first step. It feels like cheating. It is actually forcing you to write a second test that rules out the hardcoded answer — and that second test is one you might otherwise have skipped.

When TDD Earns Its Keep

Good fitPoor fit
Business rules, parsers, calculationsExploratory work where you don't know the goal yet
Bug fixes (write the failing case first)UI layout and visual design
Refactoring legacy code (test, then change)Throwaway scripts and notebooks
Anything with clear inputs and outputsPerformance tuning (benchmark, don't unit-test)

TDD is a tool, not an identity. The one place it is close to unarguable is bug fixing: a failing test that reproduces the report, then the fix, gives you a permanent regression guard for free.


Code Example #1 (Basic)

Building a Roman numeral converter, one cycle at a time. Read this as a transcript.

# ---------- CYCLE 1 : Red ----------
# test_roman.py
from roman import to_roman

def test_one():
    assert to_roman(1) == "I"

# $ pytest  ->  ImportError: cannot import name 'to_roman'
# Good. That is a legitimate Red -- the module does not exist yet.
# ---------- CYCLE 1 : Green ----------
# roman.py
def to_roman(n):
    return "I"           # Yes, really. Simplest thing that passes.
# ---------- CYCLE 2 : Red ----------
def test_two():
    assert to_roman(2) == "II"      # fails: got "I"

# ---------- CYCLE 2 : Green ----------
def to_roman(n):
    return "I" * n                  # passes 1, 2, 3 -- and it is still wrong
# ---------- CYCLE 3 : Red ----------
def test_four():
    assert to_roman(4) == "IV"      # fails: got "IIII"

# ---------- CYCLE 3 : Green ----------
NUMERALS = [(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]

def to_roman(n):
    result = ""
    for value, symbol in NUMERALS:
        while n >= value:
            result += symbol
            n -= value
    return result
# ---------- CYCLE 4 : Refactor ----------
# Tests are green. Now improve the code WITHOUT changing behaviour.
NUMERALS = (
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
    (100, "C"),  (90, "XC"),  (50, "L"),  (40, "XL"),
    (10, "X"),   (9, "IX"),   (5, "V"),   (4, "IV"),
    (1, "I"),
)

def to_roman(n: int) -> str:
    if not isinstance(n, int) or not 1 <= n <= 3999:
        raise ValueError("Roman numerals cover 1 to 3999")

    parts = []
    for value, symbol in NUMERALS:
        count, n = divmod(n, value)
        parts.append(symbol * count)
    return "".join(parts)

# Run the suite: still green. That is what makes the rewrite safe.

Notice cycle 2. return "I" * n is obviously wrong, and writing it deliberately is what produced the test for 4 — the first genuinely interesting case. Jumping straight to the final algorithm would have skipped it.

Code Example #2 (Intermediate)

The highest-value use of TDD: fixing a real bug.

# ---------- STEP 1: reproduce the report as a failing test ----------
# Bug #412: "Cart total is wrong when a percentage discount is applied
#            to an item bought in quantity."

import pytest
from decimal import Decimal
from cart import Cart

def test_percentage_discount_applies_to_full_line():
    """Regression test for #412."""
    cart = Cart()
    cart.add("widget", price=Decimal("10.00"), quantity=3)
    cart.apply_discount(percent=10)

    # 3 x 10.00 = 30.00, minus 10% = 27.00
    assert cart.total() == Decimal("27.00")

# $ pytest -k 412
# FAILED  assert Decimal('29.00') == Decimal('27.00')
#
# The bug is now reproduced and pinned. Note the failure is informative:
# 29.00 means the discount was applied to ONE unit, not the line.
# ---------- STEP 2: the smallest fix that turns it green ----------
class Cart:
    def __init__(self):
        self._lines = []
        self._discount_percent = Decimal("0")

    def add(self, name, price, quantity=1):
        self._lines.append({"name": name, "price": price, "quantity": quantity})

    def apply_discount(self, percent):
        self._discount_percent = Decimal(str(percent))

    def total(self):
        subtotal = sum(
            line["price"] * line["quantity"]      # <-- the fix: multiply first
            for line in self._lines
        )
        discount = subtotal * self._discount_percent / 100
        return (subtotal - discount).quantize(Decimal("0.01"))
# ---------- STEP 3: lock in the neighbours before refactoring ----------
@pytest.mark.parametrize("percent, expected", [
    (0,   "30.00"),
    (10,  "27.00"),
    (100, "0.00"),
])
def test_discount_levels(percent, expected):
    cart = Cart()
    cart.add("widget", price=Decimal("10.00"), quantity=3)
    cart.apply_discount(percent=percent)
    assert cart.total() == Decimal(expected)

def test_rejects_impossible_discount():
    cart = Cart()
    with pytest.raises(ValueError):
        cart.apply_discount(percent=150)

That last test is Red again — apply_discount accepts 150 happily — so the cycle continues. This is what TDD looks like in maintenance work, and it is where the practice is least controversial: the bug report becomes a permanent test. It cannot silently return.


Common Mistakes

  1. Writing the test after the code and calling it TDD: you get tests, which is good, but you lose the design pressure and you never observe the test failing.
  2. Skipping Red: if you did not watch it fail, you do not know it works. A test that cannot fail is worse than no test, because it reports safety you do not have.
  3. Testing too much at once: a first test that requires a database, an HTTP client, and three classes leaves you with nothing to do but write all of it. Shrink the step.
  4. Testing implementation instead of behaviour: assert cart._lines[0]["price"] == 10 breaks the moment you rename a private field, even though nothing is wrong. Assert on cart.total().
  5. Refusing the dumb Green: insisting on the final algorithm immediately skips the tests that would have pinned the edge cases.
  6. Never refactoring: stopping at Green leaves the mess permanently. The third step is not optional; it is where the design happens.
  7. Changing tests to match new behaviour without thinking: if a passing test suddenly fails after a change, that is the net working. Decide whether the code or the expectation was wrong — do not reflexively edit the assertion.
  8. Applying TDD to exploration: when you do not yet know what you are building, write a spike, throw it away, then TDD the real thing.

Best Practices

  • Keep cycles to minutes: if you have been Red for twenty minutes, your step was too big. Revert and take a smaller one.
  • Run the suite constantly: pytest-watch (ptw) re-runs on every save, which is what makes short cycles practical.
  • Use pytest -x --ff while cycling: stop at the first failure, and run the previously-failing test first next time.
  • Name tests as sentences: test_rejects_discount_above_100_percent documents the rule; test_discount_2 documents nothing.
  • Start every bug fix with a failing test: this single habit is worth adopting even if you reject the rest of TDD.
  • Assert on public behaviour: tests coupled to internals block the refactoring step they are supposed to enable.
  • Commit at each green: a working state every few minutes makes git bisect and git reset genuinely useful.
  • Let the tests tell you about the design: if a test is hard to write, the code is hard to use. That difficulty is information, not an obstacle.

Practice Exercises

  1. The Full Cycle: TDD a FizzBuzz function from scratch, committing at each green. Write down what your first Green was and whether you were tempted to skip ahead.
  2. The Bug Fix Drill: Find a bug in your own code (or plant one). Write the failing test that reproduces it before touching the implementation, fix it, then add two neighbouring cases. Confirm the original test now fails if you revert the fix.
  3. The Stack: TDD a Stack class supporting push, pop, peek, and is_empty — one test at a time, never writing a line of implementation before a Red. Include pop on an empty stack raising IndexError, and note which test forced you to change your first design decision.