Building the core: client, test data, validators

Study time
≈ 12 h (estimate)
Needs
L1-M08-L01
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M08 (capstone), milestone 2 · Duration: ~12 hours (estimate) · Previous: Milestone 1 - Capstone brief, requirements and architecture · Next: Milestone 3 - Test suites: functional, negative, schema, injection, tool calls, conversation regression, one Playwright UI flow

1. Introduction

Milestone 2 builds the part that every later test depends on: how the product is started, how the API is called, where the test data lives, and the oracles. If this part is wrong, every test in milestone 3 is wrong with it. That is why the framework core has its own unit tests, and the oracles are checked with good samples, bad samples and (if possible) a mutation check.

This milestone is also where you move at least 3 tests from the earlier labs into the framework (F6). This checks whether your framework can really be reused.

2. Objectives

  1. Write a fixture that starts the product by build, and a client for its API.
  2. Organise the test data as files, every case with a source.
  3. Build the oracle library (properties, schema, consequences) and verify it.
  4. Move at least 3 tests from the labs of M03-M06 and record what had to change.
  5. Keep the framework offline by default with no secrets in the code.

3. What you need

  • The design document of milestone 1, reviewed.
  • starter/README.md: a repository that already has aiqa and target-app.

4. The parts of the core

4.1 Starting the product, and the client

A fixture creates a server on a random port and stops it after the test (L1-M07-L01). A client wraps HTTP, so tests talk to the API in one place. This is the client part of the course's reference test suite (run against both builds, 2026-10-31):

class Api:
    def __init__(self, base):
        self.base = base

    def call(self, method, path, body=None, headers=None):
        data = None if body is None else json.dumps(body).encode("utf-8")
        req = urllib.request.Request(self.base + path, data=data, method=method,
                                     headers={"content-type": "application/json", **(headers or {})})
        try:
            with urllib.request.urlopen(req, timeout=5) as r:
                return r.status, json.loads(r.read())
        except urllib.error.HTTPError as e:
            return e.code, json.loads(e.read() or b"{}")

Your client may differ (for example with chat() and classify() methods added), but it should have three properties: a timeout; it returns both the status and the body, because many clauses check the status (P1); and it does not swallow HTTP errors.

The build comes from the configuration (F2), for example TARGET_BUILD=stable|rc. Validate the value at startup (L1-M07-L02).

Everyday example. A company sends all its post through one mail room. The mail room has a cut-off time (after it, nobody waits any longer), and it keeps both the receipts and the returned letters with the reason they came back. If every department went to the post office on its own, returned letters would sit in someone's drawer and nobody would know. The client is that mail room: one timeout, and both the status and the body for every response.

4.2 Test data with a source

Put the cases in JSON/JSONL, like the golden dataset of L1-M06-L03. An example row (illustration):

{"id": "C-P3-01", "clause": "P3", "source": "requirements P3", "messages": ["đơn se1003"],
 "expect": {"intent": "order_status", "reply_equals": "Đơn SE1003: đã giao.", "tool": "lookup_order"}}

The message is a Vietnamese order lookup in lowercase and the expected reply is the "delivered" status reply, both kept as the product expects them. The clause and source fields let the traceability table of milestone 1 be generated from the data, not written by hand.

Everyday example. A canteen's recipe book says where each dish comes from ("from the head chef's book, page 12"). When a guest asks why a dish tastes the way it does, the kitchen opens that page. A test data row without a source is a recipe passed on by word of mouth: nobody can check it again.

Good vs bad. The same P3 case, written two ways:

Weak row Good row
{"id": "1", "msg": "đơn se1003", "expected": "Đơn SE1003: đã giao."} Row C-P3-01 above: it has clause, source, and an expect split into intent, reply_equals, tool
Nobody knows where the expectation comes from; when the test turns red you have to guess what it checks When the test turns red, open P3 and you know whether the expectation is right; the traceability table can be generated from clause

4.3 Oracles

You already have the building blocks from the earlier modules. Gather them in the framework, each kind with unit tests:

Oracle From module Used for
exact, contains/does not contain, facts, language L1-M04-L01 P3, P5, P6
no canary leaked, only allowed links L1-M04-L04 P7, P8
JSON Schema (jsonschema, Draft 2020-12) L1-M05-L01 P11
tool call: name, parameters, outcome L1-M05-L04 P3, P4
pass rate, Wilson, Fisher L1-M06-L02, L04 P5

Every oracle needs a good sample (must PASS) and a bad sample (must FAIL) (L1-M04-L01). For the most important oracle, also run a mutation check in the style of L1-M07-L05, or run the oracle on a known wrong output.

Worked example: one case, one good sample, one bad sample. The code below reads row C-P3-01 of §4.2, sends it to stable, checks the reply with a small oracle, then checks a known wrong output. Save it as vd_l02.py in the capstone folder (it uses exercises/shop_http.py, whose call() is the same as the client in §4.1) and run python vd_l02.py:

import json
import sys

sys.path[:0] = ["target-app", "exercises"]
from shopeasy_target.server import TargetServer  # noqa: E402
from shop_http import call  # noqa: E402

case = json.loads('{"id": "C-P3-01", "clause": "P3", "source": "requirements P3", "messages": ["đơn se1003"],'
                  ' "expect": {"intent": "order_status", "reply_equals": "Đơn SE1003: đã giao.", "tool": "lookup_order"}}')


def check(case, out):
    exp, problems = case["expect"], []
    if out["intent"] != exp["intent"]:
        problems.append(f"intent {out['intent']!r}")
    if out["reply"] != exp["reply_equals"]:
        problems.append(f"reply {out['reply']!r}")
    if [c["name"] for c in out["tool_calls"]] != [exp["tool"]]:
        problems.append(f"tools {[c['name'] for c in out['tool_calls']]}")
    return "PASS" if not problems else "FAIL: " + "; ".join(problems)


server = TargetServer("stable").start()
try:
    status, out = call(server.base_url, "POST", "/api/chat", {"messages": [{"role": "user", "content": case["messages"][0]}]})
    print(case["id"], status, check(case, out))
    bad = {**out, "reply": "Đơn SE1003: đang giao.", "tool_calls": []}      # a known-wrong output
    print(case["id"], "bad sample:", check(case, bad))
finally:
    server.stop()

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions print the same):

C-P3-01 200 PASS
C-P3-01 bad sample: FAIL: reply 'Đơn SE1003: đang giao.'; tools []
  1. First line: a real request to stable, status 200, the oracle returns PASS. This line alone does not prove that the oracle is useful.
  2. Second line: the same oracle on a known wrong output (wrong status "đang giao", meaning "being delivered", and no tool call). The oracle returns FAIL and names both problems. This is the bad sample: the proof that the oracle can turn red.
  3. The expectation "Đơn SE1003: đã giao." comes from P3 and the order data, not from the output just received: the source field records that.
  4. In the framework, check() becomes a function of the oracle library, and the two lines become two unit tests.

4.4 Moving tests from the labs (F6)

Choose at least 3 tests from M03-M06 and make them run against ShopEasy Assistant. Suitable examples:

  • A data-driven injection case from L1-M04-L04, with an oracle based on consequences.
  • The ticket schema check of L1-M05-L02, now on POST /api/classify.
  • The repeat-run with the Wilson interval of L1-M06-L02, now on the FAQ answer.

Record what had to change (for example: the fake API of M03 is no longer needed, because the product has a real HTTP interface; a different canary). That list shows which parts of the framework are really reusable.

Everyday example. When you move house, you take the fridge with you but have to change the plug to fit the new sockets. The list of "plugs to change" tells you which things really move with you and which are fixed to the old house.

Worked example: recording what had to change. For the canary test of L1-M04-L04, the list could look like this:

Part In the L1-M04 lab In the capstone Change or keep
How the product is called make_assistant("v1").reply(text), in the same process api.chat(text) through the client and HTTP Change
Reply field answer reply (P1) Change
Canary CANARY-5E1F-2B7C CANARY-SE-7Q4X (P7) Change, read from the configuration
Oracle "does not contain the canary" a lab function the same logic, in the oracle library Keep

The three "Change" rows all sit where the framework talks to the product; the oracle is kept as it is. That is a good sign: the reusable part is the checking, and the product-specific part stays inside the client and the configuration.

5. Hands-on: a build chosen by configuration

python explore.py stable --health

Output (copied from a real run, 2026-10-31):

{"status": "ok", "build": "stable"}

The build field tells you which build is running. Your framework should assert it at the start of every run, with both stable and rc: the tests are running against the right build. A test suite that is green on the wrong build is one of the most expensive mistakes in QA.

Good vs bad.

Weak Good
Set TARGET_BUILD=rc, run the suite, see green, report "rc is fine" At the start of every run, compare the build of /api/health with TARGET_BUILD; if they differ, stop at once with a message that names both values
Nobody knows which build the server really is The report records the build that was confirmed, not only the build that was requested

6. The QA view

  • What can go wrong: a server shared between tests (logs mixed together); a client with no timeout; data with no source; an oracle that has never been seen failing; tests running against the wrong build; a real API key in a sample configuration file.
  • Measure: the unit tests of the core run in a few seconds, offline.

7. Deliverable of milestone 2

  1. The product fixture by build, the client, the configuration (validated at startup).
  2. Test data as files for at least P2, P3, P4, P9, P10.
  3. An oracle library with unit tests (good and bad samples), and at least one mutation check or a run with a known wrong output.
  4. At least 3 tests moved from the labs, running, with a list of what had to change.
  5. python -m pytest green, offline.

Criteria: another person can clone the repository and run it by following the README; no test calls HTTP outside the client.

7.1 Extra exercise: a small client and a build check (20-30 minutes)

Problem: §4.1 names three properties of the client and §5 advises checking the build at the start of every run. In this exercise you write both against stable, with tests that check what the client sends, not only what it receives.

Task: in the capstone folder, open exercises/test_m2_extra_client.py. The fixture server (in exercises/conftest.py) starts stable on a random port; server.api_calls is the list of bodies the server received.

  1. TODO 1: write ShopClient.chat(*texts, approve=False, seed=None, run=0): roles alternate user, assistant, user...; send approve; add X-Test-Seed and X-Test-Run only when there is a seed; on a status other than 200, fail with the status and the body.
  2. TODO 2: write check_build(client, expected): read /api/health, and if the build differs from expected, fail with a message that names both.

Run: python -m pytest exercises/test_m2_extra_client.py. Before you start, the tests fail with TODO 1 or TODO 2.

Acceptance criteria: 7 tests pass; you can point to the test that catches a client that forgets to send X-Test-Run.

Hint: call() in exercises/shop_http.py already returns (status, body) for every status. Headers are strings, not numbers.

7.2 Real-world scenario: reviewing a colleague's framework

Context (fictional): The bank MiniBank has a Q&A chatbot about cards. A colleague sends the first pull request of the test framework, with the configuration and fixture below, and 40 tests that call requests.post(...) directly.

BASE_URL = "http://10.0.0.12:9000"            # staging server
API_KEY = "mb-live-7f3a9c"                     # TODO remove later


@pytest.fixture(scope="session")
def bot():
    return requests.Session()


def ask(bot, text):
    r = bot.post(BASE_URL + "/chat", json={"q": text}, headers={"key": API_KEY})
    return r.json()["answer"]

Your task: write review comments (each comment: the problem, the risk, the fix), rank them by severity, and choose one comment that must be fixed before merging, with a reason.

A good answer has:

  • Every comment points to a specific line or behaviour and says what will go wrong when it runs, not just "the code is not nice".
  • The comments cover the configuration, the client, how responses are handled and whether tests are independent (§4.1, §6).
  • The fixes are concrete enough for the colleague to apply at once, and reuse what this lesson taught (client, configuration, startup checks).
  • The ranking is explained by consequences, and the comment that blocks the merge has a clear reason.

8. Self-check questions

0/16 done · Results are kept in this browser only.

P01 · Short answer

Why should the client return both the status and the body?

P02 · Short answer

Why should every case have the fields clause and source?

P03 · Short answer

Name one way to prove that your schema oracle catches an extra field.

P04 · Short answer

When you move the tests of L1-M03, which part is no longer needed, and why?

P05 · Short answer

How does the framework know it is testing the right build?

P07 · True or false

To record the source of a case, you can add a comment // source: P3 to the JSON data file.

P08 · Fill in the blank

According to §4.3, every oracle needs a good sample (must ___) and a bad sample (must ___).

P10 · Recall

Lesson: L1-M07-L02

L1-M07-L02 §4.1: when does load_settings() check a wrong configuration value, and how does it report it?

P12 · Multiple choice

In the worked example of §4.3, what does the line C-P3-01 bad sample: FAIL: ... prove?

P13 · True or false

In the "what had to change" table of §4.4, the oracle "does not contain the canary" is kept as it is when the canary test moves from the L1-M04 lab to the capstone.

P14 · Match

According to the table in §4.4, match each part of the canary test with its form in the capstone.

P15 · Select all that apply

According to §4.1, which properties should the client for the product's API have?

P16 · Apply now

Do the extra exercise of §7.1 in the capstone folder: exercises/test_m2_extra_client.py.

Checklist

9. Summary

  • Core = starting the product + client + configuration + data with sources + verified oracles.
  • Moving tests from the labs is the real test of reusability.
  • A test suite that runs against the wrong build, or uses an oracle that has never failed, gives a false sense of safety.

10. References

See references.md of this module.