QA and Test Automation · Lab 11 of 35
API Test Suite With pytest and httpx: ShopRung, Step by Step
Build a real API test suite in Python: fixtures for a client and one login per user, boundary tests with parametrize, orders and permissions, a JSON schema check and smoke markers. 23 tests that catch 7 of ShopRung's planted bugs.
⏱ 60 minIntermediate💸 Free8 steps
Python 3.12pytest 8.3httpx 0.28jsonschema 4.23ShopRung
Overview video
What you will build
A pytest project that tests ShopRung's API from the outside, the way SDET teams do it, with 23 passing tests in four files:
conftest.py: a shared client, a data reset before every test, and alogin("alice")factory that gives each user their own client.test_auth.py: good and bad logins, the same message for a wrong password and an unknown email, missing and tampered tokens.test_cart.py: quantity limits, out of stock, SAVE10 at exactly $50.00, FLAT5 at $20.00, expired and unknown coupons, free shipping at $75.00.test_orders.py: stock goes down when you order, the order state machine, only admins ship, Bob cannot see Alice's order.test_schema.py: the whole cart response checked against a JSON schema.
You finish by switching on ShopRung's mystery bugs and finding all five with one command.
Before you start
- Python basics: functions, lists, dictionaries. The ideas in this lab are explained in API tests with pytest, HTTP and REST for testers and API authentication.
- ShopRung installed, as in lab 1 setup. Keep it running in its own terminal for the whole lab.
- Helpful but not required: Your first Java test project, which tests the same money rules as plain code.
Setup
S1Start ShopRung
Start ShopRung as in lab 1: in the shoprung folder run npm start, and leave that terminal open. Check it answers:
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"} S2Check Python 3.12 or newer
On Windows use py where this lab says python3.
python3 --versionpython3 --versionpy --version Python 3.12.x (or newer)
S3Make the project folder and a virtual environment
A virtual environment keeps this project's libraries separate from everything else on your computer. Make a folder, create the environment, and activate it. Your prompt then starts with (.venv). Run the activate line again in every new terminal.
mkdir -p shoprung-api-tests/tests shoprung-api-tests/schemas
cd shoprung-api-tests
python3 -m venv .venv
source .venv/bin/activatemkdir -p shoprung-api-tests/tests shoprung-api-tests/schemas
cd shoprung-api-tests
python3 -m venv .venv
source .venv/bin/activatemkdir shoprung-api-tests\tests, shoprung-api-tests\schemas
cd shoprung-api-tests
py -m venv .venv
.venv\Scripts\Activate.ps1 Install pinned libraries
pytest, httpx and jsonschema installed at exact versions, so everyone on the team gets the same results.
Create requirements.txt in the project folder. Each line pins one library to an exact version. pytest finds and runs tests, httpx sends HTTP requests, and jsonschema checks the shape of JSON.
Then create pytest.ini. It tells pytest where the tests are, adds -ra (a short summary of anything that did not pass) to every run, and registers a smoke marker, which you will use in step 7.
pytest==8.3.4
httpx==0.28.1
jsonschema==4.23.0 - Exact versions (
==). Unpinned libraries can change under you and break a green suite overnight.line 1
[pytest]
testpaths = tests
addopts = -ra
markers =
smoke: the few fast checks to run on every commit - Only look for tests in
tests/.line 2 - Registered markers avoid typos: pytest warns about a marker it does not know.line 5
pip install -r requirements.txt
pytest --version Successfully installed ... httpx-0.28.1 ... jsonschema-4.23.0 ... pytest-8.3.4 ... pytest 8.3.4
Stuck on this step?
pipis not found, or installs into the wrong Python.- Activate the virtual environment first (setup step 3).
python -m pip install -r requirements.txtalways uses the active Python.
A client fixture and a reset before every test
Shared setup in conftest.py: one HTTP client for the run, and seed data restored before each test.
Create tests/conftest.py. pytest loads this file automatically and gives its fixtures to every test in the folder. A test asks for a fixture by naming it as a parameter.
apiis onehttpx.Clientfor the whole run (scope="session"). Itsbase_urlcomes from theBASE_URLenvironment variable, so the same suite can test another server. Thetimeoutstops a hung server from hanging your run. If ShopRung is not running,pytest.exitstops everything with a clear message instead of 23 confusing failures.resethasautouse=True, so it runs before every test without being asked for. It callsPOST /api/test/reset, which puts ShopRung back to its seed data. Tests never depend on each other.
"""Shared setup for the ShopRung API suite: one client per user, data reset before every test."""
import os
import httpx
import pytest
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
@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 reset(api):
"""Every test starts from ShopRung's seed data."""
assert api.post("/api/test/reset").status_code == 200 - Point the suite elsewhere with
BASE_URL=http://staging... pytest. No code change.line 7 - One client, reused: connections stay open, so the suite is fast.line 10
- Fail fast with one helpful line when the shop is down.line 17
- Runs before every test. Known data in, known results out.line 21
First tests: logins and missing tokens
Five passing tests for ShopRung's login rules, including two cases from one parametrized test.
Create tests/test_auth.py. Tests are plain functions whose names start with test_, and they check results with plain assert. When an assert fails, pytest prints both sides of the comparison, so you rarely need a message.
@pytest.mark.parametrize runs one test function once per row: here a wrong password and an unknown email. Both must give the same message, so attackers cannot find out which emails have accounts. That is a security rule, not just wording.
"""ACC rules: who you are (401) is tested apart from what you may do (403/404)."""
import pytest
@pytest.mark.smoke
def test_login_returns_a_token(api):
r = api.post("/api/auth/login", json={"email": "alice@shoprung.test", "password": "Alice123!"})
assert r.status_code == 200
assert r.json()["token"].count(".") == 2 # a JWT has three parts
@pytest.mark.parametrize("email, password", [
("alice@shoprung.test", "wrong"), # wrong password
("nobody@shoprung.test", "Alice123!"), # unknown email
])
def test_bad_login_gives_the_same_message(api, email, password):
r = api.post("/api/auth/login", json={"email": email, "password": password})
assert r.status_code == 401
assert r.json()["message"] == "Email or password is wrong"
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
def test_cart_needs_a_token(api):
r = api.get("/api/cart")
assert r.status_code == 401
assert r.json()["error"] == "unauthorized" - A marker. Step 7 runs only the smoke tests.line 5
- A JWT has three parts separated by dots: header, payload, signature.line 9
- Two rows, two test cases, each reported on its own line.line 12
- Emails are not case sensitive (ACC rules).line 23
pytest -v tests/test_auth.py::test_login_returns_a_token PASSED tests/test_auth.py::test_bad_login_gives_the_same_message[alice@shoprung.test-wrong] PASSED tests/test_auth.py::test_bad_login_gives_the_same_message[nobody@shoprung.test-Alice123!] PASSED tests/test_auth.py::test_email_is_not_case_sensitive PASSED tests/test_auth.py::test_cart_needs_a_token PASSED 5 passed in 0.40s
Stuck on this step?
ShopRung is not running at http://localhost:8080- Start it in another terminal with
npm start, or setBASE_URLif it runs on another port. no tests ran- Run
pytestfrom the project folder (wherepytest.iniis), and check the file name starts withtest_.
A login factory: one client per user
login("alice") returns a client that sends Alice's token; alice, bob and admin are ready-made fixtures.
Most endpoints need a logged-in user, and authorisation tests need two users. Replace tests/conftest.py with the version below.
login is a factory fixture: instead of a value, it returns a function. login("bob") logs Bob in through the API and returns a new httpx.Client that sends his token on every request. Each user gets their own client, so a test can use Alice and Bob side by side without their tokens mixing. After the test, the code after yield closes every client it opened.
Then add the tampered-token test to tests/test_auth.py: it changes the last character of Alice's real token. The signature no longer matches, so ShopRung must answer 401 invalid_token.
"""Shared setup for the ShopRung API suite: one client per user, data reset before every test."""
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 reset(api):
"""Every test starts from ShopRung's seed data."""
assert api.post("/api/test/reset").status_code == 200
@pytest.fixture
def login(api):
"""A factory: 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") - ShopRung's practice accounts. Real suites read these from CI secrets.line 8
- The function the fixture hands to the test.line 37
- Every request from this client carries the bearer token.line 42
- Teardown: runs after the test, pass or fail.line 47
"""ACC rules: who you are (401) is tested apart from what you may do (403/404)."""
import pytest
@pytest.mark.smoke
def test_login_returns_a_token(api):
r = api.post("/api/auth/login", json={"email": "alice@shoprung.test", "password": "Alice123!"})
assert r.status_code == 200
assert r.json()["token"].count(".") == 2 # a JWT has three parts
@pytest.mark.parametrize("email, password", [
("alice@shoprung.test", "wrong"), # wrong password
("nobody@shoprung.test", "Alice123!"), # unknown email
])
def test_bad_login_gives_the_same_message(api, email, password):
r = api.post("/api/auth/login", json={"email": email, "password": password})
assert r.status_code == 401
assert r.json()["message"] == "Email or password is wrong"
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
def test_cart_needs_a_token(api):
r = api.get("/api/cart")
assert r.status_code == 401
assert r.json()["error"] == "unauthorized"
def test_a_tampered_token_is_refused(api, alice):
token = alice.headers["Authorization"].removeprefix("Bearer ")
tampered = token[:-1] + ("A" if token[-1] != "A" else "B")
r = api.get("/api/cart", headers={"Authorization": f"Bearer {tampered}"})
assert r.status_code == 401
assert r.json()["error"] == "invalid_token" - Change one character. A real token with a broken signature must be refused.line 35
pytest -q ...... 6 passed in 0.45s
Cart and price rules on their boundaries
Ten tests that check CART and PRICE rules exactly on their edges.
Create tests/test_cart.py. Boundaries are where bugs live, so each test sits on an edge from ShopRung's requirements:
- Quantity 0 and 11 are refused (
400); 1 and 10 are accepted. - The Red Build Mug has no stock:
409with Red Build Mug is out of stock. - Four notebooks are exactly $50.00, the lowest subtotal SAVE10 accepts: discount 500 cents, shipping 499, total $49.99. The code is typed in lower case on purpose: coupon codes are not case sensitive.
- One T-shirt is exactly $20.00, the edge for FLAT5: total $19.99.
- WELCOME15 expired (
400), NOPE does not exist (404). - One keyboard is exactly $75.00, where shipping becomes free.
Comparing a tuple of four numbers checks them together, and a failure shows all four, which is easier to read than four separate asserts.
"""CART and PRICE rules, checked on their boundaries. Products: 1 = notebook $12.50, 6 = T-shirt $20.00, 8 = keyboard $75.00."""
import pytest
def add(client, product_id, quantity):
return client.post("/api/cart/items", json={"productId": product_id, "quantity": quantity})
@pytest.mark.parametrize("quantity, status", [(0, 400), (1, 200), (10, 200), (11, 400)])
def test_quantity_must_be_1_to_10(alice, quantity, status):
r = add(alice, 1, quantity)
assert r.status_code == status, r.text
def test_out_of_stock_product_cannot_be_added(alice):
r = add(alice, 5, 1) # Red Build Mug, stock 0
assert r.status_code == 409
assert r.json()["message"] == "Red Build Mug is out of stock"
@pytest.mark.smoke
def test_save10_applies_at_exactly_50_dollars(alice):
add(alice, 1, 4) # 4 x $12.50 = $50.00
r = alice.post("/api/cart/coupon", json={"code": "save10"})
assert r.status_code == 200
cart = r.json()
assert (cart["subtotalCents"], cart["discountCents"], cart["shippingCents"], cart["totalCents"]) == (5000, 500, 499, 4999)
assert cart["total"] == "$49.99"
def test_flat5_at_exactly_20_dollars(alice):
add(alice, 6, 1) # $20.00
cart = alice.post("/api/cart/coupon", json={"code": "FLAT5"}).json()
assert (cart["discountCents"], cart["totalCents"]) == (500, 1999)
@pytest.mark.parametrize("code, status, message", [
("WELCOME15", 400, "This coupon has expired"),
("NOPE", 404, "No coupon called NOPE"),
])
def test_coupons_that_do_not_apply(alice, code, status, message):
add(alice, 6, 1)
r = alice.post("/api/cart/coupon", json={"code": code})
assert r.status_code == status
assert r.json()["message"] == message
def test_shipping_is_free_from_75_dollars(alice):
cart = add(alice, 8, 1).json() # exactly $75.00
assert (cart["shippingCents"], cart["totalCents"]) == (0, 7500) - A small helper keeps each test to the point.line 5
- Both sides of both edges: 0 | 1 and 10 | 11.line 9
- Lower case on purpose: codes are not case sensitive.line 24
- Subtotal, discount, shipping, total, in cents. Never floats for money.line 27
pytest -q tests/test_cart.py .......... 10 passed in 0.70s
Orders, stock and who may do what
Five tests for the order rules, including a side effect and two authorisation checks.
Create tests/test_orders.py. These tests go past the response:
- Side effects. Placing an order for 2 copies of The Bug Hunter's Diary must reduce its stock by 2 and empty the cart. The order response alone cannot tell you that, so the test reads the product and the cart again.
- State machine. Alice's seed order 2 is SHIPPED, so cancelling it must fail with
409and Cannot cancel an order that is SHIPPED. - Roles. Alice pays for her new order, but shipping it as a customer is
403; the admin can. - Ownership. Bob asks for Alice's order 1:
404, No order with id 1. ShopRung answers 404, not 403, so it does not even admit the order exists.
"""ORD rules: placing, stock, the state machine and who may see an order."""
def place(client, product_id, quantity):
client.post("/api/cart/items", json={"productId": product_id, "quantity": quantity})
return client.post("/api/orders")
def test_placing_an_order_reduces_stock_and_empties_the_cart(api, alice):
before = api.get("/api/products/3").json()["stock"] # The Bug Hunter's Diary
r = place(alice, 3, 2)
assert r.status_code == 201
order = r.json()
assert order["status"] == "PLACED"
assert api.get("/api/products/3").json()["stock"] == before - 2
assert alice.get("/api/cart").json()["itemCount"] == 0
def test_an_empty_cart_cannot_be_ordered(alice):
r = alice.post("/api/orders")
assert r.status_code == 400
assert r.json()["error"] == "empty_cart"
def test_a_shipped_order_cannot_be_cancelled(alice):
r = alice.post("/api/orders/2/cancel") # Alice's seed order 2 is SHIPPED
assert r.status_code == 409
assert r.json()["message"] == "Cannot cancel an order that is SHIPPED"
def test_only_an_admin_can_ship(alice, admin):
order_id = place(alice, 1, 1).json()["id"]
assert alice.post(f"/api/orders/{order_id}/pay").status_code == 200
assert alice.post(f"/api/orders/{order_id}/ship").status_code == 403
r = admin.post(f"/api/orders/{order_id}/ship")
assert r.status_code == 200
assert r.json()["status"] == "SHIPPED"
def test_bob_cannot_see_alices_order(bob):
r = bob.get("/api/orders/1")
assert r.status_code == 404
assert r.json()["message"] == "No order with id 1" - Read the stock first, so the test does not depend on the seed number.line 10
- The side effect: the response said 201, but did the stock really change?line 15
- Two fixtures, two users, two clients.line 31
- Broken object-level authorisation is the top API security risk. Always test with a second user.line 41
pytest -q tests/test_orders.py ..... 5 passed in 0.60s
Check the whole response shape with a schema
A JSON schema for the cart, checked on a full and an empty cart.
Value checks look at a few fields. A JSON schema checks every field at once: required fields, types, ranges and patterns. Save the schema as schemas/cart.schema.json, then create tests/test_schema.py.
If a developer turned totalCents into a string, the value tests might still pass, but this one fails and names the field. See JSON schema validation for the details.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["items", "itemCount", "subtotalCents", "discountCents", "shippingCents", "totalCents", "total"],
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"required": ["productId", "sku", "quantity", "lineCents"],
"properties": {
"productId": {"type": "integer", "minimum": 1},
"sku": {"type": "string", "pattern": "^[A-Z]{2}-[0-9]{3}$"},
"quantity": {"type": "integer", "minimum": 1, "maximum": 10},
"lineCents": {"type": "integer", "minimum": 0}
}
}
},
"itemCount": {"type": "integer", "minimum": 0},
"subtotalCents": {"type": "integer", "minimum": 0},
"discountCents": {"type": "integer", "minimum": 0},
"shippingCents": {"type": "integer", "enum": [0, 499]},
"totalCents": {"type": "integer", "minimum": 0},
"total": {"type": "string", "pattern": "^\\$[0-9]+\\.[0-9]{2}$"}
}
} - Without a required list, an empty object would pass.line 4
- Every SKU looks like BK-101.line 13
- Shipping is free or $4.99. Nothing else.line 22
"""The shape of the cart response, all fields at once (on top of the value checks)."""
import json
from pathlib import Path
from jsonschema import validate
SCHEMA = json.loads((Path(__file__).parent.parent / "schemas" / "cart.schema.json").read_text())
def test_cart_matches_its_schema(alice):
alice.post("/api/cart/items", json={"productId": 1, "quantity": 4})
validate(instance=alice.get("/api/cart").json(), schema=SCHEMA)
def test_empty_cart_matches_its_schema(alice):
validate(instance=alice.get("/api/cart").json(), schema=SCHEMA) - Raises a ValidationError with the failing field if the shape is wrong.line 12
pytest -q ....................... 23 passed in 2.34s
Smoke tests and a report for CI
Run a two-test smoke set, and write a JUnit XML report a CI server can read.
Two tests carry @pytest.mark.smoke: a login and SAVE10. -m smoke runs only those, which is what you would run on every commit when the full suite is slow.
--junitxml writes the results as JUnit XML, the format every CI server (GitHub Actions, Jenkins, GitLab) can display as a test report. Part 8 uses it in a pipeline.
pytest -q -m smoke
pytest -q --junitxml=results.xml .. 2 passed, 21 deselected in 0.24s ....................... 23 passed in 1.98s
Check it works
Your suite is only useful if it fails when the shop is broken. Switch on one ShopRung bug, run the suite, and read the failure:
Then try the others one at a time (quantity-limit, free-shipping-boundary, cancel-shipped, stock-not-reduced, expired-coupon, order-leak): each makes exactly one test fail. Finally, switch on mystery mode, which turns on five bugs without telling you which. Your suite finds all five: the quantity limit, the SAVE10 edge, the stock, the shipped cancel and the order leak. Turn the bugs off at the end.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
pytest -q E assert 400 == 200 FAILED tests/test_cart.py::test_save10_applies_at_exactly_50_dollars - assert... 1 failed, 22 passed in 1.82s
Troubleshooting
Every test fails with ConnectError or the "not running" message.
ShopRung stopped or runs on another port. Start it with npm start, or run BASE_URL=http://localhost:PORT pytest.
Tests pass alone but fail together.
Something escaped the reset: check that reset still has autouse=True, and that no test changes the shared api client's headers. Use login() clients for anything logged in.
fixture 'alice' not found
conftest.py must be inside tests/ (or above it), and the fixture name must match the parameter exactly.
A test still passes with its bug switched on.
Run curl http://localhost:8080/api/test/bugs to check the bug is really on, and check the test asserts the exact value, not just the status code.
Windows: curl -d with single quotes fails.
Use curl.exe and escape the quotes: -d "{\"enabled\":[]}", or switch the bug from the yellow bar link in the shop.
What changes in production
- Credentials come from CI secret variables (
os.environ), never from the code. ShopRung's passwords are public only because it is a practice shop. - A global reset does not work on shared environments or in parallel. Real suites create their own data per test, usually a new user through the API, and clean up only what they made.
- Teams run smoke tests on every pull request and the full suite on merge or nightly, with the JUnit report shown in CI and failures posted to the team chat.
- Contract tests and schema checks catch shape changes early; value tests like these catch logic bugs. Mature suites have both.
Interview angle
“How would you structure an API test framework in Python?”
pytest with httpx or requests. A conftest.py holds a session client with the base URL from the environment and a timeout, a data fixture (a reset, or per-test data for parallel runs) and a login factory that gives each user their own client. Tests are grouped by feature, use parametrize for boundaries, assert exact values and side effects, and include two-user authorisation checks. Schemas check response shape, markers pick smoke tests, and --junitxml feeds CI. I prove the suite works by planting bugs and seeing the right test fail.
Clean up
Practice
These run in your browser and check your answer.
Round the SAVE10 discount correctly
ShopRung rounds a percentage discount to the nearest cent, with half a cent going up (PRICE-6). Write discount_cents(subtotal_cents, percent) that returns the discount in whole cents. Hint: a subtotal of 7499 cents at 10% is 749.9 cents, which must become 750. Use only integers.
def discount_cents(subtotal_cents, percent):
# wrong: this rounds down
return subtotal_cents * percent // 100
Hint
Add 50 before dividing by 100: (subtotal * percent + 50) // 100.
The full project
Every file from this lab, as it is after the last step.