BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
Backend Engineering

Intermediate · Lesson 6 of 12

Software Architecture

Test an API at Its Boundaries

Two notebooks cost AED 27, yet the receipt is blank and the order says AED 24. Trace the fault with pricing, PostgreSQL and HTTP tests.

A shopkeeper packs a blue notebook beside price tags and a printed receipt.

A stationery shop changes the price of its blue notebook from AED 12.00 to AED 13.50. The first customer to order two sees “Order created” on her phone, but the receipt screen shows no total. At the counter, the clerk finds an order worth AED 24.00. The test suite is green. Its only checkout test sends a request and checks that the server returned 201. Which parts of this incident could that test actually have caught?

We will follow the same two notebooks through a pricing function, a PostgreSQL transaction and an HTTP response. Each test will answer a question that matters to somebody in the shop. The customer needs the agreed price, the clerk needs a complete order, and the app needs a receipt it can display. Keeping those questions separate makes a red test much easier to interpret.

Give the order three observable promises

For this exercise the shop charges the catalog price at checkout. A basket stores a product code and quantity. Adding something to a basket does not reserve its price. Once an order is accepted, its lines keep the charged unit price even if the shop changes the catalog tomorrow. We use integer fils throughout. There are 100 fils in a dirham. The example has one currency and no tax, delivery fee or discount.

Boundary Input or event Evidence of success
Pricing Basket shows 1200 fils, current price is 1350, quantity is 2 Charged unit price is 1350 and line total is 2700
Database The order header is inserted and the line insert fails A separate reader finds neither the header nor its lines
HTTP The signed-in customer submits the two notebooks Status is 201 and the app can read an order ID, currency and integer total

A boundary is where one piece of software relies on a promise made by another. Choose the observer before choosing a tool. If the promise concerns arithmetic, a function result is enough. If it concerns what another till can see, inspect committed rows from another connection. If it concerns the app on the customer's phone, look at the response after routing and serialization have both run.

Start with a cheap test for the price change

Give the pricing function the basket line and the current catalog price explicitly. That makes the old price visible in the test without requiring a fake database. The line carries its earlier display price because the shop may show a price-change notice. We still expect the new amount to be charged. Write the expected figure as a literal calculated from our example. Computing it by calling the application's own pricing helper would allow the same mistake on both sides of the assertion.

@pytest.mark.parametrize("shown,current,qty,expected", [
    (1200, 1350, 2, 2700),
    (1350, 1200, 2, 2400),
    (1350, 1350, 1, 1350),
])
def test_checkout_price(shown, current, qty, expected):
    line = BasketLine(sku="BLUE", shown_fils=shown, quantity=qty)
    charge = quote_line(line, current_unit_fils=current)
    assert charge.unit_fils == current
    assert charge.total_fils == expected

The first row reproduces the customer's complaint. The second catches an appealing but incorrect fix that always takes the higher price. The third makes the one-unit case easy to read when a change breaks ordinary sales. Each row is a separate case in the test report. The pytest documentation describes how to supply argument sets this way. Parametrizing tests in pytest

Try a deliberate mistake in a working copy. Change the function to multiply the displayed price by the quantity. The first case should now report 2400 where it expected 2700, or fail at the preceding unit-price assertion. Restore the function after seeing that failure. This small experiment establishes that the example distinguishes the old behavior from the agreed rule. It also exposes a limit. The test hands the current price to the function. A repository that accidentally loads yesterday's price can still pass every row.

Make a real write fail halfway

The order writer inserts an order header and then its lines. A header on its own is a problem even if the caller saw an error. A clerk might prepare an empty parcel, or the daily report might count a sale that never happened. We need to exercise precisely the interval between those two writes. If input validation rejects the request before the first insert, the absence of a header tells us nothing about rollback.

Run the production writer against a disposable PostgreSQL database with the application's migrations applied. Seed the customer and the blue notebook and commit that setup. Give the attempted order its own reference, such as BOUNDARY-41. For this test call the persistence boundary directly with a prepared order whose line references a nonexistent product. The schema must have a foreign key from order lines to products. Keep the quantity, amount and header valid so the targeted constraint is the reason the operation fails.

ref = "BOUNDARY-41"
with pytest.raises(ForeignKeyViolation) as failure:
    writer.save(prepared_order(ref, product_id=missing_product_id))
assert failure.value.diag.constraint_name == "order_lines_product_fk"

with new_connection() as reader:
    assert count_headers(reader, ref) == 0
    assert count_lines_by_order_ref(reader, ref) == 0

These snippets use illustrative fixture and helper names. Check the actual constraint name in your migrations. If the writer translates a driver exception, assert the documented application error and check its recorded cause. The fresh reader matters because the writer's connection may still be in a failed transaction. A query on that same connection can fail before it tells you anything about the state a clerk would see. An explicit transaction around both inserts gives them a single commit or rollback outcome. PostgreSQL transactions

Pair the failure case with a successful write through the same entry point. Use a fresh reference and the seeded product. The reader must find one header and one line with two units at 1350, for 2700 fils in total. Change the catalog to 1500 after commit and read the saved line again. It should still carry 1350. This second read catches an order-history query that silently joins to today's catalog price. It also gives you confidence that a broken counting helper is not returning zero for absolutely everything.

Watch the test harness itself. Some suites wrap each test in an outer transaction and roll it back for cleanup. That can hide a premature commit or keep the reader from seeing setup data. For this test, give the writer control of its normal transaction, commit the starting data, then clean up the isolated database after the assertions. As a check on the test, temporarily commit just after the header insert. The failure case should now find a stranded header.

Read the receipt as the mobile app would

The public contract for this shop says that a successful POST /orders returns 201 with a JSON object containing a string id, currency equal to AED and totalFils as an integer. The request contains the product and quantity. The service supplies the price. Use an authenticated fixture for the customer and send JSON to the route through the application test client. Configure the same routing and serialization conventions used in production. Start with the catalog at 1350 and use a fresh order for this case.

r = client.post("/orders", json={"items": [{"sku": "BLUE", "qty": 2}]})
assert r.status_code == 201
assert r.mimetype == "application/json"
receipt = r.get_json()
assert isinstance(receipt["id"], str) and receipt["id"].strip()
assert receipt["currency"] == "AED"
assert type(receipt["totalFils"]) is int
assert receipt["totalFils"] == 2700

A response can look entirely reasonable in a log and still break the phone. Rename the field to total_fils in the serializer. The status assertion still passes, but reading the required key fails in the same way a consumer relying on that spelling would fail. Restore the name and return the text "2700". A human reading the log still sees the expected digits. The type assertion catches the difference before a client concatenates two strings when it meant to add amounts. Flask's client exercises the application without opening a live network socket. Testing Flask applications

Use the ID from the returned receipt to load the committed order and compare its stored total to 2700. That last comparison connects the representation the customer received to the order the clerk will handle. Avoid comparing a snapshot of the entire response when the contract permits extra fields. Adding an optional pickup estimate should leave a compatible client working. Conversely, if a mobile release requires that estimate, make its presence and units explicit in the contract and add a targeted assertion.

Read a failure before adding more tests

Suppose the unit cases pass and the HTTP test returns 2400. First inspect the order identified by the response. If its saved line already says 1200, trace which catalog record the handler loaded before calling the pricing function. If the line is correct at 1350 and the saved total is 2700, inspect the data passed to the serializer. Those two observations cut the search area considerably. Repeating the same POST a hundred times adds little information.

Give each test run its own order reference and catalog fixture. A shared product whose price is changed by another test can make this lesson look like an intermittent pricing bug. Keep the fast arithmetic cases convenient to run during edits and run the database and HTTP checks against each proposed checkout change. A green set of all three gives a reviewer concrete evidence about these three promises. It still leaves separate questions about traffic, network failures and two customers ordering at the same time.

اقرأ الدرس بالعربية

Exercise: find the first broken promise

Tomorrow's price is AED 14.25 and a customer orders three notebooks. The unit test reports 4275, the committed line records three units at 1425, and the phone receives {"currency":"AED","totalFils":"4275","id":"O-52"} with status 201. Which test should fail first for this defect? What evidence would you collect before changing the pricing code?

Answer. The receipt test fails on the type of totalFils. The arithmetic and the stored line independently support 4275 fils. Correct the serializer so the JSON contains the number 4275, then rerun the HTTP case and read the saved order by its returned ID. The exercise passes when the response has the required integer, the committed amount agrees, and the forced database failure still leaves zero headers for its own reference.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Sessions and Order Ownership

Follow two customers on a shared tablet. Scope receipt reads and pickup-branch changes to the signed-in customer, then test both the response and stored orders.

Read article ↗