Recipe
Build a function test-first
Use when: you are about to write a function whose behaviour you can describe with examples
Goal: a working function where every behaviour has a test that was seen to fail first
Taught in Fixtures, edge cases, and TDD
Quick recipe
-
1
Choose the simplest thing the function should do that it doesn't do yet.
Example
"900 cents among 3 people is three shares of 300."
Why: small steps keep each failure easy to understand and each fix small.
-
2
Write one test for that behaviour and run it; watch it fail for the reason you expect.
Example
assert split_bill(900, 3) == [300, 300, 300]fails withassert None == [...].Why: a test you've seen fail is a test that can fail.
-
3
Write the simplest code that passes this test, then run every test.
Example
return [total // people] * people.Why: the simplest version shows exactly what the tests demand, and no more.
-
4
Improve names and structure without changing behaviour; re-run the tests after each change.
Example
Add the docstring; the two tests stay green.
Why: the tests prove the clean-up changed nothing they check.
-
5
Go back to step 1 with the next behaviour, until the edge cases are covered.
Example
split_bill(100, 3) == [34, 33, 33], thensplit_bill(10, 0)raisingValueError.Why: each round adds one tested behaviour, so the suite grows with the code.