AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 53

    Unit, Integration and Contract Testing

    The privacy package from Lesson 52 purges Northwind on day 31 and leaves Contoso alone.

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 53 · Full-Stack Security, Testing and Deployment

    Lesson Overview

    The privacy package from Lesson 52 purges Northwind on day 31 and leaves Contoso alone. The reminder workflow from Lesson 47 proposes mail only for learner ids the enrollment port returns. Both behaviors already have a few tests beside the code. They do not yet have a map of which test is allowed to boot a database, which test must stay pure, and which test freezes the shape of a neighbor so a fixture and a fake cannot drift apart.

    That map is the testing pyramid for this module. A unit test calls a pure function with a fixed clock. An integration test wires the in-memory store to purgeExpired and to a route that reads a session. A contract test checks a recorded enrollment document and the in-memory fake against the same assertions: id shape, tenant fence, cap of 50, and no secret field. None of these tests call a model provider. None of them read MODEL_API_KEY.

    Planning assumptions:

    • The runner is Node's built-in test module, the same runner Lesson 47 uses.
    • Integration uses an in-memory PrivacyStore. A later lesson can point the same tests at Postgres with a transaction rollback. The assertions stay.
    • The contract fixture is fixtures/enrollment/northwind-stalled.json. It is committed. It contains synthetic ids.
    • A second fixture, fixtures/model/cohort-reminder-v1.json, is checked only for schema: version, string output, no apiKey, no URL, no @. Lesson 54 scores what those strings mean.
    • The lesson player is not started. Playwright arrives in Lesson 55.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Place a check at unit, integration, or contract level and say what bug each level is there to catch.
    2. Unit-test classification, redaction, and retention with a frozen now.
    3. Keep unit tests free of sockets, env files, and shared mutable clocks.
    4. Integration-test purgeExpired so a Northwind purge writes a tombstone and a Contoso row remains.
    5. Integration-test a route that takes the tenant from the session and rejects a body tenant.
    6. Describe an enrollment contract: id pattern, tenant fence, length cap, closed error reasons.
    7. Run that contract against a committed JSON fixture and against the in-memory fake.
    8. Reject a fixture that contains apiKey, url, or an email.
    9. Pin promptVersion to cohort-reminder-v1 on the model fixture schema.
    10. Report failures with the fixture id and the assertion name.
    11. Leave probabilistic model scoring to Lesson 54 and browser flows to Lesson 55.
    12. Share one assertLookupContract so the fake and the file cannot diverge quietly.
    13. Time-box integration setup so a purge test does not become an end-to-end boot.
    14. State what a contract test does not prove: production uptime, model quality, or CSS.
    15. Hand a green unit-and-contract job to the CI design in Lesson 56.

    Prerequisites

    What is Unit, Integration and Contract Testing?

    A unit test loads one module and calls it. The privacy clock, the redactor, and the template parser are units. They return data. They do not choose a database.

    An integration test crosses a boundary you own: a route plus a store, or a purge job plus the table it rewrites. The neighbors are still fakes. The point is to catch wiring mistakes, such as a route that prefers body.tenantId over the session.

    A contract test freezes the shape two sides share. The consumer is the reminder workflow. The provider is the enrollment adapter. The contract says: success yields lrn_ ids for that tenant, at most 50, and failure yields timeout or upstream. A JSON file checked into git and a fake used in unit tests both have to pass. When a real adapter arrives, it passes the same function before anyone points it at production.

    TermMeaning in this lesson
    UnitOne function, no I/O
    IntegrationRoute or job plus an in-memory store
    ContractShared assertions over a fixture and a fake
    FixtureCommitted JSON with synthetic ids
    ConsumerThe workflow that calls lookupStalled
    Provider of the contractThe enrollment adapter, not the LLM provider
    Schema gateA fixture may be committed when this lesson's checks pass

    The word "provider" is overloaded in this course. In a contract test, the provider is the supplier of the API you call. The model vendor is a different supplier, and its quality bar is Lesson 54. This lesson's model file is only a schema gate so a recorded completion cannot smuggle a key into the repository.

    Why Do We Need It?

    text
    Each package ships with a happy-path demo
    |
    v
    A route trusts body.tenantId, a fixture gains an email, the fake drops the cap
    |
    v
    Unit tests on pure rules, integration on the seam, one contract function on both doubles
    |
    v
    CI fails on the id, the tenant, the cap, or a secret field
    |
    v
    Lesson 54 may score behavior, and Lesson 55 may open a browser

    Benefits:

    • A retention change fails a unit test in milliseconds.
    • A cross-tenant purge fails an integration test without Postgres installed.
    • An enrollment fixture and the fake share assertLookupContract, so they drift only by failing CI.
    • Secret material fails the schema gate before a reviewer has to notice it.
    • The suite stays offline. A red build means a logic change, not a vendor outage.

    Real World Example

    A Northwind fixture lists lrn_priya and lrn_omar. A bad edit adds lrn_contoso and an apiKey field "so the demo can run." The contract test fails on the tenant fence and on the secret field. The integration test still purges only Northwind when now is 31 days later. The unit test still rejects a handle that is not sec_....

    The same split is how a payments team unit-tests fee math, integration-tests a ledger transaction, and contract-tests the bank file format. Amazon-style order APIs publish consumer contracts so a warehouse payload cannot add a surprise field. Google and Microsoft API reviews keep recorded samples free of customer content. A hospital interface contract can require an order id and forbid a free-text diagnosis in the operational feed. TechLearningPro's version is the stalled-learner document and the privacy store.

    Internal Working

    1. npm test runs node --test on *.test.ts. Unit files import pure modules only.
    2. retentionDecision and redactForTrace are asserted with literals. The clock is an argument, never Date.now() inside the assertion.
    3. The integration file builds a PrivacyStore in memory, seeds two tenants, and calls purgeExpired with new Date("2026-02-01T00:00:00.000Z").
    4. postExport reads session.tenantId. If body.tenantId is present and different, the route returns 403 and does not call the store.
    5. loadLookupFixture reads the JSON file from a path the test passes. The loader rejects objects that contain apiKey, authorization, url, or @.
    6. assertLookupContract(tenantId, result) checks the result type. On success, every id matches ^lrn_[a-z0-9_]+$, none contain the other tenant's name, and the length is at most 50. On failure, the reason is timeout or upstream.
    7. The in-memory enrollment fake is passed through the same function as the file.
    8. assertModelSchema checks promptVersion === "cohort-reminder-v1", checks output is a string, and checks the serialized row has no key, URL, or email.
    9. Failures throw with the fixture id. The runner prints that id. The test does not retry against a network.
    10. A test that needs a live model is not part of this file. Lesson 54 keeps scoring offline too. A nightly live job, if finance approves one later, is a different script with a budget and a secret mounted by CI, and it is outside this lesson.

    Architecture

    flowchart TD
      Unit[Unit: classify, redact, retention]
      Integ[Integration: route plus memory store]
      Contract[assertLookupContract]
      File[northwind-stalled.json]
      Fake[In-memory enrollment]
      Schema[assertModelSchema]
      ModelFile[cohort-reminder-v1.json]
      CI[Offline CI job]
    
      Unit --> CI
      Integ --> CI
      File --> Contract
      Fake --> Contract
      Contract --> CI
      ModelFile --> Schema
      Schema --> CI
    text
    Pull request
    |
    v
    Unit tests (no I/O)
    |
    v
    Integration tests (memory, frozen now, session tenant)
    |
    v
    Contract tests (fixture + fake, same assertions)
    |
    v
    Schema gate on recorded model strings
    |
    +--> pass --> Lesson 54 may score those strings
    +--> fail --> stop, no browser, no vendor

    Request flow for postExport starts at the session. Response flow is the learner's row or a 403. The contract flow has no HTTP at all: it is a function over data.

    Deep Dive

    What each layer is allowed to touch

    Unit tests may import classify.ts and retention.ts. They may not import a server, a pg client, or a fixture loader that reads disk. Disk belongs to the contract test, where the thing under test is the file itself.

    Integration tests may use a Map. They may open the privacy store interface. They should still finish in well under a second. If a test boots Next.js, it has become an end-to-end test and belongs in Lesson 55 with a clear tag.

    Contract tests may read JSON from fixtures/. They may not fetch. A comment that says "skip if offline" is a failed design. CI is supposed to be offline for this job.

    The enrollment contract

    The workflow's needs are small and worth writing down:

    • ok: true carries learnerIds: string[].
    • Each id matches lrn_ plus lowercase slug characters.
    • When tenantId is northwind, no id contains contoso, and the reverse.
    • Length is 0 through 50. The workflow also rejects above 50, and the contract stops the fixture from advertising a larger page.
    • ok: false carries timeout or upstream only. A third reason would force the workflow to guess.

    The fake used in Lesson 47 filtered lrn_contoso for Northwind. This lesson promotes that behavior from "a line inside one test" to a function both the fake and the file must satisfy. A future HTTP adapter must call assertLookupContract in its own test with a recorded body before it is allowed to parse production traffic.

    The model schema gate

    Recorded model outputs are useful and dangerous. They are useful because Lesson 54 can score them without spend. They are dangerous because people paste a curl command into the fixture "for context." assertModelSchema rejects apiKey, authorization, url, and @. The output is a string the scorer will parse later. This lesson does not decide whether that string is a valid template. Splitting schema from behavior keeps a privacy failure loud even when the JSON is otherwise interesting.

    Session over body

    The integration route is the place Lesson 49 usually breaks. A client posts { "tenantId": "contoso" } while the cookie says Northwind. postExport compares the two and returns 403 when they differ. When the body omits the tenant, the session tenant is the only one used. The store is then called with that id. The test seeds both tenants and asserts the Contoso email never appears in the Northwind response.

    Clocks and isolation

    now is an argument. Tests do not stub the global clock, because a stub leaks into the next test in the same process. Two integration tests build two stores. There is no module-level array.

    Parallelism is safe while every test owns its data. Node's test runner may run files concurrently. A shared fixture file is read-only, which is safe. A shared database would not be, and this lesson does not introduce one.

    What these tests will not claim

    A green contract does not mean the enrollment service is up. A green schema gate does not mean the model told the truth. A green purge test does not mean Postgres permissions are correct. Those are later layers: a smoke probe with a health check, Lesson 54's score, and a migration test against a real engine in the deployment lessons. Claiming more than the layer saw is how a release note lies.

    Code Examples

    Place tests in packages/privacy/src/ and fixtures in fixtures/. The contract helper lives in packages/enrollment/src/contract.ts so the workflow and the adapter share it.

    Simple example: unit tests of the clock and the redactor

    packages/privacy/src/unit.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { classifyField, redactForTrace } from "./classify.js";
    import { retentionDecision } from "./retention.js";
    const TOKEN = "TEST_ONLY_MODEL_TOKEN";
    test("day 30 keeps personal data and day 31 purges it", () => {
    assert.equal(retentionDecision({ dataClass: "personal", ageDays: 30, published: true }), "keep");
    assert.equal(retentionDecision({ dataClass: "personal", ageDays: 31, published: true }), "purge");
    assert.equal(retentionDecision({ dataClass: "operational", ageDays: 90, published: true }), "keep");
    assert.equal(retentionDecision({ dataClass: "operational", ageDays: 91, published: true }), "purge");
    });
    test("redaction removes the fixture marker and an address", () => {
    const text = redactForTrace(`priya@northwind.example MODEL_API_KEY=${TOKEN}`);
    assert.equal(text.includes(TOKEN), false);
    assert.equal(text.includes("@"), false);
    assert.equal(classifyField("transcript", "draft").dataClass, "personal");
    });

    These tests import no store and no fixture loader. A failure here is a policy bug, and the file should finish before a human notices the process started.

    Intermediate example: the shared contract

    packages/enrollment/src/contract.ts

    typescript
    import assert from "node:assert/strict";
    export type LookupResult =
    | { ok: true; learnerIds: string[] }
    | { ok: false; reason: "timeout" | "upstream" };
    const ID = /^lrn_[a-z0-9_]+$/;
    const MAX_IDS = 50;
    /**
    * Consumer contract for lookupStalled.
    * Northwind results may not carry a Contoso id, and the reverse.
    */
    export function assertLookupContract(tenantId: string, result: LookupResult): void {
    if (!result.ok) {
    assert.equal(result.reason === "timeout" || result.reason === "upstream", true);
    return;
    }
    assert.equal(result.learnerIds.length <= MAX_IDS, true);
    const other = tenantId === "northwind" ? "contoso" : "northwind";
    for (const id of result.learnerIds) {
    assert.match(id, ID);
    assert.equal(id.includes(other), false);
    }
    }
    export interface ModelSchemaRow {
    id: string;
    promptVersion: string;
    output: string;
    }
    const BANNED = ["apiKey", "authorization", "url", "@", "TEST_ONLY_MODEL_TOKEN"];
    /** Schema only. Lesson 54 decides whether output is a valid template. */
    export function assertModelSchema(row: ModelSchemaRow): void {
    assert.equal(row.promptVersion, "cohort-reminder-v1");
    assert.equal(typeof row.output, "string");
    const serialized = JSON.stringify(row);
    for (const banned of BANNED) {
    assert.equal(serialized.includes(banned), false, `${row.id} contains ${banned}`);
    }
    }

    assertLookupContract is the function a real adapter test will call later. Keeping the cap at 50 matches Lesson 47 so the fixture cannot outgrow the workflow.

    Enterprise example: integration route, fixture file, and both doubles

    packages/privacy/src/export-route.ts

    typescript
    import { exportPersonal, type PersonalRow } from "./store.js";
    export interface ExportSession {
    tenantId: string;
    userId: string;
    role: "learner" | "instructor" | "support" | "admin";
    }
    export interface ExportBody {
    learnerId?: string;
    tenantId?: string;
    }
    /**
    * Tenant comes from the session. A conflicting body tenant is 403.
    * Learners may export only their own learner id.
    */
    export function postExport(
    session: ExportSession | null,
    body: ExportBody,
    rowsForTenant: (tenantId: string) => PersonalRow[],
    ): { status: number; body: PersonalRow[] | { error: string } } {
    if (!session?.tenantId || !session.userId) return { status: 401, body: { error: "unauthorized" } };
    if (body.tenantId && body.tenantId !== session.tenantId) return { status: 403, body: { error: "tenant_mismatch" } };
    const learnerId = body.learnerId ?? session.userId;
    if (session.role === "learner" && learnerId !== session.userId) return { status: 403, body: { error: "forbidden" } };
    const rows = exportPersonal(rowsForTenant(session.tenantId), learnerId);
    return { status: 200, body: rows };
    }

    fixtures/enrollment/northwind-stalled.json

    json
    {
    "tenantId": "northwind",
    "result": { "ok": true, "learnerIds": ["lrn_priya", "lrn_omar"] }
    }

    fixtures/model/cohort-reminder-v1.json

    json
    [
    {
    "id": "valid-template",
    "promptVersion": "cohort-reminder-v1",
    "output": "{\"templateId\":\"cohort_reminder_v1\"}"
    }
    ]

    packages/enrollment/src/contract.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { readFileSync } from "node:fs";
    import { assertLookupContract, assertModelSchema, type LookupResult, type ModelSchemaRow } from "./contract.js";
    import { postExport } from "../../privacy/src/export-route.js";
    import { purgeExpired, type PersonalRow, type PrivacyStore, type Tombstone } from "../../privacy/src/store.js";
    test("the committed enrollment fixture and the fake honor the same contract", () => {
    const parsed = JSON.parse(readFileSync(new URL("../../../fixtures/enrollment/northwind-stalled.json", import.meta.url), "utf8")) as {
    tenantId: string;
    result: LookupResult;
    };
    assert.equal(JSON.stringify(parsed).includes("@"), false);
    assertLookupContract(parsed.tenantId, parsed.result);
    const fake = lookupFake("northwind", ["lrn_priya", "lrn_omar", "lrn_contoso"]);
    assertLookupContract("northwind", fake);
    if (fake.ok) assert.equal(fake.learnerIds.includes("lrn_contoso"), false);
    const timeout: LookupResult = { ok: false, reason: "timeout" };
    assertLookupContract("northwind", timeout);
    });
    test("a model fixture with a key or a url is rejected, and the committed file passes", () => {
    const rows = JSON.parse(readFileSync(new URL("../../../fixtures/model/cohort-reminder-v1.json", import.meta.url), "utf8")) as ModelSchemaRow[];
    for (const row of rows) assertModelSchema(row);
    assert.throws(() => assertModelSchema({
    id: "leaky",
    promptVersion: "cohort-reminder-v1",
    output: "https://example.test",
    }));
    });
    test("export uses the session tenant and purge leaves the other tenant", () => {
    const memory = memoryStore([
    person("northwind", "lrn_priya", "2026-01-01T00:00:00.000Z"),
    person("contoso", "lrn_contoso", "2026-01-01T00:00:00.000Z"),
    ]);
    const ok = postExport(
    { tenantId: "northwind", userId: "usr_support", role: "support" },
    { learnerId: "lrn_priya", tenantId: "contoso" },
    memory.store.listPersonal,
    );
    assert.equal(ok.status, 403);
    const exported = postExport(
    { tenantId: "northwind", userId: "usr_support", role: "support" },
    { learnerId: "lrn_priya" },
    memory.store.listPersonal,
    );
    assert.equal(exported.status, 200);
    assert.equal(JSON.stringify(exported.body).includes("contoso"), false);
    const tombstones = purgeExpired(memory.store, "northwind", { now: new Date("2026-02-01T00:00:00.000Z") });
    assert.equal(tombstones.length, 1);
    assert.equal(memory.store.listPersonal("contoso").length, 1);
    });
    function lookupFake(tenantId: string, stalled: string[]): LookupResult {
    const learnerIds = stalled.filter((id) => (tenantId === "northwind" ? !id.includes("contoso") : !id.includes("northwind")));
    return { ok: true, learnerIds };
    }
    function person(tenantId: string, learnerId: string, createdAt: string): PersonalRow {
    return { tenantId, learnerId, email: `${learnerId}@${tenantId}.example`, transcript: "draft", createdAt };
    }
    function memoryStore(seed: PersonalRow[]) {
    const rows = [...seed];
    const tombstones: Tombstone[] = [];
    const store: PrivacyStore = {
    listPersonal: (tenantId) => rows.filter((item) => item.tenantId === tenantId),
    replacePersonal: (tenantId, next) => {
    const rest = rows.filter((item) => item.tenantId !== tenantId);
    rows.length = 0;
    rows.push(...rest, ...next);
    },
    writeTombstone: (tombstone) => tombstones.push(tombstone),
    };
    return { store, tombstones };
    }

    The path from packages/enrollment/src/ up to fixtures/ is three levels if the repo root holds both packages/ and fixtures/. Adjust the relative URL if your layout differs, and keep the fixture inside the repository so CI does not download it.

    Run:

    bash
    npx tsc --noEmit
    node --experimental-strip-types --test packages/privacy/src/unit.test.ts packages/enrollment/src/contract.test.ts

    No test reads an API key. readFileSync reads only the two JSON files you committed.

    Architecture Diagram

    text
    unit.test.ts
    |
    +--> retentionDecision, redactForTrace, classifyField
    contract.test.ts
    |
    +--> fixtures/enrollment/northwind-stalled.json
    +--> lookupFake
    +--> assertLookupContract
    |
    +--> fixtures/model/cohort-reminder-v1.json
    +--> assertModelSchema
    |
    +--> postExport + in-memory PrivacyStore
    |
    +--> 403 on tenant mismatch
    +--> purgeExpired(northwind) leaves contoso

    Version pins:

    text
    privacy-retention-v1
    cohort-reminder-v1
    enrollment lookup contract (max 50, lrn_ ids, closed reasons)

    Real-Time Enterprise Example

    The pull request job runs the unit file and the contract file on every push. It does not receive MODEL_API_KEY. A developer who adds lrn_contoso to the Northwind fixture sees assertLookupContract fail. A developer who pastes a curl URL into the model fixture sees assertModelSchema fail with the row id leaky or whichever id they used.

    The export route in the API process is the same postExport. Production passes a Postgres loader that already includes WHERE tenant_id = $1. The integration test uses the memory loader so a laptop without Docker can still prove the 403. A nightly job, described in the deployment lessons, can run the same assertions against a migrated database. The assertions are not rewritten for that job.

    Challenge: the enrollment team wants a 51st id "just in the fixture," support wants the body tenant to win "for impersonation," and someone adds apiKey so a local script can find it. The contract fails the length. Impersonation, if product requires it, is a support role plus an audit event in Lesson 45, and the session tenant remains the data scope unless a separate audited override exists. The schema gate fails the key. You do not weaken the assertion to keep the script.

    Performance Optimization

    Unit tests should be the bulk of the count and the smallest share of the time. Keep them synchronous. The contract test reads two small JSON files once. The integration test mutates arrays in memory. If this job exceeds a few seconds, a test has started booting a framework or sleeping on a timeout, and that test moves to Lesson 55 or to a nightly lane.

    Do not point integration tests at a shared developer database. Shared state makes the suite order-dependent and slow. A transaction-per-test against a local Postgres is a valid later step when SQL itself is the risk. Until then, the memory store is the honest double of the interface.

    Contract fixtures stay small: ids and a version. Large transcripts belong in no fixture. That keeps CI clones fast and keeps personal data out of git, which is also the Lesson 52 rule.

    Security

    • Authentication. postExport returns 401 without a session. The test covers that path by passing null if you add the case in the exercise.
    • Authorization. Learners export their own id. A mismatched body tenant is 403.
    • Least privilege. The test process has no provider credential and no database password.
    • Validation. Contracts reject unexpected id shapes and unexpected error reasons.
    • Secrets. Banned substrings include apiKey, authorization, url, @, and TEST_ONLY_MODEL_TOKEN inside committed model fixtures. The unit test is the one place the marker exists, and it asserts absence from output.
    • Tenant isolation. The fake filters the other tenant's marker. The purge test asserts the other tenant's row count.
    • Injection. Fixture JSON is parsed and then checked. It is not evaluated.
    • OWASP. The relevant issues are broken access control and sensitive data in repositories. The controls are the session check and the schema gate.

    Common Mistakes

    1. One "integration" test that calls the model. Symptom: CI fails whenever the vendor blips, or CI stores a key. Cause: a demo script was renamed to a test. Fix: this job stays on fixtures. Lesson 54 scores recorded strings.
    2. Copying assertions into the fake and the file test. Symptom: the file allows 80 ids and the fake allows 50. Cause: two copies drifted. Fix: one assertLookupContract.
    3. Trusting body.tenantId. Symptom: a Northwind session reads Contoso. Cause: the route used the JSON field. Fix: 403 on mismatch, and an integration test that seeds both.
    4. Using Date.now() in a retention test. Symptom: the suite fails for one hour a year or fails on a slow laptop. Cause: the boundary was "now plus 30 days" computed during the run. Fix: pass ageDays literally, or pass a fixed Date.
    5. Sharing a module-level array between tests. Symptom: order-dependent failures. Cause: const rows = [] at the top of the file. Fix: memoryStore() inside each test.
    6. Committing a curl sample as a fixture. Symptom: a key or a customer email is in git. Cause: the schema gate was not applied to new files. Fix: run assertModelSchema on every row in the directory.
    7. Asserting a snapshot of an entire error page. Symptom: a copy change breaks the contract. Cause: a contract was used as a screenshot. Fix: assert ids, reasons, and banned substrings.
    8. Skipping tests when the file is missing. Symptom: a deleted fixture turns the suite green. Cause: try/catch around readFileSync. Fix: let the throw fail the run.
    9. Retrying contract tests. Symptom: a flake disappears and the bug stays. Cause: retries were copied from a browser config. Fix: these tests are deterministic. Retries belong to Lesson 55's browser layer, and even there they are limited.
    10. Booting the whole app to check a 403. Symptom: the job takes minutes. Cause: the route was only reachable through HTTP. Fix: postExport is a function. Lesson 55 covers the button that calls it.
    11. Treating schema success as model quality. Symptom: a release note says the reminder was evaluated. Cause: assertModelSchema was described as a score. Fix: say "the fixture is safe to commit." Lesson 54 scores the output.
    12. Putting TEST_ONLY_MODEL_TOKEN in the fixture to "see if the gate works." Symptom: the committed file fails, or someone later treats the file as a real env. Cause: the negative case was saved as data. Fix: the negative case is an object literal inside the test, as leaky is.

    Best Practices

    1. Keep the pyramid explicit in the test file names: unit, contract, and later e2e.
    2. Run unit tests on every push.
    3. Pass clocks as arguments.
    4. Give each test its own store.
    5. Read fixtures with readFileSync from a URL relative to the test, and fail if they are absent.
    6. Share contract assertions between fakes and files.
    7. Cap enrollment ids at 50 in the contract and in the workflow.
    8. Keep error reasons a closed union.
    9. Fence tenant markers inside assertLookupContract.
    10. Gate model fixtures on version, type, and banned substrings.
    11. Leave behavioral scoring of model strings to Lesson 54.
    12. Take the tenant from the session in routes under test.
    13. Return 403 when the body names another tenant.
    14. Keep emails out of committed fixtures. The integration seed may use @tenant.example inside the test process only.
    15. Assert the other tenant's row count after a purge.
    16. Do not retry deterministic tests.
    17. Do not skip on missing files.
    18. Do not call fetch from this job.
    19. Do not mount MODEL_API_KEY into this job.
    20. Keep fixtures small and synthetic.
    21. When a real adapter appears, call the same contract function on a recorded body.
    22. Report the fixture id in the assertion message.
    23. Move any test that boots a browser into Lesson 55.

    Interview Questions & Answers

    Beginner

    1. What is the difference between a unit test and an integration test here?
      A unit test calls retentionDecision or redactForTrace with plain values. An integration test calls postExport or purgeExpired with a session and a store. The second test is still in memory. It exists to catch wiring, especially the tenant source.

    2. What is a contract test in this lesson?
      It is assertLookupContract applied to a committed JSON file and to the fake the workflow uses. Both have to agree on id shape, the other-tenant fence, the cap, and the error reasons.

    3. Why is the model file not "evaluated" yet?
      assertModelSchema checks that the row is safe and versioned. It does not parse the template. Lesson 54 decides whether the output is acceptable behavior.

    Intermediate

    1. How do you stop a fixture and a fake from drifting?
      Both call one function. A new rule, such as "ids are unique," is added once. A pull request that updates only the fake fails the file, or the reverse.

    2. How does the export test prove tenant isolation?
      The store contains Northwind and Contoso. The session is Northwind and the body says Contoso. The status is 403. A second call without a body tenant returns Priya's row, and the JSON does not contain contoso.

    3. Why freeze now?
      Day 31 has to mean the same instant on every laptop and in CI. new Date("2026-02-01T00:00:00.000Z") against a January 1 row is that instant. Date.now() would make the test depend on the calendar.

    Senior

    1. How would you add Postgres without rewriting the assertions?
      Implement PrivacyStore with SQL that requires tenant_id. Wrap each integration test in a transaction that rolls back. Call the same postExport and purgeExpired. Keep the memory tests so a SQL outage is not the only signal. The contract fixtures stay file-based either way.

    2. What belongs in CI on the pull request, and what waits?
      Unit, integration-in-memory, and contract schema run on the pull request with no secrets. Browser tests from Lesson 55 can run as a smaller smoke set on the pull request and a wider set nightly. A live model run is a separate budgeted job, and this lesson does not add it.

    Architect

    1. How do you version a contract when enrollment adds a field?
      Unknown fields are ignored by the consumer until the contract names them. A breaking change, such as renaming learnerIds, is a new fixture directory and a new assertion function. Old workflow versions keep reading the old fixture. You do not silently accept a second id field that could carry another tenant.

    2. How does this relate to consumer-driven contracts in a larger company?
      The idea matches a Pact-style exchange: the consumer publishes the examples it depends on, and the provider build verifies them. This lesson keeps the exchange as a function and a JSON file because there is one consumer and no broker yet. A broker is justified when several services must verify the same examples in separate repositories. The assertions do not get weaker when you add a broker.

    3. What is a false sense of safety you would reject?
      A green schema gate described as "AI quality," a 200 from a health URL described as "tenant isolation," or a mocked client that returns success and never runs assertLookupContract. Each of those can stay green while Contoso ids ship. The proof you accept is the shared contract plus the session test.

    4. How should a flaky test be handled?
      Deterministic tests are fixed or deleted. They are not retried. If the flake is a real clock, a shared array, or a network call, that is the bug. Browser flakes are Lesson 55's topic, and the fix there starts with locators and isolated state, not with an unlimited retry.

    Knowledge Check

    1. What problem does this capability solve?

    It catches policy bugs, tenant wiring bugs, and unsafe fixtures at three explicit layers, all without a provider key or a live enrollment service.

    2. What alternatives exist, and when would you choose each?

    A pure unit test fits a clock or a redactor. An in-memory integration test fits a route and a job. A contract fits a boundary another team could break. A browser test fits a click. A live vendor call fits a budgeted probe after the offline suite is green, and it is not a substitute for any of the three.

    3. Which data, identity, and trust boundaries matter?

    The session tenant is the one postExport uses. Fixtures are untrusted files until the schema gate runs. The fake is untrusted until assertLookupContract runs. Model strings are untrusted text with a version, not a credential store.

    4. What can fail, and how should the system respond?

    A day-count change fails the unit test. A cross-tenant body fails with 403. A Contoso id in a Northwind fixture fails the contract. A URL or key in a model fixture fails the schema gate. Missing files fail the run. Nothing in this layer retries or calls out.

    5. How would you test quality, security, performance, and cost?

    Quality of the suite is "the assertion failed for the right reason," which you check by adding the leaky row and the mismatched tenant. Security is the banned-substring list and the 403. Performance is a job that stays on memory and small files. Cost is a pull request that never spends model tokens.

    Practical Exercise

    Add a unit test that a learner role exporting lrn_omar while the session user is lrn_priya returns 403, and that the same learner exporting lrn_priya returns 200. Add a contract case whose failure reason is "nope" and show that it throws. Keep both cases offline.

    Deliverable and Rubric

    Submit the pyramid diagram, the test files, the two fixtures, and a sentence on what assertModelSchema deliberately does not score.

    AreaWeight
    Conceptual accuracy and architecture20%
    Working implementation and code quality25%
    Security, privacy, and responsible AI20%
    Testing, reliability, and observability20%
    Documentation and decision rationale15%

    Production checklist:

    • Unit tests do not touch the network or a clock they do not control.
    • Integration tests own their store and cover tenant mismatch.
    • Enrollment fixtures and fakes share assertLookupContract.
    • Model fixtures share assertModelSchema and pin cohort-reminder-v1.
    • Banned substrings include keys, URLs, emails, and the fixture token.
    • Missing fixtures fail the job.
    • The pull request job has no MODEL_API_KEY.
    • Behavioral model scoring is left to Lesson 54.
    • Browser coverage is left to Lesson 55.

    Key Takeaways

    1. Unit tests cover pure policy. Integration tests cover seams you own. Contracts cover shapes you share.
    2. The runner is node:test, and this job is offline.
    3. Day 30 keeps personal data. Day 31 purges it. The dates in the test are fixed.
    4. postExport trusts the session tenant.
    5. A conflicting body tenant is 403.
    6. assertLookupContract caps ids at 50 and fences the other tenant.
    7. The fake and the JSON file call that same function.
    8. assertModelSchema is a safety gate, not a quality score.
    9. cohort-reminder-v1 is the allowed prompt version on the fixture.
    10. Negative cases live in the test as literals, not as committed secrets.
    11. Tests do not share a mutable store.
    12. Missing files fail closed.
    13. Deterministic tests are not retried.
    14. Postgres can implement the same store interface later.
    15. Lesson 54 is allowed to trust a fixture only after this gate.

    Summary

    Lesson 53 gives the privacy package and the enrollment boundary a test pyramid that a laptop can run. Pure clocks stay fast, the export route proves it will not follow a body tenant, and a single contract function keeps the fixture honest. Recorded model strings may enter the repository only when they are versioned and free of secrets. What those strings mean for the reminder is the next lesson.

    Next Lesson Preview

    Testing LLM Features and Agent Workflows scores the fixture strings this lesson only sanitized. You will check template ids, denied tools, empty-cohort spend, and traces that must not contain an email, still without a live key. A judge may comment. It may not overturn a failed check.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.