liveBook · Manning

Test-driven development

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

Test-driven development is a software development practice in which tests are written before implementation and repeatedly run to guide development and detect regressions.

Test-driven development writes tests before implementation, runs them to expose the missing behavior, implements the feature, and reruns the full suite to catch regressions. Tests cannot prove a program has no errors, but they provide a practical check against imagined or discovered bugs. section 2.3.5

Use the cycle incrementally:

  • Add a test for an unimplemented unit and confirm that it fails. section 11.3.2
  • Write the smallest implementation that makes the test pass, then run all tests. section 11.3.2
  • Refactor for readability or structure while using the tests to verify behavior. section 11.5

Testing add1()

Start with def add1(n): pass, then test expected results such as add1(0) == 1, add1(1) == 2, and add1(-1) == 0. Replace pass with return n + 1 and rerun pytest. section 11.3.2

def test_add1():
   assert add1(0) == 1
   assert add1(1) == 2
   assert add1(-1) == 0

Inspect the compact assertion-based test that drives the add1() implementation. section 11.3.2

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines the red-green-refactor cycle and demonstrates it with a small function, but defers how to write tests generally.
Examples
Uses an add1() function, assertion cases for zero and signed values, and a Pytest test run.
What it assumes
Assumes basic Python functions and assertions while postponing general test-writing instruction.
What you can do after
Apply it via Pytest to implement small functions, verify expected behavior, and refactor with regression protection.
How it connects
Connects testing with regression detection, refactoring, functions, assertions, and testing frameworks.

Also explained in

Compare how 15 books explain test-driven development →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.