Notes
Setup
Install pytest and httpx. Httpx has a client with a base address and works much like the popular requests library, which is also fine; the ideas in this episode are the same. The layout is simple: a conftest file for shared fixtures, test files named test underscore something, a pytest ini file for settings and markers, and a requirements file with pinned versions, so CI installs exactly what you used.
pip install pytest httpx shoprung-api-tests/ conftest.py # fixtures test_cart.py test_orders.py pytest.ini # markers requirements.txt requests works too: same ideas
Client fixture
A fixture is a function that prepares something for a test. The client fixture creates one httpx client for the whole session, with the base URL read from an environment variable, and localhost as the default, plus a ten second timeout so a hung server cannot hang CI. Yield hands the client to the tests, and the with block closes it at the end. Run against staging by setting base URL, no code changes.
import os, httpx, pytest
BASE = os.getenv("BASE_URL",
"http://localhost:8080")
@pytest.fixture(scope="session")
def client():
with httpx.Client(base_url=BASE,
timeout=10) as c:
yield c Data fixtures
Two more fixtures. Reset has auto use set to true, so it runs before every test and puts ShopRung's data back to the start, which keeps tests independent. The alice fixture logs in through the API and adds the bearer token to the client's headers. A test that needs a logged in customer just asks for alice as a parameter. After the test, the fixture removes the header again, so the next test starts logged out.
@pytest.fixture(autouse=True)
def reset(client):
client.post("/api/test/reset")
@pytest.fixture
def alice(client):
r = client.post("/api/auth/login",
json={"email": ALICE, ...})
assert r.status_code == 200
client.headers["Authorization"] =
f"Bearer {r.json()['token']}" A test
Here is the save ten test again, now in Python. The test asks for alice, adds four notebooks, exactly fifty dollars, applies save ten, and checks with plain assert statements: status two hundred, discount five hundred cents, total forty nine ninety nine. Pytest rewrites asserts, so when one fails it prints both sides of the comparison. No matcher library to learn.
def test_save10_at_exactly_50(alice):
alice.post("/api/cart/items",
json={"productId": 1,
"quantity": 4})
r = alice.post("/api/cart/coupon",
json={"code": "save10"})
assert r.status_code == 200
cart = r.json()
assert cart["discountCents"] == 500
assert cart["total"] == "$49.99" Parametrize
Parametrize turns one function into many tests. The quantity rule gets four cases: zero gives four hundred, one and ten give two hundred, eleven gives four hundred. Pytest reports each case separately, with the values in its name, like test quantity limits eleven dash four hundred. The message after the comma prints the response body when the assert fails, which saves a debugging round trip.
@pytest.mark.parametrize(
"qty, status",
[(0, 400), (1, 200),
(10, 200), (11, 400)])
def test_quantity_limits(alice,
qty, status):
r = alice.post("/api/cart/items",
json={"productId": 1,
"quantity": qty})
assert r.status_code == status,
r.text A real run
We ran this suite against ShopRung. Six tests, all passed, in under a second. Then we switched on the quantity limit bug, which lets you add eleven of an item. Exactly one test failed: quantity limits, eleven, four hundred, with assert two hundred equals four hundred, and the response body. The name alone tells you which rule broke and with which value. That is what a good failure looks like.
BASE_URL=http://localhost:8080 pytest -q ...... [100%] 6 passed in 0.80s bug "quantity-limit" on: FAILED test_quantity_limits [11-400] assert 200 == 400 1 failed, 5 passed
Organising
As the suite grows, organise it. Markers tag tests, like smoke, and dash m smoke runs only those. Dash k selects by name, dash x stops at the first failure, and last failed reruns only what failed. The x dist plugin runs tests in parallel with dash n auto, but only if tests do not share data, so a global reset must become per user data first. Junit XML writes a report CI tools understand.
@pytest.mark.smoke pytest -m smoke pytest -k coupon pytest -x # stop at 1st pytest --lf # last failed pytest -n auto # pytest-xdist pytest --junitxml=results.xml pytest.ini: markers = smoke: fast checks
Models
Python dictionaries are quick, but a typo in a key only fails at run time. For bigger suites, a pydantic model gives typed responses: a cart model with integer fields for subtotal, discount and total. Model validate checks the JSON matches, with a clear error if a field is missing or has the wrong type, and the editor completes field names. It is the Python cousin of the Java records from the last episode.
from pydantic import BaseModel
class Cart(BaseModel):
subtotalCents: int
discountCents: int
totalCents: int
cart = Cart.model_validate(r.json())
assert cart.totalCents == 4999
# wrong type → clear error Common mistakes
Habits to avoid. HTTP calls without a timeout, which can hang a pipeline forever. The base URL repeated in every test. Tests that only pass in a certain order. Login code at module level instead of in a fixture. Checking only that the response is okay. Try and except blocks that swallow assertion errors. Unpinned requirements. And parallel runs on shared data, which creates flaky failures.
- requests.get without timeout
- base URL in every test
- tests that depend on order
- module-level login code
- a bare assert r.ok only
- try/except that hides fails
- unpinned requirements
- parallel runs on shared data
Say it like this
In the interview: I use pytest with httpx or requests. Conftest holds a session client with the base URL from the environment and a timeout, a data fixture that resets or creates test data, and login fixtures per role. Parametrize covers boundaries, plain asserts include the response body as the message, markers select smoke tests, x dist runs in parallel when data is isolated, and junit XML feeds CI.
- "pytest with httpx or requests.
- conftest holds a session client
- (base URL from env, timeouts), a reset or data fixture, and login fixtures per role.
- parametrize covers boundaries;
- plain asserts with the body as message. Markers for smoke, xdist for speed, JUnit XML
- for CI."