QA and Test Automation · Capstone 1 of 4
QA Capstone: a Test Strategy and Automated Suite for an Online Shop
Plan and build the testing for a whole product: a risk-based strategy, 48 API and UI tests tagged with requirement ids, a traceability report, a matrix that proves the suite catches all 11 planted shop bugs, a go/no-go report and a CI workflow.
⏱ 420 minIntermediate💸 Free8 milestones
Python 3.12pytesthttpxpytest-playwrightPlaywright (Chromium)GitHub Actions
Overview video
What you will build
A repository shoprung-quality you can show in an interview: the plan and the proof that it works.
- docs/: a one-page test strategy and a risk register with a severity for every area.
- tests/api: 43 pytest + httpx tests for accounts, search, cart, prices and orders, each tagged with its requirement.
- tests/ui: 5 Playwright journeys in Python: login error, search, out of stock, a coupon at exactly $50.00, an order.
- tools/trace.py: which requirements have tests (31 of 41) and which do not, by name.
- tools/bug_matrix.py: switches on each of ShopRung's 11 shop bugs in turn; the suite catches all 11.
- tools/readiness.py: a one-page go/no-go report for a release candidate, plus a GitHub Actions workflow.
Before you start
- The episodes behind it: Test strategy for a product, Risk-based testing, Quality metrics and Release readiness.
- Labs that teach the parts: Test cases for a checkout, A pytest API suite, Playwright with Python and Suites in GitHub Actions.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start and leave it running. Open its requirements: every test you write points at one of those ids.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Make the project
Python 3.12 or newer (py on Windows). Create requirements.txt, pytest.ini and .gitignore with the contents below, install, download Chromium for Playwright, and start a Git repository. Run the activate line again in every new terminal.
mkdir -p shoprung-quality && cd shoprung-quality
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
playwright install chromium
git initmkdir -p shoprung-quality && cd shoprung-quality
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
playwright install --with-deps chromium
git initmkdir shoprung-quality; cd shoprung-quality
py -m venv .venv; .venv\Scripts\Activate.ps1
pip install -r requirements.txt
playwright install chromium
git init Successfully installed ... httpx-0.28.1 ... playwright-1.63.0 ... pytest-8.3.4 ... pytest-playwright-0.10.0 ... Initialized empty Git repository in .../shoprung-quality/.git/
A strategy and a risk register
Decide what to test, how deep, and when it is enough.
Before any code, write docs/strategy.md (one page) and docs/risks.csv. The strategy names the scope (what you test and what you leave to other suites), the layers (which tool checks what, and when it runs), the rules every test follows, the exit criteria for a release, and the known gaps. Keep it short enough that a developer reads it.
The risk register scores each area as likelihood x impact (1 to 3 each) and gives the severity if a requirement there breaks. Columns: area,requirements,likelihood,impact,score,severity; requirements is an id or a pattern like PRICE-*. Put specific rows before patterns: a leak of another customer's order (ORD-7) is critical even though other order rules are "only" high. The readiness report in milestone 8 reads this file.
docs/strategy.mdhas sections for scope, risks, layers, rules for tests, exit criteria and known gaps.docs/risks.csvcovers ACC, SRCH, CART, PRICE, ORD and NF, and its first matching row for ORD-7 says critical.- Someone else can read the strategy in under 5 minutes and say what runs on every pull request.
Hints
- Start from the requirements page: group the ids by area, then ask "what does a failure here cost?"
- Likelihood goes up for complex rules and frequent change (coupons); impact for money, data and legal risk.
- Known gaps are a decision, not a failure: write which requirements have no test yet, and why.
Show the reference solution for milestone 1
Try it yourself first. This is one good way to do it, not the only one.
# Test strategy: ShopRung 1.0
## Scope
- **In scope:** accounts, search, cart, prices and coupons, orders (requirements ACC, SRCH, CART, PRICE, ORD) and
the JSON error format (NF-4), through the API and the main web journeys.
- **Out of scope here:** the support chat (AI-1 to AI-8) has its own eval and red-team suites; browser and
phone coverage (NF-1) and accessibility (NF-2) are separate checks.
## Risks first
The risk register is `docs/risks.csv`: likelihood x impact per area, and the severity if a requirement there breaks.
Money (prices and coupons) and other customers' data (ORD-7) get the most tests and the deepest boundaries.
## Layers
| Layer | Tool | What it checks | Runs |
| --- | --- | --- | --- |
| API | pytest + httpx | every rule with boundaries, two users, the status flow | every pull request |
| UI | pytest-playwright (Chromium) | 5 journeys: login error, search, out of stock, coupon at $50, order | every pull request |
| Bug matrix | `tools/bug_matrix.py` | each planted bug is caught by at least one test | weekly, and when tests change |
| Readiness | `tools/readiness.py` | a release candidate against the exit criteria | before each release |
## Rules for every test
- Names its requirement with `@pytest.mark.req("PRICE-3")`; `tools/trace.py` fails if a test has none.
- Starts from fresh data (`POST /api/test/reset`) and never depends on another test.
- Tests the exact boundary and the value just past it.
- Has been seen failing: the bug matrix proves it against ShopRung's planted bugs.
## Exit criteria for a release
- Both suites green; no open critical or high bug.
- Every high-risk requirement has a test (`tools/trace.py`).
- `tools/readiness.py` recommends GO; the product owner decides.
## Known gaps (decided, not forgotten)
ACC-1, ACC-5, ACC-7, SRCH-1, CART-5, PRICE-8, ORD-8 and NF-1 to NF-3 have no automated test yet. ACC-7 (2-hour login)
needs a controllable clock; the rest are next in risk order. - Saying what is out of scope is what makes the rest believable.line 3
- Each layer has a job and a moment it runs.line 14
- Agreed before testing, used in milestone 8.line 27
area,requirements,likelihood,impact,score,severity
order privacy,ORD-7,2,3,6,critical
prices and coupons,PRICE-*,3,3,9,high
orders and stock,ORD-*,2,3,6,high
accounts,ACC-*,1,3,3,medium
cart,CART-*,2,2,4,medium
search,SRCH-*,2,2,4,low
non-functional,NF-*,1,2,2,low - Specific row first: the first match wins.line 2
- Highest score: many rules, frequent change, money.line 3
The project, and accounts and search
Fixtures every test shares, and the first tagged tests.
Write tests/conftest.py: the ShopRung address from BASE_URL (default http://localhost:8080), a session-wide client that stops the run with a clear message if the shop is down, an autouse fixture that resets the data before every test, and a login("alice") factory plus alice, bob and admin fixtures.
Then tests/api/test_accounts.py for ACC and SRCH, and the error format NF-4. Every test carries @pytest.mark.req("ACC-2") (registered in pytest.ini). Test boundaries exactly: a 50-character name is accepted, 51 refused; a 1-character search refused, 2 and 50 accepted, 51 refused. Search must answer in under a second (SRCH-5).
pytest tests/api/test_accounts.pypasses: 15 tests.- Every test in the file has a
reqmarker. - With ShopRung stopped, the run ends at once with "ShopRung is not running at http://localhost:8080".
Hints
- Use
pytest.mark.parametrizefor boundary pairs: one test function, several cases. - The login message is the same for a wrong password and an unknown email (ACC-6): compare the whole JSON.
- For SRCH-5, time the request with
time.perf_counter()around it.
Show the reference solution for milestone 2
Try it yourself first. This is one good way to do it, not the only one.
"""Shared setup: ShopRung's address, a fresh shop before every test, and logged-in API clients."""
import os
import httpx
import pytest
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
USERS = {
"alice": ("alice@shoprung.test", "Alice123!"),
"bob": ("bob@shoprung.test", "Bob12345!"),
"admin": ("admin@shoprung.test", "Admin123!"),
}
@pytest.fixture(scope="session")
def api():
"""A client with no login, shared by the whole run."""
with httpx.Client(base_url=BASE_URL, timeout=10) as client:
try:
client.get("/api/health")
except httpx.ConnectError:
pytest.exit(f"ShopRung is not running at {BASE_URL}. Start it with: npm start", returncode=2)
yield client
@pytest.fixture(autouse=True)
def fresh_shop(api):
"""Every test starts from ShopRung's seed data. The bug switch is not changed."""
assert api.post("/api/test/reset").status_code == 200
@pytest.fixture
def login(api):
"""login("alice") returns a client that sends Alice's token."""
opened = []
def _login(name):
email, password = USERS[name]
r = api.post("/api/auth/login", json={"email": email, "password": password})
assert r.status_code == 200, r.text
client = httpx.Client(base_url=BASE_URL, timeout=10, headers={"Authorization": f"Bearer {r.json()['token']}"})
opened.append(client)
return client
yield _login
for client in opened:
client.close()
@pytest.fixture
def alice(login):
return login("alice")
@pytest.fixture
def bob(login):
return login("bob")
@pytest.fixture
def admin(login):
return login("admin") - A clear stop beats 48 identical connection errors.line 22
- Every test starts from the seed data. The bug switch is left as it is: milestone 7 needs that.line 27
"""Accounts (ACC) and search (SRCH)."""
import time
import pytest
@pytest.mark.smoke
@pytest.mark.req("ACC-6")
def test_wrong_password_and_unknown_email_get_the_same_message(api):
wrong = api.post("/api/auth/login", json={"email": "alice@shoprung.test", "password": "Wrong123!"})
unknown = api.post("/api/auth/login", json={"email": "nobody@shoprung.test", "password": "Wrong123!"})
assert wrong.status_code == unknown.status_code == 401
assert wrong.json() == unknown.json() == {"error": "invalid_credentials", "message": "Email or password is wrong"}
@pytest.mark.req("ACC-2")
@pytest.mark.parametrize("length, status", [(50, 201), (51, 400)])
def test_name_length_limit(api, length, status):
r = api.post("/api/auth/signup", json={"name": "N" * length, "email": f"n{length}@example.test", "password": "Passw0rd!"})
assert r.status_code == status, r.text
if status == 400:
assert r.json()["message"] == "Name must be 1 to 50 characters"
@pytest.mark.req("ACC-3")
def test_email_is_not_case_sensitive(api):
r = api.post("/api/auth/login", json={"email": "Alice@ShopRung.TEST", "password": "Alice123!"})
assert r.status_code == 200
@pytest.mark.req("ACC-4")
def test_one_account_per_email(api):
r = api.post("/api/auth/signup", json={"name": "Alice Two", "email": "ALICE@shoprung.test", "password": "Passw0rd!"})
assert r.status_code == 409
assert r.json()["error"] == "email_taken"
@pytest.mark.req("ACC-8")
def test_cart_needs_a_login(api):
assert api.get("/api/cart").status_code == 401
@pytest.mark.req("SRCH-2")
def test_search_is_not_case_sensitive(api):
names = [[p["name"] for p in api.get("/api/products", params={"q": q}).json()["items"]] for q in ("mug", "MUG", "Mug")]
assert names[0] == names[1] == names[2] == ["Green Build Mug", "Red Build Mug"]
@pytest.mark.req("SRCH-3")
@pytest.mark.parametrize("text, status", [("a", 400), ("ab", 200), ("x" * 50, 200), ("x" * 51, 400)])
def test_search_text_length(api, text, status):
assert api.get("/api/products", params={"q": text}).status_code == status
@pytest.mark.req("SRCH-5")
def test_search_answers_in_under_a_second(api):
start = time.perf_counter()
assert api.get("/api/products", params={"q": "pack"}).status_code == 200
assert time.perf_counter() - start < 1.0
@pytest.mark.req("NF-4")
@pytest.mark.parametrize("method, path, body", [
("POST", "/api/auth/login", {"email": "x@example.test", "password": "nope"}),
("GET", "/api/products?q=a", None),
("GET", "/api/products/999", None),
])
def test_errors_are_json_with_error_and_message(api, method, path, body):
r = api.request(method, path, json=body)
assert r.status_code >= 400
assert r.headers["content-type"].startswith("application/json")
assert set(r.json()) == {"error", "message"} - The requirement id, read by milestones 6 and 8.line 16
- At the limit and one past it.line 17
- A non-functional rule, checked in the same suite.line 59
pytest tests/api/test_accounts.py -qpytest tests/api/test_accounts.py -qpytest tests/api/test_accounts.py -q ............... [100%] 15 passed in 0.86s
Cart and prices
The highest-risk area, tested at every boundary.
Write tests/api/test_cart.py (CART-1 to CART-6) and tests/api/test_prices.py (PRICE-2 to PRICE-10). Build carts from real products so the subtotal lands exactly where you need it. Useful: 4 x Clean Code Notebook ($12.50) = $50.00; Testing Field Guide ($24.99) + 5 x Sticker Pack ($4.99) = $49.94; 2 x Testing Field Guide + 1 Sticker Pack = $54.97, whose 10% is 549.7 cents (PRICE-6 says $5.50).
Cover: quantity 0, 1, 10, 11 and adding to a line already at 10; more than the stock; out of stock; SAVE10 at $50.00 and below; FLAT5 at $20.00 and $19.96; the expired WELCOME15; an unknown code named in capitals; free shipping at exactly $75.00 and not at $74.99; and SAVE10 on $80.00, where $72.00 after the discount still pays shipping.
pytest tests/api/test_cart.py tests/api/test_prices.pypasses: 20 tests.- With ShopRung's
coupon-boundarybug on,test_save10_at_exactly_50fails. - Amounts are compared in cents (
subtotalCents,discountCents...), never as floats.
Hints
- Product ids: 1 notebook $12.50, 2 field guide $24.99, 5 red mug (stock 0), 6 T-shirt $20.00, 7 hoodie $49.99, 8 keyboard $75.00, 11 sticker pack $4.99.
- A helper
cart_with(client, [(product_id, quantity)], code)keeps each test to three lines. - Switch a bug on with
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}', and off with[].
Show the reference solution for milestone 3
Try it yourself first. This is one good way to do it, not the only one.
"""Cart rules (CART)."""
import pytest
def add(client, product_id, quantity=1):
return client.post("/api/cart/items", json={"productId": product_id, "quantity": quantity})
@pytest.mark.smoke
@pytest.mark.req("CART-1")
def test_add_a_product(alice):
r = add(alice, 1, 2)
assert r.status_code == 200
assert r.json()["items"][0]["quantity"] == 2
@pytest.mark.req("CART-2")
@pytest.mark.parametrize("quantity, status", [(0, 400), (1, 200), (10, 200), (11, 400)])
def test_quantity_limits(alice, quantity, status):
assert add(alice, 4, quantity).status_code == status
@pytest.mark.req("CART-2")
def test_adding_to_a_line_cannot_pass_ten(alice):
assert add(alice, 4, 10).status_code == 200
r = add(alice, 4, 1)
assert r.status_code == 400
assert r.json() == {"error": "invalid_quantity", "message": "Quantity must be between 1 and 10"}
@pytest.mark.req("CART-3")
def test_cannot_add_more_than_the_stock(alice):
r = add(alice, 3, 4) # The Bug Hunter's Diary: 3 in stock
assert r.status_code == 409
assert "3" in r.json()["message"]
@pytest.mark.req("CART-4")
def test_out_of_stock_cannot_be_added(alice):
r = add(alice, 5)
assert r.status_code == 409
assert r.json() == {"error": "out_of_stock", "message": "Red Build Mug is out of stock"}
@pytest.mark.req("CART-6")
def test_cart_survives_a_new_login(alice, login):
add(alice, 1, 3)
again = login("alice")
assert again.get("/api/cart").json()["itemCount"] == 3 - The second half of CART-2, often missed.line 24
"""Coupons, rounding, shipping and totals (PRICE). Amounts in cents."""
import pytest
def cart_with(client, lines, code=None):
for product_id, quantity in lines:
assert client.post("/api/cart/items", json={"productId": product_id, "quantity": quantity}).status_code == 200
if code:
return client.post("/api/cart/coupon", json={"code": code})
return client.get("/api/cart")
@pytest.mark.smoke
@pytest.mark.req("PRICE-3")
def test_save10_at_exactly_50(alice):
r = cart_with(alice, [(1, 4)], "SAVE10") # 4 x $12.50 = $50.00
assert r.status_code == 200, r.text
c = r.json()
assert (c["subtotalCents"], c["discountCents"], c["shippingCents"], c["totalCents"]) == (5000, 500, 499, 4999)
@pytest.mark.req("PRICE-3")
def test_save10_below_50_is_refused(alice):
r = cart_with(alice, [(2, 1), (11, 5)], "SAVE10") # $24.99 + 5 x $4.99 = $49.94
assert r.status_code == 400
assert r.json()["error"] == "coupon_not_applicable"
@pytest.mark.req("PRICE-4")
@pytest.mark.parametrize("lines, status", [([(6, 1)], 200), ([(11, 4)], 400)]) # $20.00 and $19.96
def test_flat5_minimum(alice, lines, status):
assert cart_with(alice, lines, "FLAT5").status_code == status
@pytest.mark.req("PRICE-5")
def test_expired_welcome15_is_refused(alice):
r = cart_with(alice, [(8, 1)], "WELCOME15")
assert r.status_code == 400
assert r.json()["message"] == "This coupon has expired"
@pytest.mark.req("PRICE-6")
def test_half_a_cent_rounds_up(alice):
c = cart_with(alice, [(2, 2), (11, 1)], "SAVE10").json() # $54.97: 10% is 549.7 cents
assert c["discountCents"] == 550
@pytest.mark.req("PRICE-2")
@pytest.mark.req("PRICE-7")
def test_unknown_code_is_named_in_capitals(alice):
r = cart_with(alice, [(1, 1)], "free100")
assert r.status_code == 404
assert r.json()["message"] == "No coupon called FREE100"
@pytest.mark.req("PRICE-9")
@pytest.mark.parametrize("lines, shipping", [
([(8, 1)], 0), # keyboard: exactly $75.00
([(7, 1), (1, 2)], 499), # hoodie + 2 notebooks: $74.99
])
def test_free_shipping_from_75(alice, lines, shipping):
assert cart_with(alice, lines).json()["shippingCents"] == shipping
@pytest.mark.req("PRICE-9")
def test_free_shipping_uses_the_subtotal_after_the_discount(alice):
c = cart_with(alice, [(6, 4)], "SAVE10").json() # $80.00 - $8.00 = $72.00
assert (c["discountCents"], c["shippingCents"]) == (800, 499)
@pytest.mark.req("PRICE-10")
def test_total_is_subtotal_minus_discount_plus_shipping(alice):
c = cart_with(alice, [(1, 4)], "SAVE10").json()
assert c["totalCents"] == c["subtotalCents"] - c["discountCents"] + c["shippingCents"] - Subtotal, discount, shipping, total: all four, exactly.line 19
- The rounding rule no earlier suite in the course tested.line 43
- Free shipping uses the subtotal after the discount.line 67
pytest tests/api/test_cart.py tests/api/test_prices.py -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
pytest tests/api/test_prices.py -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'pytest tests/api/test_cart.py tests/api/test_prices.py -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
pytest tests/api/test_prices.py -q
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'pytest tests/api/test_cart.py tests/api/test_prices.py -q
curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[\"coupon-boundary\"]}'
pytest tests/api/test_prices.py -q
curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[]}' 20 passed in 1.68s ... FAILED tests/api/test_prices.py::test_save10_at_exactly_50 - AssertionError: ... FAILED tests/api/test_prices.py::test_total_is_subtotal_minus_discount_plus_shipping 2 failed, 9 passed in 0.89s
Orders and who sees them
The status flow, stock, and a second customer.
Write tests/api/test_orders.py (ORD-1 to ORD-7). Placing an order empties the cart and reduces the stock; cancelling puts it back; an empty cart cannot be ordered; Alice's seed data includes a SHIPPED order, which cannot be cancelled; a customer can pay but only an admin can ship; and Bob gets "not found" for Alice's order while an admin sees it.
pytest tests/api/test_orders.pypasses: 8 tests.- At least one test uses two logged-in users at once (ORD-7).
- Stock checks read the product before and after, instead of assuming the seed numbers.
Hints
- Find the shipped order from Alice's order list rather than hard-coding its id.
- ORD-5: Alice pays (
/pay), then/shipas Alice is 403, as the admin it works.
Show the reference solution for milestone 4
Try it yourself first. This is one good way to do it, not the only one.
"""Orders (ORD): placing, stock, the status flow and who can see what."""
import pytest
def place(client, lines=((1, 2),)):
for product_id, quantity in lines:
client.post("/api/cart/items", json={"productId": product_id, "quantity": quantity})
r = client.post("/api/orders")
assert r.status_code == 201, r.text
return r.json()
def stock(api, product_id):
return api.get(f"/api/products/{product_id}").json()["stock"]
@pytest.mark.smoke
@pytest.mark.req("ORD-1")
def test_order_is_placed_and_empties_the_cart(alice):
order = place(alice)
assert order["status"] == "PLACED"
assert alice.get("/api/cart").json()["itemCount"] == 0
@pytest.mark.req("ORD-2")
def test_order_reduces_the_stock(api, alice):
before = stock(api, 1)
place(alice, [(1, 3)])
assert stock(api, 1) == before - 3
@pytest.mark.req("ORD-3")
def test_empty_cart_cannot_be_ordered(alice):
r = alice.post("/api/orders")
assert r.status_code == 400
assert r.json()["error"] == "empty_cart"
@pytest.mark.req("ORD-4")
def test_shipped_order_cannot_be_cancelled(alice):
shipped = [o for o in alice.get("/api/orders").json() if o["status"] == "SHIPPED"][0]
r = alice.post(f"/api/orders/{shipped['id']}/cancel")
assert r.status_code == 409
assert r.json()["message"] == "Cannot cancel an order that is SHIPPED"
@pytest.mark.req("ORD-5")
def test_only_an_admin_can_ship(alice, admin):
order = place(alice)
assert alice.post(f"/api/orders/{order['id']}/pay").status_code == 200
assert alice.post(f"/api/orders/{order['id']}/ship").status_code == 403
assert admin.post(f"/api/orders/{order['id']}/ship").json()["status"] == "SHIPPED"
@pytest.mark.req("ORD-6")
def test_cancel_puts_items_back(api, alice):
before = stock(api, 1)
order = place(alice, [(1, 2)])
assert alice.post(f"/api/orders/{order['id']}/cancel").json()["status"] == "CANCELLED"
assert stock(api, 1) == before
@pytest.mark.req("ORD-7")
def test_customer_cannot_open_another_customers_order(alice, bob):
order = place(alice)
r = bob.get(f"/api/orders/{order['id']}")
assert r.status_code == 404
assert r.json()["error"] == "not_found"
@pytest.mark.req("ORD-7")
def test_admin_sees_every_order(alice, admin):
order = place(alice)
assert admin.get(f"/api/orders/{order['id']}").status_code == 200 - The critical row of the risk register gets its own test.line 64
- Relative to the current stock, so the test survives seed changes.line 27
pytest tests/api/test_orders.py -qpytest tests/api/test_orders.py -qpytest tests/api/test_orders.py -q ........ [100%] 8 passed in 0.68s
Five journeys through the screens
Check the screens use the rules, without retesting every rule.
The API tests cover the rules; the UI tests check that the web shop shows them. Write tests/ui/conftest.py (a base_url from BASE_URL, and a logged_in page that logs Alice in through the form) and tests/ui/test_shop.py with five journeys: the wrong-password message, searching "MUG" finds 2 products, the Red Build Mug's button is disabled, SAVE10 at exactly $50.00 in the cart shows -$5.00 and $49.99, and placing an order shows PLACED.
Use role and label locators (get_by_role, get_by_label) and ShopRung's data-testid values; let expect wait, never sleep.
pytest tests/uipasses: 5 tests in Chromium.- No
time.sleeporwait_for_timeoutanywhere in the UI tests. pytestwith no arguments runs all 48 tests.
Hints
- Every product card has a button named "Add
to cart". - The header shows "Hi, Alice Shah" in
data-testid="user-name"once the login worked. - Run
pytest tests/ui --headed --slowmo 300to watch a journey.
Show the reference solution for milestone 5
Try it yourself first. This is one good way to do it, not the only one.
"""UI tests run in Chromium through pytest-playwright, against the same ShopRung as the API tests."""
import os
import pytest
from playwright.sync_api import Page, expect
@pytest.fixture(scope="session")
def base_url():
return os.getenv("BASE_URL", "http://localhost:8080")
@pytest.fixture
def logged_in(page: Page):
"""A page with Alice logged in through the login form."""
page.goto("/#/login")
page.get_by_label("Email").fill("alice@shoprung.test")
page.get_by_label("Password").fill("Alice123!")
page.get_by_role("button", name="Log in").click()
expect(page.get_by_test_id("user-name")).to_have_text("Hi, Alice Shah")
return page """The main journeys through the web shop. API tests cover the rules; these check the screens use them."""
import re
import pytest
from playwright.sync_api import Page, expect
def add_from_list(page: Page, name: str, times: int = 1):
for _ in range(times):
page.get_by_role("button", name=f"Add {name} to cart").click()
@pytest.mark.smoke
@pytest.mark.req("ACC-6")
def test_wrong_password_shows_the_message(page: Page):
page.goto("/#/login")
page.get_by_label("Email").fill("alice@shoprung.test")
page.get_by_label("Password").fill("Wrong123!")
page.get_by_role("button", name="Log in").click()
expect(page.get_by_role("alert")).to_have_text("Email or password is wrong")
@pytest.mark.req("SRCH-2")
@pytest.mark.req("SRCH-4")
def test_search_in_capitals_finds_the_mugs(page: Page):
page.goto("/")
page.get_by_role("searchbox", name="Search products").fill("MUG")
page.get_by_role("button", name="Search").click()
expect(page.get_by_test_id("result-count")).to_have_text("2 products")
@pytest.mark.req("CART-4")
def test_out_of_stock_cannot_be_added(logged_in: Page):
expect(logged_in.get_by_role("button", name="Add Red Build Mug to cart")).to_be_disabled()
@pytest.mark.req("PRICE-3")
@pytest.mark.req("PRICE-1")
def test_save10_at_exactly_50_in_the_cart(logged_in: Page):
page = logged_in
add_from_list(page, "Clean Code Notebook", 4)
expect(page.get_by_test_id("cart-count")).to_have_text("4")
page.get_by_test_id("cart-link").click()
page.get_by_label("Coupon code").fill("SAVE10")
page.get_by_role("button", name="Apply").click()
expect(page.get_by_test_id("discount")).to_have_text("-$5.00")
expect(page.get_by_test_id("total")).to_have_text("$49.99")
@pytest.mark.req("ORD-1")
def test_place_an_order(logged_in: Page):
page = logged_in
add_from_list(page, "Clean Code Notebook")
expect(page.get_by_test_id("cart-count")).to_have_text("1")
page.get_by_test_id("cart-link").click()
page.get_by_test_id("checkout").click()
expect(page.get_by_test_id("order-placed")).to_be_visible()
expect(page.get_by_test_id("order-status")).to_have_text("PLACED")
expect(page).to_have_url(re.compile(r"#/order/\d+")) - SRCH-2 seen by a shopper, with SRCH-4's count.line 29
- The same boundary as the API test, through the screen.line 47
pytest -qpytest -qpytest -q ................................................ [100%] 48 passed in 5.29s
Traceability
Which requirements have tests, and which do not.
Add a small pytest plugin in the project-root conftest.py: an option --req-map FILE that, after collection, writes {test id: [requirement ids]}. Then tools/trace.py reads ShopRung's /requirements.md, collects the tests with --req-map, and prints coverage per area, the requirements with no test, and any test without a requirement (which fails the script).
Our result: 31 of 41 requirements, and the 10 without a test are exactly the known gaps in the strategy. The support chat's AI-1 to AI-8 are out of scope.
python tools/trace.pyprints coverage per area and "31 of 41" (or your own number) and exits 0.- Remove a
reqmarker from any test: the script lists it and exits 1. - The "no test" list matches the known gaps in
docs/strategy.md.
Hints
item.iter_markers("req")gives everyreqmarker on a collected test, including stacked ones.- Requirement ids start a line in requirements.md:
re.findall(r"^([A-Z]+-\d+)\s", text, re.M).
Show the reference solution for milestone 6
Try it yourself first. This is one good way to do it, not the only one.
"""Project-wide pytest plugin: `--req-map FILE` writes which requirements each collected test checks."""
import json
from pathlib import Path
def pytest_addoption(parser):
parser.addoption("--req-map", default=None, help="write {test id: [requirement ids]} to this JSON file")
def pytest_collection_finish(session):
path = session.config.getoption("--req-map")
if path:
reqs = {item.nodeid: [m.args[0] for m in item.iter_markers("req")] for item in session.items}
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text(json.dumps(reqs, indent=2)) - Runs once, after pytest has found every test.line 10
"""Traceability: which ShopRung requirements have at least one test, and which have none.
python tools/trace.py (ShopRung running: it reads /requirements.md from the shop)
"""
import json
import os
import re
import subprocess
import sys
import urllib.request
from collections import defaultdict
from pathlib import Path
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
MAP = Path("reports/req-map.json")
OUT_OF_SCOPE = {"AI"} # the support chat has its own suites (eval set, red team)
def requirement_ids() -> list[str]:
text = urllib.request.urlopen(f"{BASE_URL}/requirements.md", timeout=10).read().decode()
return re.findall(r"^([A-Z]+-\d+)\s", text, re.M)
def collected() -> dict[str, list[str]]:
subprocess.run([sys.executable, "-m", "pytest", "--collect-only", "-q", "--req-map", str(MAP)],
check=True, capture_output=True)
return json.loads(MAP.read_text())
def main() -> None:
reqs = [r for r in requirement_ids() if r.split("-")[0] not in OUT_OF_SCOPE]
tests_for = defaultdict(list)
untagged = []
for test, ids in collected().items():
for rid in ids:
tests_for[rid].append(test)
if not ids:
untagged.append(test)
by_area = defaultdict(lambda: [0, 0])
for rid in reqs:
area = rid.split("-")[0]
by_area[area][1] += 1
by_area[area][0] += bool(tests_for.get(rid))
covered = sum(bool(tests_for.get(r)) for r in reqs)
print(f"{'area':<6} {'covered':>8}")
for area, (c, n) in by_area.items():
print(f"{area:<6} {c:>4} of {n}")
print(f"total {covered} of {len(reqs)} requirements have a test ({covered / len(reqs):.0%})")
print("no test:", " ".join(r for r in reqs if not tests_for.get(r)) or "none")
unknown = sorted(set(tests_for) - set(reqs) - {r for r in tests_for if r.split("-")[0] in OUT_OF_SCOPE})
if unknown:
print("tests point at unknown requirements:", " ".join(unknown))
if untagged:
print(f"{len(untagged)} test(s) have no requirement:", *untagged, sep="\n ")
sys.exit(1 if unknown or untagged else 0)
if __name__ == "__main__":
main() - Scope from the strategy, in code.line 16
- A CI gate: every test names its requirement.line 55
python tools/trace.pypython tools/trace.pypython tools/trace.py area covered ACC 5 of 8 SRCH 4 of 5 CART 5 of 6 PRICE 9 of 10 ORD 7 of 8 NF 1 of 4 total 31 of 41 requirements have a test (76%) no test: ACC-1 ACC-5 ACC-7 SRCH-1 CART-5 PRICE-8 ORD-8 NF-1 NF-2 NF-3
Prove it: the bug matrix
Coverage says tests exist; this says they catch bugs.
Write tools/bug_matrix.py. It reads ShopRung's planted bugs from GET /api/test/bugs (leaving out the support-chat ones), checks the suite is green with no bug on, then for each bug: switch it on, run the whole suite with a JUnit XML report, and record which tests failed. It always switches the bugs off again, and writes reports/bug-matrix.md.
Our suite catches all 11 shop bugs, including the two that every earlier suite in this course missed: rounding (PRICE-6) and the name length (ACC-2). Note which bugs only the UI or only one test catches: those tests are the ones you must never delete.
python tools/bug_matrix.pyends with "caught 11 of 11" (or names what you miss) and writesreports/bug-matrix.md.- Afterwards
GET /api/test/bugsshows"active": []. - Every bug the matrix says is caught names at least one test.
Hints
- Run pytest with
subprocess.run([sys.executable, "-m", "pytest", "-q", f"--junitxml={xml}"]), then read<testcase>elements that contain<failure>or<error>. - Put the bug loop in
try/finallyso an error cannot leave a bug switched on. - slow-search takes longest: the UI search waits for its timeout.
Show the reference solution for milestone 7
Try it yourself first. This is one good way to do it, not the only one.
"""Run the whole suite once per planted ShopRung bug and record which tests catch it.
python tools/bug_matrix.py (about a minute; writes reports/bug-matrix.md)
"""
import json
import os
import subprocess
import sys
import time
import urllib.request
import xml.etree.ElementTree as ET
from pathlib import Path
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
REPORTS = Path("reports")
def call(method: str, path: str, body=None) -> dict:
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE_URL + path, data=data, method=method, headers={"Content-Type": "application/json"})
return json.load(urllib.request.urlopen(req, timeout=10))
def run_suite(name: str) -> tuple[list[str], float]:
"""Run pytest; return the ids of the failed tests and the time taken."""
xml = REPORTS / f"junit-{name}.xml"
start = time.perf_counter()
subprocess.run([sys.executable, "-m", "pytest", "-q", f"--junitxml={xml}"], capture_output=True)
failed = [f"{c.get('classname').split('.')[-1]}::{c.get('name')}"
for c in ET.parse(xml).iter("testcase") if c.find("failure") is not None or c.find("error") is not None]
return failed, time.perf_counter() - start
def main() -> None:
REPORTS.mkdir(exist_ok=True)
bugs = {name: text for name, text in call("GET", "/api/test/bugs")["known"].items() if not name.startswith("chat-")}
call("POST", "/api/test/bugs", {"enabled": []})
base, secs = run_suite("baseline")
print(f"baseline: {len(base)} failed ({secs:.1f} s)")
if base:
sys.exit("The suite must be green on the normal shop first: " + ", ".join(base))
rows = []
try:
for name, text in bugs.items():
call("POST", "/api/test/bugs", {"enabled": [name]})
failed, secs = run_suite(name)
rows.append((name, text, failed))
print(f"{name:<24} {'CAUGHT' if failed else 'missed'} {len(failed)} failed ({secs:.1f} s)")
finally:
call("POST", "/api/test/bugs", {"enabled": []})
caught = sum(bool(f) for _, _, f in rows)
lines = ["# Bug detection matrix", "", f"{caught} of {len(rows)} planted bugs caught (support-chat bugs are out of scope).", "",
"| Bug | What it breaks | Caught by |", "| --- | --- | --- |"]
lines += [f"| {n} | {t} | {', '.join(f'`{x}`' for x in f) or '**missed**'} |" for n, t, f in rows]
(REPORTS / "bug-matrix.md").write_text("\n".join(lines) + "\n")
print(f"caught {caught} of {len(rows)}; see reports/bug-matrix.md")
if __name__ == "__main__":
main() - The chat has its own suites.line 36
- A matrix on a red suite proves nothing.line 41
- Never leave the shop broken for the next person.line 49
python tools/bug_matrix.pypython tools/bug_matrix.pypython tools/bug_matrix.py baseline: 0 failed (5.6 s) coupon-boundary CAUGHT 3 failed (10.6 s) quantity-limit CAUGHT 2 failed (5.3 s) free-shipping-boundary CAUGHT 1 failed (5.4 s) search-case CAUGHT 2 failed (10.5 s) cancel-shipped CAUGHT 1 failed (5.2 s) discount-rounding CAUGHT 1 failed (5.3 s) stock-not-reduced CAUGHT 2 failed (5.5 s) expired-coupon CAUGHT 1 failed (5.4 s) name-length CAUGHT 1 failed (5.4 s) slow-search CAUGHT 1 failed (23.0 s) order-leak CAUGHT 1 failed (5.2 s) caught 11 of 11; see reports/bug-matrix.md
Go/no-go, and CI
A release decision from evidence, on every change.
Write tools/readiness.py. It switches on the bugs you name (practise with mystery: 5 bugs, names hidden), runs the suite, maps every failed test to its requirements, looks up each requirement's severity in docs/risks.csv (first match wins), and writes reports/readiness.md: what was tested, whether the exit criteria are met, the broken requirements by severity, and GO only if nothing critical or high is broken. It exits 1 on NO-GO.
Our mystery run: 9 tests failed, mapping to 1 critical (ORD-7), 6 high and 1 medium requirement: NO-GO. Five bugs became eight broken requirements because one bug can break several rules; the report lists tests per requirement so you can find the common cause. Finally add the workflow: it starts ShopRung from a shoprung/ folder in the repository (as in lab 23), runs trace.py as a gate, then all tests, and uploads the reports.
python tools/readiness.py --bugs mysteryprints NO-GO with ORD-7 as critical, and exits 1.python tools/readiness.pyon the normal shop prints GO and exits 0.actionlintpasses on.github/workflows/quality.yml.
Hints
fnmatch.fnmatch("PRICE-3", "PRICE-*")matches patterns from the risk register.- JUnit names tests
classname+name; build the same key from the--req-maptest ids. - Commit the ShopRung folder (without node_modules) into
shoprung/so CI can start it.
Show the reference solution for milestone 8
Try it yourself first. This is one good way to do it, not the only one.
"""Release readiness: run the suite against a release candidate and write a one-page go/no-go report.
python tools/readiness.py --bugs mystery (practice: 5 hidden bugs; writes reports/readiness.md)
python tools/readiness.py (the shop as it is)
"""
import argparse
import csv
import fnmatch
import json
import subprocess
import sys
from collections import Counter
from pathlib import Path
from bug_matrix import REPORTS, call, run_suite
ORDER = ["critical", "high", "medium", "low"]
def severity_of(rid: str, risks: list[dict]) -> str:
"""The first row of the risk register whose pattern matches the requirement."""
return next((r["severity"] for r in risks if fnmatch.fnmatch(rid, r["requirements"])), "medium")
def main() -> None:
p = argparse.ArgumentParser()
p.add_argument("--bugs", default="", help="comma-separated ShopRung bugs to switch on, e.g. mystery")
args = p.parse_args()
REPORTS.mkdir(exist_ok=True)
subprocess.run([sys.executable, "-m", "pytest", "--collect-only", "-q", "--req-map", str(REPORTS / "req-map.json")],
check=True, capture_output=True)
reqs = {f"{Path(k.split('::')[0]).stem}::{k.split('::', 1)[1]}": v for k, v in json.loads((REPORTS / "req-map.json").read_text()).items()}
risks = list(csv.DictReader(open("docs/risks.csv")))
call("POST", "/api/test/bugs", {"enabled": [b for b in args.bugs.split(",") if b]})
try:
failed, secs = run_suite("readiness")
finally:
call("POST", "/api/test/bugs", {"enabled": []})
broken = {}
for test in failed:
for rid in reqs.get(test, ["(no requirement)"]):
broken.setdefault(rid, []).append(test)
sev = {rid: severity_of(rid, risks) for rid in broken}
counts = Counter(sev.values())
go = not (counts["critical"] or counts["high"])
lines = [
"# Release readiness", "",
f"**Candidate:** ShopRung {'with ' + args.bugs if args.bugs else 'as running'} ",
f"**Tested:** {len(reqs)} tests (API and UI) in {secs:.0f} s, {len(failed)} failed ",
f"**Exit criteria:** {'met' if not failed else 'NOT met'} ",
f"**Broken requirements:** " + (", ".join(f"{counts[s]} {s}" for s in ORDER if counts[s]) or "none"), "",
"| Requirement | Severity | Failing tests |", "| --- | --- | --- |",
]
for rid in sorted(broken, key=lambda r: (ORDER.index(sev[r]), r)):
lines.append(f"| {rid} | {sev[rid]} | {', '.join(f'`{t}`' for t in broken[rid])} |")
lines += ["", f"**Recommendation: {'GO' if go else 'NO-GO'}.** " + (
"No critical or high-severity requirement is broken." if go else
"Critical or high-severity requirements are broken; fix them and test a new candidate."),
"The product owner decides; this report gives the evidence."]
(REPORTS / "readiness.md").write_text("\n".join(lines) + "\n")
print("\n".join(lines))
sys.exit(0 if go else 1)
if __name__ == "__main__":
main() - Severity comes from the risk register, agreed in milestone 1.line 20
- The exit criterion, in one line.line 45
- The tester recommends; the owner decides.line 59
name: quality
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
tests:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Start ShopRung
working-directory: shoprung
run: |
npm start > shoprung.log 2>&1 &
npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Install
run: |
pip install -r requirements.txt
playwright install --with-deps chromium
- name: Every test names its requirement
run: python tools/trace.py
- name: API and UI tests
run: pytest --junitxml=reports/junit.xml
- uses: actions/upload-artifact@v4
if: always()
with:
name: test-reports
path: |
reports/
test-results/
shoprung/shoprung.log - An untagged test fails the build before the tests run.line 39
- Reports are uploaded even when tests fail: that is when you need them.line 45
python tools/readiness.py --bugs mysterypython tools/readiness.py --bugs mysterypython tools/readiness.py --bugs mystery # Release readiness **Candidate:** ShopRung with mystery **Tested:** 48 tests (API and UI) in 11 s, 9 failed **Exit criteria:** NOT met **Broken requirements:** 1 critical, 6 high, 1 medium | Requirement | Severity | Failing tests | | --- | --- | --- | | ORD-7 | critical | `test_orders::test_customer_cannot_open_another_customers_order` | | ORD-2 | high | `test_orders::test_order_reduces_the_stock` | | ORD-4 | high | `test_orders::test_shipped_order_cannot_be_cancelled` | | ORD-6 | high | `test_orders::test_cancel_puts_items_back` | | PRICE-1 | high | `test_shop::test_save10_at_exactly_50_in_the_cart[chromium]` | | PRICE-10 | high | `test_prices::test_total_is_subtotal_minus_discount_plus_shipping` | | PRICE-3 | high | `test_prices::test_save10_at_exactly_50`, `test_shop::test_save10_at_exactly_50_in_the_cart[chromium]` | | CART-2 | medium | `test_cart::test_quantity_limits[11-400]`, `test_cart::test_adding_to_a_line_cannot_pass_ten` | **Recommendation: NO-GO.** Critical or high-severity requirements are broken; fix them and test a new candidate. The product owner decides; this report gives the evidence.
Check it works
pytest passes all 48 tests on the normal shop, and python tools/trace.py exits 0.
python tools/bug_matrix.py catches every shop bug, and python tools/readiness.py --bugs mystery says NO-GO.
pytest -q
python tools/trace.py
python tools/readiness.pypytest -q
python tools/trace.py
python tools/readiness.pypytest -q
python tools/trace.py
python tools/readiness.py 48 passed in 5.29s ... total 31 of 41 requirements have a test (76%) ... **Recommendation: GO.** No critical or high-severity requirement is broken.
Review rubric
Review your project the way a senior engineer or an interviewer would. Aim for the right column on every row.
| Area | Works | Production-ready |
|---|---|---|
| Strategy | Lists what is tested and with which tools. | Scope, risks, layers, exit criteria and known gaps on one page; every decision traces to a risk. |
| Risk | A risk list. | Scored likelihood x impact, severity per area, specific rows before patterns, used by the readiness report. |
| API tests | Happy paths pass. | Exact boundaries, two users, the status flow, amounts in cents, each test independent and tagged. |
| UI tests | A few journeys with CSS selectors and waits. | Role and label locators, expect waits only, journeys that complement the API tests instead of repeating them. |
| Proof | Coverage numbers. | Traceability plus a bug matrix: every planted bug caught, and the tests that catch each one named. |
| Release | All tests green means ship. | A one-page report mapping failures to requirements and severity, with a recommendation the owner can act on. |
| CI | Tests run on push. | Runs on every pull request, gates on untagged tests, uploads reports even on failure. |
Stretch goals
- Close two known gaps: ACC-5 (password rules) and CART-5 (change and remove a line), then rerun
trace.py. - Add a
@pytest.mark.smokejob that runs on every push in under 2 seconds, and the full suite on pull requests. - Run the UI journeys in Firefox and WebKit too (
--browser firefox --browser webkit) for NF-1. - Add the support-chat suites from Part 10 and include the six chat bugs in the matrix.
- Shard the UI tests across two CI jobs and merge the JUnit reports.
Troubleshooting
ShopRung is not running at http://localhost:8080.
Start it with npm start in the ShopRung folder, or set BASE_URL to where it runs.
error: unrecognized arguments: --req-map.
The option must be in the project-root conftest.py, not in tests/conftest.py: pytest reads the root one before it parses options.
Everything fails after you stopped bug_matrix.py halfway.
A bug is still on. POST {"enabled":[]} to /api/test/bugs.
Executable doesn't exist at .../chromium-....
Run playwright install chromium with the virtual environment active.
The bug matrix stops with "The suite must be green on the normal shop first".
Fix the failing tests it names first; a matrix on a red suite proves nothing.
What changes in production
- Teams keep the strategy and risk register next to the code, and review them each release.
- Requirement or ticket ids in test names (or markers) make traceability and impact analysis a script, not a spreadsheet.
- Mutation testing or planted faults are how mature teams check that a suite catches bugs, not just that it runs code.
- Release reports like this are generated by CI and attached to the release, with the owner's decision recorded.
Interview angle
“Walk me through how you would test an online shop from scratch.”
Risks first: I scored each area likelihood x impact, so prices and order privacy got the deepest tests. A one-page strategy set the layers: 43 API tests for the rules at exact boundaries, 5 UI journeys, all tagged with requirement ids. A trace script shows 31 of 41 requirements covered, and the gaps are written down. To prove the suite works, I switched on each of 11 planted bugs: all 11 were caught. For releases, a script maps failures to requirements and severity: a candidate with 5 hidden bugs got a NO-GO with a critical data leak. It all runs in CI on every pull request.
The full project
The full reference solution, as it is after the last milestone. Build your own first, then compare.