Test-Driven Development in Python
Part of the Python Roadmap
In short
Most people write code first and tests later, if at all. TDD flips it: write a failing test that describes what you want, then write just enough code to make it pass. You end up with clear requirements and tests for free.
In test-driven development you write a failing test first, write just enough code to pass it, then clean up the code (red, green, refactor). It leads to small, testable functions and clear requirements.

Think of it like this
The tailor's measurements first
A good darzi in Lucknow measures you before cutting a single thread. Shoulder, chest, sleeve, written down. Only then does he cut, and at the trial he checks the kurta against those numbers. In TDD, the test is the measurement, and the code is cut to fit it.
Watch it happen
One turn of the TDD cycle
1/4Write test_valid_pincode before the function exists. Run pytest: it fails with an ImportError. Good, the test works.
The big ideas
What you need to know
Red: see it fail
A test you've never seen fail might be testing nothing. Watching it fail proves it checks the right thing.
Green: simplest code
Write only enough to pass. Resist adding features no test asks for yet.
Refactor: clean safely
Rename, simplify and remove duplication while the tests guard you.
Tiny steps
Each loop takes minutes, not hours. Small steps keep you always close to working code.
How it works
Building is_valid_pincode with TDD
- 1
Test six digits
assert is_valid_pincode("560001"). Fails because the function doesn't exist.
- 2
Make it pass
Return len(pin) == 6 and pin.isdigit().
- 3
Test leading zero
assert not is_valid_pincode("060001"). Fails, since the current code accepts it.
- 4
Fix and refactor
Switch to one regex that checks everything. All tests green.
See it in code
Walk through the code
1# test_pincode.py (written first)2import pytest3 4from pincode import is_valid_pincode5 6 7@pytest.mark.parametrize("pin", ["560001", "110011", "411045"])8def test_accepts_real_pincodes(pin: str) -> None:9 assert is_valid_pincode(pin)10 11 12@pytest.mark.parametrize("pin", ["060001", "56000", "5600011", "56A001", ""])13def test_rejects_bad_pincodes(pin: str) -> None:14 assert not is_valid_pincode(pin)15 16 17# pincode.py (written second, then refactored)18import re19 20PIN_PATTERN = re.compile(r"[1-9][0-9]{5}")21 22 23def is_valid_pincode(pin: str) -> bool:24 return PIN_PATTERN.fullmatch(pin) is not None1/4First, the happy path: real PIN codes from Bengaluru, Delhi and Pune must pass.
The tests describe the rules for an Indian PIN code. The function was written to satisfy them.
Save yourself the pain
Common mistakes
Oops
Writing all the tests for a whole feature before any code.
Do this instead
One failing test at a time. Make it pass, refactor, then write the next one.
Oops
Skipping the refactor step because the tests are green.
Do this instead
Green is the safe moment to clean up. Skipping it piles up messy code fast.
Oops
Writing the code first and then a test that matches whatever it does.
Do this instead
Tests should express what the code should do, decided before you write it.
Your mission
TDD a mobile number validator
Quick check
In red-green-refactor, why do you run the new test before writing any code?
Go deeper
- 1Build a small function, such as a password strength checker, test first.
- 2Commit after each red-green-refactor cycle.
- 3Notice how writing the test first changes how you design the function.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.