Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: Test-Driven Shopping Cart

Build a shopping cart with test-driven development: write failing pytest tests first, make them pass, refactor, and finish with fixtures, parametrization, Decimal money and coupon rules.

In this project you will build a small shopping cart the way many professional developers do: test first. For each feature you write a failing test (red), write just enough code to pass it (green), then tidy up (refactor). The tests end up documenting every rule, and you can change the code with confidence.

You will practice almost everything from this chapter of the course: fixtures, pytest.raises, parametrization, markers, floating-point and money handling, and a few test-design rules from the previous lesson.

The specification

Our cart must:

  1. start empty with a total of zero;
  2. add items with a name, a unit price and a quantity (default 1); adding the same name again increases the quantity;
  3. refuse invalid input: empty names, non-positive quantities, negative prices;
  4. remove items, raising a clear error for unknown ones;
  5. compute totals with exact decimal money (never floats);
  6. apply a coupon: SAVE10 takes 10 percent off, but only for carts of at least 50.00; unknown coupons are rejected;
  7. add 20 percent VAT on request, rounded to cents.
flowchart LR
    R["RED<br/>write a failing test"] --> G["GREEN<br/>smallest code that passes"] --> F["REFACTOR<br/>clean up, tests stay green"] --> R

Repeat the loop for each rule. Never write production code without a failing test that needs it.

Round 1: red

The project helper writes both files. We start with the tests for rules 1 to 4, and an implementation that does nothing yet, so every test fails for the right reason: "not implemented". A test that has never failed has never proven anything.

Python Red: tests first, nothing implemented

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All five fail with NotImplementedError. That is the red phase.

Round 2: green

Now write the smallest implementation that makes them pass. We store prices as Decimal built from strings, because 0.1 + 0.2 is not 0.3 in floating point, and money must never drift by a cent. Add the tests for rule 3 (validation) in the same round:

Python Green: make the tests pass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Everything passes. Notice how the parametrized test checks five invalid inputs with one body, and how each case asserts that nothing was added, a rule the spec implied but that we only noticed while writing the test.

Round 3: coupons and VAT, test first

Rule 6 is the interesting one: SAVE10 needs a minimum spend of 50.00. Boundaries are where bugs hide, so test just below, exactly at, and above the limit. Write these tests before the code. Then extend Cart with apply_coupon and total_with_vat.

Python Coupon rules and VAT, boundaries included

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Round 4: refactor safely

With all tests green you may restructure freely: move coupons into their own class, replace _lines with a small Line dataclass, extract money() helpers. After each tiny change, rerun the tests. If they stay green, behavior is unchanged. That is the payoff of testing behavior through the public interface.

What to try next

  • Add a coupon type with a fixed amount off, and test the case where the discount exceeds the total (it must not go negative).
  • Add FREESHIP that applies only when the cart contains a physical item. Decide how to model that and write the test first.
  • Protect against a coupon being applied twice.
  • Run pytest --cov=cart --cov-branch --cov-report=term-missing (coverage lesson) and write a test for every missing line, asking whether each one reveals a real rule.
  • Add a Hypothesis property: for any valid cart, 0 <= total() <= subtotal() (Hypothesis lesson).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the correct order of the TDD loop?

    You write a failing test first, implement the minimum to pass, then improve the design while the tests stay green.
  2. 2. Why should money be stored as Decimal built from strings instead of float?

    0.1 * 3 is 0.30000000000000004 in floats. Decimal keeps exact cents.
  3. 3. Why test the values 49.99, 50.00 and 50.01 for the coupon rule?

    Testing just below, at and just above a limit catches off-by-one comparison mistakes.
  4. 4. In the validation test, why assert cart.count() == 0 after the exception?

    Error handling should be atomic: a failed add must not leave partial state behind.

Summary

  • TDD loop: red (failing test), green (minimal code), refactor (tests stay green).
  • Seeing a test fail for the right reason proves it can catch the bug.
  • Use fixtures and factory fixtures for setup, parametrization for many cases with one body.
  • Test boundaries explicitly, and assert that failed operations leave state unchanged.
  • Handle money with Decimal and explicit rounding.

Next: Project: Testing an API Client