Test Suite for a Shopping Cart
Part of the Python Roadmap
In short
This project pulls the whole phase together: a small shopping cart with quantities, discount codes and GST, tested properly with fixtures, parametrize and a mocked price service. It's the kind of code and tests interviewers love to see.
A shopping cart module with add, remove, discount code and GST calculations, covered by a full pytest suite using fixtures, parametrized cases and a mocked price service. It shows you can test real logic properly.

Think of it like this
The supermarket billing counter audit
Before a new billing machine goes live at a DMart, the manager rings up test baskets: empty basket, one item, a discount coupon, a wrong coupon. Each receipt is checked by hand. Your test suite is that audit, run automatically every time the code changes.
Watch it happen
What the suite covers
1/4Three public methods, so three groups of tests.
The big ideas
What you need to know
Inject the dependency
The cart receives a price service instead of creating one, so tests can pass in a mock.
Fixtures build the world
One fixture makes the fake price service, another makes a fresh cart that uses it.
Parametrize the maths
No code, 5% off and 10% off become three rows of one test with expected totals.
Test the failures
Zero quantity and unknown codes must raise. Error paths deserve tests too.
See it in code
Walk through the code
1# cart.py2from dataclasses import dataclass, field3from typing import Protocol4 5CODES = {"WELCOME5": 5, "DIWALI10": 10}6 7 8class PriceService(Protocol):9 def price_of(self, sku: str) -> float: ...10 11 12@dataclass13class Cart:14 prices: PriceService15 items: dict[str, int] = field(default_factory=dict)16 discount: int = 017 18 def add(self, sku: str, qty: int = 1) -> None:19 if qty <= 0:20 raise ValueError("qty must be positive")21 self.items[sku] = self.items.get(sku, 0) + qty22 23 def apply_code(self, code: str) -> None:24 if code not in CODES:25 raise ValueError(f"unknown code {code}")26 self.discount = CODES[code]27 28 def total(self, gst_rate: int = 18) -> float:29 subtotal = sum(self.prices.price_of(s) * q for s, q in self.items.items())30 after_discount = subtotal * (100 - self.discount) / 10031 return round(after_discount * (100 + gst_rate) / 100, 2)32 33 34# test_cart.py35from unittest.mock import Mock36 37import pytest38 39from cart import Cart40 41 42@pytest.fixture43def prices() -> Mock:44 service = Mock()45 service.price_of.side_effect = {"PEN": 10.0, "BOOK": 100.0}.__getitem__46 return service47 48 49@pytest.fixture50def cart(prices: Mock) -> Cart:51 return Cart(prices=prices)52 53 54def test_empty_cart_total_is_zero(cart: Cart) -> None:55 assert cart.total() == 056 57 58def test_add_merges_quantities(cart: Cart) -> None:59 cart.add("PEN", 2)60 cart.add("PEN")61 assert cart.items == {"PEN": 3}62 63 64def test_add_rejects_zero_qty(cart: Cart) -> None:65 with pytest.raises(ValueError, match="positive"):66 cart.add("PEN", 0)67 68 69def test_unknown_code_is_rejected(cart: Cart) -> None:70 with pytest.raises(ValueError, match="unknown code"):71 cart.apply_code("FREE100")72 73 74@pytest.mark.parametrize(75 ("code", "expected"),76 [(None, 118.0), ("WELCOME5", 112.1), ("DIWALI10", 106.2)],77)78def test_total_with_gst_and_codes(cart: Cart, code: str | None, expected: float) -> None:79 cart.add("BOOK")80 if code:81 cart.apply_code(code)82 assert cart.total() == pytest.approx(expected)83 84 85def test_price_looked_up_once_per_sku(cart: Cart, prices: Mock) -> None:86 cart.add("PEN", 3)87 cart.add("BOOK")88 cart.total()89 assert prices.price_of.call_count == 21/6A Protocol describes what a price service looks like, without tying the cart to a real one.
Run pytest -v --cov=cart --cov-report=term-missing. All eight tests pass and every line of cart.py is covered.
Save yourself the pain
Common mistakes
Oops
Creating a real price service inside the Cart class.
Do this instead
Pass it in. Dependency injection is what makes mocking easy.
Oops
Using float money in production code without thinking.
Do this instead
This project rounds to paise for simplicity. Real billing systems often use Decimal or whole paise as int.
Oops
Only testing the happy path.
Do this instead
Empty carts, zero quantities and unknown codes are exactly where real bugs appear.
Your mission
Extend the cart, test first
Quick check
Why does the Cart take prices as an argument instead of creating its own price service?
Go deeper
- 1Write the tests for discount and tax rules before writing the code.
- 2Mock the price lookup so tests never depend on the network.
- 3Run the suite in GitHub Actions and report coverage in the README.
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.