From 41d7b3ee894372c19dd31ade0947cd46b7175947 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 22:23:11 +0100 Subject: [PATCH 1/6] feat(collections): deep collection testing, approved fixtures and test maintenance Collection Testing Engine for list operations, from a reviewed deps "collection" mapping checked strictly against the spec (mismatch = INVALID_REVIEWED_CONFIG): - strategy A (create & verify): controlled datasets with a unique marker in an isolating filter, cleanup in finally; filter (match + non-match), sort (3 distinct values created out of order), pagination (page size + 1 records), uniqueness, persisted fields by policy, bounded polling; - strategy B (approved fixtures): generate --fixtures compares a list with a fixture a person approved; fixtures capture writes candidates only; fixtures refresh --draft-pr proposes a changed candidate (one PR per operation); - strategy C (read-only) with explicit skips; strategy recorded per operation; - create -> list -> update -> list -> delete -> list scenario; - case ID vocabulary v3; same cases in TypeScript and Python. maintain: spec diff -> deterministic regeneration -> registry and manifest validation -> one Draft PR per suite (updated, never duplicated, never merged) with a summary of changed operations, tests, expectations, fixtures and gaps. Fault injection: the demo API simulates six list defects (DEMO_FAULT); scripts/mutation-check.ts requires each to be caught. The previous generator's 65 demo tests catch 0/6; the collection tests catch 6/6 in both languages. Fixes: a single resource with an array field is not an unconfigured collection; hand-written _support/api/*Api.ts stay in the generation manifest. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 20 +- CHANGELOG.md | 12 + README.md | 30 +- demo-api/deps.json | 28 + demo-api/expected-gaps.json | 1 + demo-api/fixtures/approved/listItems.json | 41 ++ demo-api/openapi.yaml | 23 + demo-api/server.ts | 31 +- docs/OPENAPI_CHANGE_TRIGGER.md | 13 + docs/SUPPORT_MATRIX.md | 68 +- scripts/mutation-check.ts | 85 +++ src/cases/assign.ts | 38 +- src/cases/ids.ts | 13 +- src/cases/validate.ts | 4 +- src/cli.ts | 111 +++- src/contract/contract.py | 135 ++++ src/fixtures/capture.ts | 114 ++++ src/fixtures/fixtures.ts | 161 +++++ src/generate/collection-render.ts | 598 ++++++++++++++++++ src/generate/collection-tests.ts | 128 ++++ src/generate/collection.ts | 140 ++++ src/generate/coverage.ts | 1 + src/generate/generate.ts | 49 +- src/generate/graph.ts | 6 + src/generate/python.ts | 18 +- src/generate/templates.ts | 157 ++++- src/maintain.ts | 172 +++++ src/pr.ts | 35 + .../coverage/kitchen-sink.expected-gaps.json | 2 +- tests/unit/collection.test.ts | 148 +++++ tests/unit/core.test.ts | 2 +- tests/unit/coverage-report.test.ts | 2 +- tests/unit/coverage.test.ts | 14 +- 33 files changed, 2353 insertions(+), 47 deletions(-) create mode 100644 demo-api/deps.json create mode 100644 demo-api/fixtures/approved/listItems.json create mode 100644 scripts/mutation-check.ts create mode 100644 src/fixtures/capture.ts create mode 100644 src/fixtures/fixtures.ts create mode 100644 src/generate/collection-render.ts create mode 100644 src/generate/collection-tests.ts create mode 100644 src/generate/collection.ts create mode 100644 src/maintain.ts create mode 100644 tests/unit/collection.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d68133a..6ad5135 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,7 +71,7 @@ jobs: ' - name: Generate tests (resource/method/functional|contract|scenarios) and run them once - run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run -o reports/generate --fail-on never + run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --deps demo-api/deps.json --fixtures demo-api/fixtures/approved --scenarios demo-api/scenarios.json --allow-write --run -o reports/generate --fail-on never - name: Self-check - generated suite fails only on the known defect run: | @@ -103,7 +103,7 @@ jobs: - name: Generate Python tests (pytest + requests) and run them once run: | pip install pytest requests jsonschema - npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never + npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --deps demo-api/deps.json --fixtures demo-api/fixtures/approved --scenarios demo-api/scenarios.json --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never node -e ' const r = require("./reports/generate-python/report.json"); const bad = r.generated.scenarios.filter(s => s.status === "CONTRACT_MISMATCH" || s.status === "TEST_FAILURE").map(s => s.name); @@ -122,6 +122,22 @@ jobs: npx tsx src/cli.ts registry validate tests/api-python/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null npx tsx src/cli.ts manifest validate --tests-dir tests/api-python + - name: Fault injection - the collection tests must catch every injected defect (TS and Python) + # The demo API runs once per DEMO_FAULT (ignored filter, wrong sort, hidden record, duplicates, wrong field, + # overlapping pages) on its own port: clean without a fault, at least one failure with each. + run: | + npx tsx scripts/mutation-check.ts --lang typescript --port 3200 tests/api/items/get + npx tsx scripts/mutation-check.ts --lang python --port 3300 tests/api-python/items/get + node -e ' + for (const l of ["typescript", "python"]) { const r = require("./reports/mutation-" + l + ".json"); console.log(l, r.detected + "/" + r.injected); if (r.detected !== r.injected) process.exit(1); } + ' + + - name: Maintenance - a spec change is regenerated, validated and summarized (no PR in CI) + run: | + sed 's/enum: \[name, -name, price, -price\]/enum: [name, -name, price]/' demo-api/openapi.yaml > reports/openapi.changed.yaml + npx tsx src/cli.ts maintain reports/openapi.changed.yaml --base demo-api/openapi.yaml --deps demo-api/deps.json --tests-dir tests/api -o reports/maintain + grep -q 'sort value "-price" is not documented' reports/maintain/maintenance-summary.md + - name: Analyse the legacy example project (init + run) working-directory: examples/legacy-project run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index eff1d90..d217ce5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- **Collection testing** (docs/SUPPORT_MATRIX.md, "Collections"): + - reviewed deps `collection` mapping, checked strictly against the spec (`INVALID_REVIEWED_CONFIG` gap on a mismatch); + - strategy A (create & verify): controlled datasets with a unique marker in an isolating filter, cleanup in `finally`; strategy C (read-only) with explicit skips; strategy recorded per list operation in `coverage-gaps.json`; + - assertions in TypeScript and Python alike: contains / not contains, persisted fields by policy (exact, tolerance, schema, ignore), all match a filter, unique by, sorted by, page size, no duplicates across pages; offset and page/size paging; bounded polling for documented eventual consistency; + - create → list → update → list → delete → list scenario on the list operation; + - case ID vocabulary v3: `collection-contains`, `filter`, `sort`, `pagination`, `unique`, `fixture`. +- **Approved fixtures (strategy B):** `generate --fixtures ` compares a list with `.json` approved by a person; `fixtures capture` writes candidates only; `fixtures refresh --draft-pr` proposes a changed candidate in one Draft PR per operation (updated, never duplicated). Approved files are never written by the agent. +- **`maintain`:** spec diff → deterministic regeneration → registry and manifest validation → one Draft PR per suite with a summary (changed operations, files and cases, expectations old → new, fixtures, stale reviewed configuration, gaps before → after). Never merges; no PR when validation fails or nothing changed. +- **Fault injection:** the demo API simulates six list defects (`DEMO_FAULT`); `scripts/mutation-check.ts` runs a generated suite against each, and CI requires 6/6 detected in TypeScript and Python. The previous generator detected 0/6. +- Demo API: `offset`, `tag` and `sort` on `GET /items`; two reference items tagged `catalog` (the approved demo fixture). +- Fixes: a GET of a single resource with an array field is no longer reported as an unconfigured collection; hand-written `_support/api/*Api.ts` stay in the generation manifest after the first run. + - **Coverage completeness** (see docs/SUPPORT_MATRIX.md): - one physical test → one stable case ID (vocabulary v2: `accepted-value`, `invalid-credentials`, `method-not-allowed`, `precondition-failed`), checked on the real run (Playwright report, pytest collection); cases no longer generated become tombstones; - recursive request-body negative cases at any depth, exactly one broken rule each (verified with ajv), configurable limit `--max-cases` with dropped cases reported; diff --git a/README.md b/README.md index 0e24812..66db03c 100644 --- a/README.md +++ b/README.md @@ -143,10 +143,29 @@ Coverage is reported, never implied. The full keyword-by-keyword table is in [do - responses: status, Content-Type, headers, JSON / text schema, no body where none is documented, writeOnly; - documented errors with a safe trigger: 400 / 422, 401 (missing and invalid credentials), 404, 405 (GET only), 412, 415. -**Needs your confirmation (deps or scenarios file):** CRUD chains and cleanup, 409 conflicts (`conflictOn`), fields a create returns as sent (`echoes`), values taken from existing data (`fill`), and every business flow (`--scenarios`): state transitions, parent → child, login / refresh, list / search / pagination. +**Needs your confirmation (deps or scenarios file):** CRUD chains and cleanup, 409 conflicts (`conflictOn`), fields a create returns as sent (`echoes`), values taken from existing data (`fill`), collection semantics (`collection`: identifier, persisted fields and their comparison policy, filters, sorts, paging, uniqueness, eventual consistency), approved fixtures (`--fixtures`), and every other business flow (`--scenarios`): state transitions, parent → child, login / refresh. **Never generated (reported as gaps):** 403 without a reviewed role setup, 429, a 405 that would need an unsafe method, oneOf / anyOf branches other than the one sent, rules that cannot be broken without breaking another, media types other than JSON / text, and anything the spec does not state. +## Collections, fixtures and maintenance + +The number of tests is not the goal; catching defects is. On the demo API the previous generator's 65 tests miss all six injected list defects (ignored filter, wrong sort, hidden record, duplicates, wrong field value, overlapping pages); the collection tests catch all six, in TypeScript and Python (`npx tsx scripts/mutation-check.ts tests/api/items/get`). + +```bash +# Deep list tests from a reviewed "collection" mapping (demo-api/deps.json) and approved fixtures +npx tsx src/cli.ts generate demo-api/openapi.yaml --deps demo-api/deps.json --fixtures demo-api/fixtures/approved + +# Fixtures are never trusted automatically: capture writes a candidate, refresh proposes it in a Draft PR +npx tsx src/cli.ts fixtures capture demo-api/openapi.yaml --operation listItems -u http://localhost:3100 --query tag=catalog +npx tsx src/cli.ts fixtures refresh demo-api/openapi.yaml --operation listItems -u http://localhost:3100 --draft-pr + +# After a spec change: diff → regenerate → validate → one Draft PR per suite (updated, never duplicated, never merged) +npx tsx src/cli.ts maintain openapi.yaml --base --deps deps.json --draft-pr +``` + +Collection tests create their own records with a unique marker, read them through an isolating filter, and remove them in `finally`; without a confirmed create they run read-only on existing data and skip with the reason when there is not enough. Strategy and reasons per list operation are in `coverage-gaps.json`. Details: [docs/SUPPORT_MATRIX.md](docs/SUPPORT_MATRIX.md#collections-srcgeneratecollectionts-srcfixtures). + + ## Options | Option | Default | | @@ -158,7 +177,7 @@ Coverage is reported, never implied. The full keyword-by-keyword table is in [do | `--max-requests`, `--rps`, `--timeout` | 100, 5, 10s | probe budget and limits | | `--max-examples`, `--max-time`, `--seed` | 25, 120s, 42 | Schemathesis budget, reproducible seed | | `--fail-on` | `mismatch` | `mismatch` / `blocked` / `never` | -| `--deps`, `--tests-dir`, `--run`, `--draft-pr` | | `generate` only | +| `--deps`, `--fixtures`, `--tests-dir`, `--run`, `--draft-pr` | | `generate` only | Credentials: `API_TOKEN` (bearer / OAuth2 / OIDC), `API_USER` + `API_PASSWORD` (basic), `API_KEY` (apiKey header or query). @@ -168,7 +187,10 @@ Credentials: `API_TOKEN` (bearer / OAuth2 / OIDC), `API_USER` + `API_PASSWORD` ( src/spec/ load, bundle, validate (swagger-parser), lint (Redocly), operation catalogue src/audit/ SafeClient, probe, Schemathesis runner + JUnit/JSON parsing, auth + redaction src/contract/ response validator (Ajv), copied verbatim into generated suites -src/generate/ dependency graph, deterministic payloads, Playwright templates, runner +src/generate/ dependency graph, deterministic payloads, Playwright / pytest templates, collection tests, runner +src/fixtures/ approved fixtures: validation, policies, capture of candidates +src/maintain.ts spec change → regenerate → validate → one Draft PR +scripts/ fault injection (mutation-check.ts) src/report/ JSON + Markdown report demo-api/ in-memory target API and its OpenAPI spec tests/unit/ Vitest unit tests @@ -176,7 +198,7 @@ tests/unit/ Vitest unit tests ## Roadmap -- **Stage 2:** more scenario shapes (list-after-create, PUT, nested resources), Schemathesis config export for CI, re-analyse only operations changed since the last spec hash. +- **Stage 2:** more scenario shapes (PUT, nested resources), cursor pagination, Schemathesis config export for CI, re-analyse only operations changed since the last spec hash. - **Stage 3:** optional AI adapter for unconfirmed dependencies, given only the operation, nearby schemas and the open question, with per-task token limits; `BLOCKED` when confidence is low. - **Stage 4:** Jira / GitHub / Telegram triggers and notifications. diff --git a/demo-api/deps.json b/demo-api/deps.json new file mode 100644 index 0000000..58b0319 --- /dev/null +++ b/demo-api/deps.json @@ -0,0 +1,28 @@ +{ + "scenarios": [ + { + "create": "createItem", + "idFrom": "/id", + "param": "itemId", + "read": "getItem", + "update": "updateItem", + "delete": "deleteItem", + "collection": { + "operationId": "listItems", + "items": "/items", + "id": "/id", + "fields": { "/name": "exact", "/price": "tolerance:0.001", "/tags": "exact", "/createdAt": "ignore" }, + "unique": ["/id"], + "filters": [{ "param": "tag", "field": "/tags", "match": "contains" }], + "sorts": [ + { "param": "sort", "value": "name", "field": "/name", "order": "asc" }, + { "param": "sort", "value": "-name", "field": "/name", "order": "desc" }, + { "param": "sort", "value": "price", "field": "/price", "order": "asc" }, + { "param": "sort", "value": "-price", "field": "/price", "order": "desc" } + ], + "page": { "style": "offset", "offsetParam": "offset", "limitParam": "limit", "maxPages": 20 }, + "deletedDisappears": true + } + } + ] +} diff --git a/demo-api/expected-gaps.json b/demo-api/expected-gaps.json index 84bbd0d..6d8230f 100644 --- a/demo-api/expected-gaps.json +++ b/demo-api/expected-gaps.json @@ -1,4 +1,5 @@ { + "CANNOT_ISOLATE_RULE": 1, "MISSING_CLEANUP": 2, "MISSING_RESOURCE_SOURCE": 1, "MISSING_RESPONSE_SCHEMA": 1 diff --git a/demo-api/fixtures/approved/listItems.json b/demo-api/fixtures/approved/listItems.json new file mode 100644 index 0000000..8c96582 --- /dev/null +++ b/demo-api/fixtures/approved/listItems.json @@ -0,0 +1,41 @@ +{ + "schemaVersion": 1, + "operationId": "listItems", + "query": { + "tag": "catalog" + }, + "items": "/items", + "id": "/id", + "policies": { + "/price": "tolerance:0.001", + "/createdAt": "ignore" + }, + "default": "exact", + "exhaustive": true, + "page": { + "style": "offset", + "offsetParam": "offset", + "limitParam": "limit", + "maxPages": 20 + }, + "expected": [ + { + "id": "00000000-0000-4000-8000-000000000001", + "name": "Catalog hammer", + "price": 12.5, + "tags": [ + "catalog" + ], + "createdAt": "2026-11-09T21:13:16.636Z" + }, + { + "id": "00000000-0000-4000-8000-000000000002", + "name": "Catalog screwdriver", + "price": 4.25, + "tags": [ + "catalog" + ], + "createdAt": "2026-11-09T21:13:16.637Z" + } + ] +} diff --git a/demo-api/openapi.yaml b/demo-api/openapi.yaml index d9983f8..042983a 100644 --- a/demo-api/openapi.yaml +++ b/demo-api/openapi.yaml @@ -49,6 +49,29 @@ paths: minimum: 1 maximum: 100 default: 20 + - name: offset + in: query + required: false + description: Items to skip (offset pagination). + schema: + type: integer + minimum: 0 + default: 0 + - name: tag + in: query + required: false + description: Only items carrying this tag. + schema: + type: string + minLength: 1 + maxLength: 30 + - name: sort + in: query + required: false + description: Order of the items; a leading "-" is descending. + schema: + type: string + enum: [name, -name, price, -price] responses: '200': description: Items page diff --git a/demo-api/server.ts b/demo-api/server.ts index 80660b7..e90dff0 100644 --- a/demo-api/server.ts +++ b/demo-api/server.ts @@ -14,6 +14,12 @@ interface Item { } const items = new Map(); +// Reference data present from the start (tag "catalog"): what demo-api/fixtures/approved/listItems.json approves. +for (const seed of [ + { id: '00000000-0000-4000-8000-000000000001', name: 'Catalog hammer', price: 12.5, tags: ['catalog'] }, + { id: '00000000-0000-4000-8000-000000000002', name: 'Catalog screwdriver', price: 4.25, tags: ['catalog'] }, +]) items.set(seed.id, { ...seed, createdAt: new Date().toISOString() }); +let lastCreated: string | undefined; // DEMO_FAULT=hide-created hides it from the list const ADMIN_TOKEN = process.env.DEMO_ADMIN_TOKEN ?? 'demo-admin-token'; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -78,8 +84,28 @@ route('/items', { const raw = url.searchParams.get('limit'); const limit = raw === null ? 20 : Number(raw); if (!Number.isInteger(limit) || limit < 1 || limit > 100) return error(res, 400, 'limit must be an integer 1-100'); - const all = [...items.values()]; - send(res, 200, { items: all.slice(0, limit), total: all.length }); + const rawOffset = url.searchParams.get('offset'); + const offset = rawOffset === null ? 0 : Number(rawOffset); + if (!Number.isInteger(offset) || offset < 0) return error(res, 400, 'offset must be an integer >= 0'); + const sort = url.searchParams.get('sort'); + if (sort !== null && !['name', '-name', 'price', '-price'].includes(sort)) return error(res, 400, 'sort must be name, -name, price or -price'); + const tag = url.searchParams.get('tag'); + if (tag !== null && (tag.length < 1 || tag.length > 30)) return error(res, 400, 'tag must be 1-30 characters'); + // DEMO_FAULT simulates one collection defect at a time (mutation tests: the generated suite must catch each). + const fault = process.env.DEMO_FAULT; + let all = [...items.values()]; + if (tag !== null && fault !== 'ignore-filter') all = all.filter((i) => i.tags.includes(tag)); + if (fault === 'hide-created') all = all.filter((i) => i.id !== lastCreated); + if (sort) { + const key = sort.replace(/^-/, '') as 'name' | 'price'; + const dir = sort.startsWith('-') ? -1 : 1; + all = [...all].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0) * dir * (fault === 'wrong-sort' ? -1 : 1)); + } + if (fault === 'duplicate') all = all.flatMap((i) => [i, i]); + const start = fault === 'bad-pagination' ? Math.max(0, offset - 1) : offset; + let page = all.slice(start, start + limit); + if (fault === 'wrong-field') page = page.map((i) => ({ ...i, price: i.price + 1 })); + send(res, 200, { items: page, total: all.length }); }, POST: async (req, res) => { const body = await readJson(req); @@ -88,6 +114,7 @@ route('/items', { if (typeof v === 'string') return error(res, 400, v); const item: Item = { id: randomUUID(), name: v.name!, price: v.price!, tags: v.tags ?? [], createdAt: new Date().toISOString() }; items.set(item.id, item); + lastCreated = item.id; // DEMO_BREAK=create-price simulates a regression so the agent's CONTRACT_MISMATCH path can be demonstrated. const out = process.env.DEMO_BREAK === 'create-price' ? { ...item, price: String(item.price) } : item; send(res, 201, out, { location: `/items/${item.id}` }); diff --git a/docs/OPENAPI_CHANGE_TRIGGER.md b/docs/OPENAPI_CHANGE_TRIGGER.md index 76c2b1c..cc0523b 100644 --- a/docs/OPENAPI_CHANGE_TRIGGER.md +++ b/docs/OPENAPI_CHANGE_TRIGGER.md @@ -280,6 +280,19 @@ scenario/positive: crud business-rule scenario/negative: business-rule ``` +Later versions only add rules (a registry of an older version stays valid): + +```text +v2 functional/positive: accepted-value request.#// + functional/negative: invalid-credentials request.security + method-not-allowed operation + precondition-failed request.header#/ +v3 functional/positive: collection-contains, fixture operation + filter, pagination request.query#/ + sort request.query#// + unique response.body#/* +``` + This is the architecture's vocabulary. The generator may support only a subset, but it never creates unknown rules. `crud` is only for a general resource lifecycle; `business-rule` covers positive and negative business scenarios, including state transitions. A separate `state-transition` rule may come in a later vocabulary version if `business-rule` proves too broad. `registry validate` checks the allowed **combination** of `suiteType`, `polarity`, `location` and `rule`, not just that the rule exists. Allowed in v1: diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 8cf62b9..68b8787 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -125,10 +125,70 @@ CRUD flows come from confirmed dependencies (OpenAPI links or the deps file). Bu | create → duplicate create → 409 | ✅ | deps `conflictOn` | 6 ✔ | | update / delete unknown resource → 404 | ✅ | functional `not-found` cases | | | business flows (login → request, parent → child, state transitions, negative transitions, idempotency key, …) | ✅ | reviewed scenarios file; strict validation: operations exist, parameters exist, every non-cleanup step names a documented status, every `{var}` is saved earlier, a writing scenario has cleanup, the primary is an action, IDs unique | 8 ✔ | -| create → list / search / filter, pagination, sort | 🟡 | as a reviewed business scenario; no automatic derivation (list fields and filters are not in the spec) | 8 ✔ | -| eventual consistency with bounded polling | ❌ | the scenario DSL has no retry / polling step yet | | +| create → list → update → list → delete → list | ✅ | reviewed deps `collection` mapping (see Collections); bounded polling | C ✔ | +| create → list / search / filter, pagination, sort | ✅ | reviewed deps `collection` mapping (see Collections); other list shapes as a reviewed business scenario | C ✔ | +| eventual consistency with bounded polling | 🟡 | collection checks: `consistency.pollTimeoutMs` (≤ 60 s) / `pollIntervalMs`; the scenario DSL has no polling step yet | C ✔ | | refresh token → request | 🟡 | as a reviewed scenario with explicit steps | 8 ✔ | +## Collections (`src/generate/collection*.ts`, `src/fixtures/`) + +A list operation is tested deeply only from a reviewed `collection` mapping in the deps file (next to the resource's CRUD chain). Nothing is inferred from names: every pointer, query parameter, sort value and paging parameter is checked against the spec, and a mismatch is an `INVALID_REVIEWED_CONFIG` gap instead of tests. A GET collection without a mapping gets an `UNCONFIRMED_BUSINESS_RULE` gap; a single resource with an array field is not a collection. + +```json +"collection": { + "operationId": "listItems", "items": "/items", "id": "/id", + "fields": { "/name": "exact", "/price": "tolerance:0.001", "/tags": "exact", "/createdAt": "ignore" }, + "unique": ["/id"], + "filters": [{ "param": "tag", "field": "/tags", "match": "contains" }], + "sorts": [{ "param": "sort", "value": "-price", "field": "/price", "order": "desc" }], + "page": { "style": "offset", "offsetParam": "offset", "limitParam": "limit", "maxPages": 20 }, + "consistency": { "pollTimeoutMs": 5000, "pollIntervalMs": 250 }, + "deletedDisappears": true +} +``` + +Strategy per list operation (recorded in `coverage-gaps.json` → `collection.strategy` / `strategies` / `reasons`): + +| Strategy | When | What it checks | +|---|---|---| +| A · create & verify | confirmed create + delete; an isolating filter whose field can carry a unique marker | the test creates its own records (marker in the filter field), reads only them, removes them in `finally`; non-trivial datasets: 2 records for a filter (one must be left out), 3 with distinct values created out of order for a sort, page size + 1 for paging | +| B · approved fixtures | `--fixtures ` holds `.json` approved by a person | every approved element is listed, each field by policy (`exact`, `tolerance:`, `schema` = present, `ignore`); `exhaustive` = nothing else | +| C · read-only | no confirmed create / cleanup or no isolating filter | the same properties on existing data; a test without enough data is skipped with the reason | +| contract-only | no mapping | schema and status only; the gap says what is missing | + +| Assertion | State | Notes | +|---|---|---| +| created resource is listed (`collection-contains`) with its persisted fields | ✅ | strategy A; field policies | +| filter returns the match and leaves out the non-match, all results match (`filter`) | ✅ | `equals` / `contains`; enum filters with an isolating marker | +| sort order (`sort`) | ✅ | one case per documented sort value; plain comparison (code points / numbers): the API must document that order | +| page size, no duplicates across pages, union holds every record (`pagination`) | ✅ | offset and page/size styles; cursor paging ❌ (not yet) | +| uniqueness (`unique`) | ✅ | | +| approved fixture (`fixture`) | ✅ | strategy B | +| create → list → update → list → delete → list | ✅ | scenario of the list operation; the last step only with `deletedDisappears` | +| bounded polling | ✅ | only with `consistency`; never longer than `pollTimeoutMs` (≤ 60 s); otherwise one read | +| fixture capture / refresh | ✅ | `fixtures capture` writes candidates only; `fixtures refresh --draft-pr` proposes a candidate in one Draft PR per operation; approved files are never written by the agent | + +Defect detection on the demo API (`scripts/mutation-check.ts`, TypeScript and Python identical): + +| Injected defect (`DEMO_FAULT`) | Previous generator (65 tests) | Collection tests | +|---|---|---| +| filter ignored | missed | detected | +| sort reversed | missed | detected | +| created record hidden from the list | missed | detected | +| every record listed twice | missed | detected | +| wrong field value in the list | missed | detected | +| pages overlap (off-by-one offset) | missed | detected | + +## Maintenance (`maintain`, `src/maintain.ts`) + +| Step | State | Notes | +|---|---|---| +| detect changed operations | ✅ | `diff` (oasdiff); without a baseline or the engine the whole suite is regenerated and the summary says so | +| regenerate | ✅ | deterministic: unaffected files keep their bytes; files whose only change is the spec hash in the header are listed separately | +| validate | ✅ | case registry against the head spec, generation manifest; no PR when validation fails | +| Draft PR | ✅ | one bot branch per suite (`api-agent/maintain-`); an open PR is updated, never duplicated; never merged | +| summary | ✅ | changed operations, files and cases added / updated / removed / retired, expectations old → new, fixtures, reviewed configuration that no longer matches, coverage gaps before → after, validation | + ## Valid data (`src/generate/sample.ts`) | Keyword | State | Limits | Stage | @@ -150,7 +210,7 @@ CRUD flows come from confirmed dependencies (OpenAPI links or the deps file). Bu | Item | State | Notes | Stage | |---|---|---|---| | `coverage-gaps.json` | ✅ | summary (operations, generated tests per suite, gaps by code); per operation: gaps with code and location, per-suite generated count and missing code, positive-blocked code, body cases potential / generated / dropped, unchecked statuses (with the reason code), unchecked request media types, unchecked security alternatives | 10 ✔ | -| machine codes | ✅ | `MISSING_VALID_SAMPLE`, `MISSING_RESOURCE_SOURCE`, `MISSING_CLEANUP`, `MISSING_RESPONSE_SCHEMA`, `UNSUPPORTED_SCHEMA_KEYWORD`, `UNSUPPORTED_MEDIA_TYPE`, `UNCONFIRMED_BUSINESS_RULE`, `UNCOVERED_VARIANT`, `CANNOT_ISOLATE_RULE`, `CASE_LIMIT_REACHED`, `UNREACHABLE_RESPONSE_STATUS`, `UNSAFE_LIVE_CHECK`, `DEPRECATED_OPERATION`, `NO_DOCUMENTED_REJECTION` (`src/generate/coverage.ts`) | 10 ✔ | +| machine codes | ✅ | `MISSING_VALID_SAMPLE`, `MISSING_RESOURCE_SOURCE`, `MISSING_CLEANUP`, `MISSING_RESPONSE_SCHEMA`, `UNSUPPORTED_SCHEMA_KEYWORD`, `UNSUPPORTED_MEDIA_TYPE`, `UNCONFIRMED_BUSINESS_RULE`, `UNCOVERED_VARIANT`, `CANNOT_ISOLATE_RULE`, `CASE_LIMIT_REACHED`, `UNREACHABLE_RESPONSE_STATUS`, `UNSAFE_LIVE_CHECK`, `DEPRECATED_OPERATION`, `NO_DOCUMENTED_REJECTION`, `INVALID_REVIEWED_CONFIG` (`src/generate/coverage.ts`) | 10 ✔ | | unique case ID per physical test | ✅ | checked on the real run: Playwright JSON report annotations, pytest collection (`API_AGENT_CASES_OUT`) | 2 ✔ | | cases no longer generated | ✅ | tombstones (`status: retired`), reactivated when generated again | 2 ✔ | | CI: registry and manifest validation | ✅ | `registry validate --spec --require-spec`, `manifest validate`, TypeScript and Python | 2 ✔ | @@ -158,4 +218,6 @@ CRUD flows come from confirmed dependencies (OpenAPI links or the deps file). Bu | CI: TypeScript / Python parity | ✅ | the same active cases for the demo API and for the synthetic fixture | 9 ✔ | | CI: the synthetic fixture compiles | ✅ | `tests/fixtures/coverage/kitchen-sink.yaml` generated in both languages: `tsc`, `py_compile`, valid registry | 6 ✔ | | CI: expected coverage gaps | ✅ | demo API (`demo-api/expected-gaps.json`) in CI; the synthetic fixture in unit tests | 10 ✔ | +| CI: fault injection | ✅ | `scripts/mutation-check.ts`: the demo list suite must be clean without a fault and fail under each of 6 `DEMO_FAULT` modes, TypeScript and Python | C ✔ | +| CI: maintenance | ✅ | `maintain` on a changed demo spec: regenerated, validated, the stale reviewed mapping reported | C ✔ | | README | ✅ | "What is covered, and what is not": spec-derived vs needs confirmation vs never generated | 10 ✔ | diff --git a/scripts/mutation-check.ts b/scripts/mutation-check.ts new file mode 100644 index 0000000..43ace71 --- /dev/null +++ b/scripts/mutation-check.ts @@ -0,0 +1,85 @@ +/** + * Fault injection for the generated collection tests (docs/SUPPORT_MATRIX.md, "Defect detection"). + * + * Starts the demo API once per fault mode (DEMO_FAULT) on its own port and runs the given generated test files: + * without a fault every test must pass; with each fault at least one test must fail. A fault no test catches is a + * hole in the generator, and the script exits 1. + * + * npx tsx scripts/mutation-check.ts --lang typescript tests/api/items/get + * npx tsx scripts/mutation-check.ts --lang python tests/api-python/items/get + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, rmSync, writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { findPython } from '../src/generate/generate.js'; + +export const FAULTS = ['ignore-filter', 'wrong-sort', 'hide-created', 'duplicate', 'wrong-field', 'bad-pagination'] as const; + +const args = process.argv.slice(2); +const lang = args.includes('--lang') ? args[args.indexOf('--lang') + 1] : 'typescript'; +const targets = args.filter((a, i) => !a.startsWith('--') && args[i - 1] !== '--lang' && args[i - 1] !== '--port'); +const basePort = Number(args.includes('--port') ? args[args.indexOf('--port') + 1] : 3200); +if (!targets.length) { + console.error('usage: mutation-check.ts [--lang typescript|python] [--port 3200] ...'); + process.exit(2); +} + +async function waitHealthy(url: string): Promise { + for (let i = 0; i < 100; i++) { + try { + if ((await fetch(url + '/health')).ok) return; + } catch { + /* not up yet */ + } + await new Promise((r) => setTimeout(r, 200)); + } + throw new Error(`demo API at ${url} did not start`); +} + +function runTests(baseUrl: string): { passed: number; failed: number; skipped: number; output: string } { + const env = { ...process.env, API_BASE_URL: baseUrl }; + if (lang === 'python') { + const r = spawnSync(findPython(), ['-m', 'pytest', '-q', '-p', 'no:cacheprovider', ...targets], { env, encoding: 'utf8' }); + const out = (r.stdout ?? '') + (r.stderr ?? ''); + const n = (word: string) => Number(out.match(new RegExp(`(\\d+) ${word}`))?.[1] ?? 0); + return { passed: n('passed'), failed: n('failed') + n('error'), skipped: n('skipped'), output: out }; + } + const config = resolve('.mutation.playwright.config.mjs'); + writeFileSync(config, `export default { testDir: '.', testMatch: ${JSON.stringify(targets.map((t) => resolve(t).replace(/\\/g, '/') + (t.endsWith('.ts') ? '' : '/**/*.spec.ts')))}, retries: 0, workers: 4, use: { baseURL: ${JSON.stringify(baseUrl + '/')}, extraHTTPHeaders: { accept: 'application/json' } } };\n`); + try { + const r = spawnSync(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['playwright', 'test', '--config', config, '--reporter=json'], { env, encoding: 'utf8', shell: process.platform === 'win32', maxBuffer: 64 * 1024 * 1024 }); + const report = JSON.parse(r.stdout.slice(r.stdout.indexOf('{'))); + const s = report.stats ?? {}; + return { passed: s.expected ?? 0, failed: (s.unexpected ?? 0) + (s.flaky ?? 0), skipped: s.skipped ?? 0, output: r.stderr }; + } finally { + rmSync(config, { force: true }); + } +} + +async function withServer(fault: string, port: number, fn: (url: string) => T): Promise { + const env = { ...process.env, PORT: String(port), ...(fault ? { DEMO_FAULT: fault } : {}) }; + delete (env as any)[fault ? '' : 'DEMO_FAULT']; + const child = spawn(process.execPath, ['--import', 'tsx', 'demo-api/server.ts'], { env, stdio: 'ignore' }); + const url = `http://localhost:${port}`; + try { + await waitHealthy(url); + return fn(url); + } finally { + child.kill(); + } +} + +const rows: { fault: string; passed: number; failed: number; skipped: number; ok: boolean }[] = []; +for (const [i, fault] of ['', ...FAULTS].entries()) { + const r = await withServer(fault, basePort + i, runTests); + const ok = fault ? r.failed > 0 : r.failed === 0 && r.passed > 0; + rows.push({ fault: fault || '(none)', passed: r.passed, failed: r.failed, skipped: r.skipped, ok }); + if (!fault && !ok) console.error(r.output.slice(-4000)); +} +console.log(`\nFault injection (${lang}): ${targets.join(', ')}`); +console.log('fault passed failed skipped verdict'); +for (const r of rows) console.log(`${r.fault.padEnd(16)} ${String(r.passed).padStart(6)} ${String(r.failed).padStart(6)} ${String(r.skipped).padStart(7)} ${r.fault === '(none)' ? (r.ok ? 'clean' : 'FAILS WITHOUT A FAULT') : r.ok ? 'detected' : 'MISSED'}`); +const detected = rows.filter((r) => r.fault !== '(none)' && r.ok).length; +console.log(`detected ${detected}/${FAULTS.length} injected defects`); +if (existsSync('reports')) writeFileSync(`reports/mutation-${lang}.json`, JSON.stringify({ lang, targets, rows, detected, injected: FAULTS.length }, null, 2) + '\n'); +process.exit(rows.every((r) => r.ok) ? 0 : 1); diff --git a/src/cases/assign.ts b/src/cases/assign.ts index f02ef0d..661dcfb 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -4,6 +4,8 @@ import type { NegCase } from '../generate/negative.js'; import { bodyPointer, caseId, location, scenarioUid, type CaseParts, type Phase, type ScenarioStep } from './ids.js'; import type { ErrorPlan } from '../generate/error-cases.js'; import type { ResolvedScenario } from '../scenarios/dsl.js'; +import type { CollectionPlan } from '../generate/collection-tests.js'; +import { ARRAY } from './ids.js'; /** * Case IDs of the tests the generator writes for one operation (docs/OPENAPI_CHANGE_TRIGGER.md, "Stable IDs"). @@ -26,9 +28,9 @@ export interface ScenarioDefinition { export interface SuiteCaseIds { /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ - functional: { success?: string; notFound?: string; unauthorized?: string; variants: string[]; invalidCredentials?: string; methodNotAllowed?: string; preconditionFailed?: string }; + functional: { collection?: string[]; fixture?: string; success?: string; notFound?: string; unauthorized?: string; variants: string[]; invalidCredentials?: string; methodNotAllowed?: string; preconditionFailed?: string }; contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[]; unsupportedMediaType?: string }; - scenario: { createRead?: string; updateRead?: string; deleteGone?: string; conflict?: string; deleteTwice?: string; business: string[] }; + scenario: { lifecycle?: string; createRead?: string; updateRead?: string; deleteGone?: string; conflict?: string; deleteTwice?: string; business: string[] }; /** Every case of this operation, by suite, with metadata for cases.json. */ records: Record<'functional' | 'contract' | 'scenario', CaseRecord[]>; scenarios: Record; @@ -51,6 +53,11 @@ export interface AssignInput { errors?: ErrorPlan; /** Documented query values the suite sends one by one (functional positive), each its own physical test. */ queryVariants?: { name: string; value: string | number | boolean }[]; + /** Deep collection tests of a list operation (one case each) and its list lifecycle. */ + collection?: CollectionPlan; + collectionChain?: CrudChain; + /** An approved fixture is compared (strategy B). */ + fixture?: boolean; } export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): SuiteCaseIds { @@ -142,6 +149,33 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): if (s.scenarios.updateRead) ids.scenario.updateRead = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion'), ...step(chain.delete, 'cleanup')]); if (s.scenarios.deleteGone) ids.scenario.deleteGone = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion')]); } + // Collection tests (functional/positive) and the list lifecycle (scenario/positive). + const cp = s.collection; + if (cp) { + const segs = (ptr: string) => ptr.split('/').slice(1).map((x) => x.replace(/~1/g, '/').replace(/~0/g, '~')); + const pageParam = cp.c.page?.style === 'offset' ? cp.c.page.offsetParam : cp.c.page?.style === 'page' ? cp.c.page.pageParam : ''; + ids.functional.collection = cp.tests.map((t) => { + const where = + t.kind === 'listed' ? { location: location.operation(), rule: 'collection-contains' } + : t.kind === 'filter' ? { location: location.query(t.filter!.param), rule: 'filter' } + : t.kind === 'sort' ? { location: location.paramValue('query', t.sort!.param, t.sort!.value), rule: 'sort' } + : t.kind === 'pagination' ? { location: location.query(pageParam), rule: 'pagination' } + : { location: location.responseBody(bodyPointer([...segs(cp.c.items), ARRAY, ...segs(t.unique!)])), rule: 'unique' }; + return add('functional', { subjectUid: uid, polarity: 'positive', ...where }); + }); + const ch = s.collectionChain; + if (cp.lifecycle && ch?.update && ch.delete) { + const steps: ScenarioStep[] = [ + { operationUid: uidOf(ch.create), phase: 'setup' }, { operationUid: uid, phase: 'assertion' }, + { operationUid: uidOf(ch.update), phase: 'action' }, { operationUid: uid, phase: 'assertion' }, + { operationUid: uidOf(ch.delete), phase: 'action' }, { operationUid: uid, phase: 'assertion' }, + ]; + const sUid = scenarioUid('crud', steps); + scenarios[sUid] = { scenarioType: 'crud', primaryOperationUid: uid, steps, roles: { create: uidOf(ch.create), read: uid, update: uidOf(ch.update), delete: uidOf(ch.delete) } }; + ids.scenario.lifecycle = add('scenario', { subjectUid: sUid, polarity: 'positive', location: location.lifecycle(), rule: 'crud' }, { relatedOperationUids: [uidOf(ch.create), uidOf(ch.update), uidOf(ch.delete)] }); + } + } + if (s.fixture) ids.functional.fixture = add('functional', { subjectUid: uid, polarity: 'positive', location: location.operation(), rule: 'fixture' }); // Reviewed business scenarios: identity from the external ID (never from the title or the steps). for (const sc of s.business ?? []) { const steps = sc.steps.map((st) => ({ operationUid: uidOf(st.op), phase: st.phase })); diff --git a/src/cases/ids.ts b/src/cases/ids.ts index 81c65d8..47753d1 100644 --- a/src/cases/ids.ts +++ b/src/cases/ids.ts @@ -12,9 +12,12 @@ export type Polarity = 'positive' | 'negative'; /** * v2 adds functional/positive `accepted-value` (one case per documented parameter value) and functional/negative - * `invalid-credentials`, `method-not-allowed`, `precondition-failed`. Registries of v1 stay readable. + * `invalid-credentials`, `method-not-allowed`, `precondition-failed`. + * v3 adds functional/positive collection rules: `collection-contains`, `unique`, `fixture` (on "operation" / + * response.body), `filter`, `pagination` (on the query parameter), `sort` (request.query#//). + * Registries of older versions stay readable. */ -export const CASE_RULE_VOCABULARY_VERSION = 2; +export const CASE_RULE_VOCABULARY_VERSION = 3; const CONSTRAINT_RULES = [ 'required', 'nullable', 'type', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', @@ -23,7 +26,7 @@ const CONSTRAINT_RULES = [ /** Built-in vocabulary v1, by suiteType/polarity. */ export const VOCABULARY_V1: Record = { - 'functional/positive': ['documented-success', 'accepted-value'], + 'functional/positive': ['documented-success', 'accepted-value', 'collection-contains', 'filter', 'sort', 'pagination', 'unique', 'fixture'], 'functional/negative': ['not-found', 'unauthorized', 'forbidden', 'invalid-credentials', 'method-not-allowed', 'precondition-failed'], 'contract/positive': ['documented', 'schema'], 'contract/negative': [...CONSTRAINT_RULES, 'content-type'], @@ -119,6 +122,10 @@ export function checkCombination(p: CaseParts): CaseIdError | undefined { const subject = (why: string): CaseIdError => ({ code: 'INVALID_CASE_SUBJECT', reason: why }); switch (`${p.suiteType}/${p.polarity}`) { case 'functional/positive': + if (p.rule === 'collection-contains' || p.rule === 'fixture') return loc === 'operation' ? undefined : bad(`${p.rule} is checked on "operation"`); + if (p.rule === 'unique') return loc.startsWith('response.body#') ? undefined : bad('unique names a response body field'); + if (p.rule === 'filter' || p.rule === 'pagination') return /^request\.query#\/[^/]*$/.test(loc) ? undefined : bad(`${p.rule} names a query parameter`); + if (p.rule === 'sort') return /^request\.query#\/[^/]*\/[^/]*$/.test(loc) ? undefined : bad('sort names a query parameter and its value'); if (p.rule === 'accepted-value') return /^request\.(query|path|header|cookie)#\/[^/]*\/[^/]*$/.test(loc) ? undefined : bad('accepted-value names a parameter and its value: request.#//'); return loc === 'operation' ? undefined : bad(`documented-success is checked on "operation", not "${loc}"`); case 'functional/negative': diff --git a/src/cases/validate.ts b/src/cases/validate.ts index ec1aedb..a0d5db9 100644 --- a/src/cases/validate.ts +++ b/src/cases/validate.ts @@ -201,7 +201,7 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine const allowed = Array.isArray(p.schema?.enum) ? p.schema.enum.map(String) : p.schema?.const !== undefined ? [String(p.schema.const)] : boundaryValues(p.schema).map(String); return allowed.includes(value) ? undefined : bad(`"${value}" is not a documented value or valid limit of ${m[1]} "${name}"`); } - if (rule !== 'required' && rule !== 'not-found' && !ruleFits(p.schema, rule)) return { code: 'INVALID_CASE_RULE_FOR_SCHEMA', pointer: '', reason: `${o.key}: "${rule}" does not apply to ${m[1]} "${name}"` }; + if (!['required', 'not-found', 'filter', 'pagination'].includes(rule) && !ruleFits(p.schema, rule)) return { code: 'INVALID_CASE_RULE_FOR_SCHEMA', pointer: '', reason: `${o.key}: "${rule}" does not apply to ${m[1]} "${name}"` }; return undefined; } const status = loc.match(/^response\.status#\/(.+)$/); @@ -231,7 +231,7 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine last = r.error.code === 'CASE_LOCATION_UNRESOLVED' ? r.error : { ...r.error, reason: `${o.key}: ${r.error.reason}` }; continue; } - if (!['schema', 'type', 'required', 'nullable', 'enum', 'const'].includes(rule) && !ruleFits(r.node, rule)) { + if (!['schema', 'type', 'required', 'nullable', 'enum', 'const', 'unique'].includes(rule) && !ruleFits(r.node, rule)) { last = { code: 'INVALID_CASE_RULE_FOR_SCHEMA', pointer: '', reason: `${o.key}: "${rule}" does not apply to ${body[1]} body ${body[2] || '(root)'}` }; continue; } diff --git a/src/cli.ts b/src/cli.ts index 0f670ee..dd65385 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -30,6 +30,10 @@ import { accountNotice, ACCOUNT_MODES, checkRegisterConfig, missingLoginVars, pa import { AiRunner, describeAiError, RUNNERS, type RunnerKind } from './ai/runner.js'; import { proposeDependencies } from './ai/dependencies.js'; import { analyzeProject } from './discover/analyze.js'; +import { loadApproved, type LoadedFixture } from './fixtures/fixtures.js'; +import { candidateSummary, captureFixture } from './fixtures/capture.js'; +import { maintain } from './maintain.js'; +import { upsertDraftPr } from './pr.js'; const VERSION = '0.1.3'; const log = (m: string) => process.stderr.write(m + '\n'); @@ -218,6 +222,7 @@ common(program.command('generate').description('audit, then generate Playwright .option('--tests-dir ', 'where generated tests are written (default: API_TESTS_DIR or tests/api)') .option('--deps ', 'JSON file with human-confirmed dependencies') .option('--scenarios ', 'reviewed business scenarios (schemas/scenarios.schema.json); validated against the spec') + .option('--fixtures ', 'approved fixtures (strategy B): /.json, compared field by field by policy') .option('--max-cases ', 'request-body negative cases per operation; the rest is reported as CASE_LIMIT_REACHED', '60') .addOption(new Option('--lang ', 'language of generated tests (default: API_TESTS_LANG or typescript)').choices(['typescript', 'python'])) .option('--run', 'run the generated tests once against --base-url (needs --allow-write)', false) @@ -226,7 +231,7 @@ common(program.command('generate').description('audit, then generate Playwright .addOption(new Option('--ai-runner ', 'console tool: claude, codex, or command (API_AI_COMMAND). Default: API_AI or claude').choices(RUNNERS)) .option('--ai-max-calls ', 'AI call budget per run', '10') .option('--ai-model ', 'model name passed to the console tool (default: its own default)') - .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; maxCases: string; scenarios?: string; aiModel?: string; aiRunner?: RunnerKind }) => { + .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; maxCases: string; scenarios?: string; aiModel?: string; aiRunner?: RunnerKind; fixtures?: string }) => { const location = await resolveInputs(specArg, o); o.testsDir ??= cfg.testsDir; o.lang ??= cfg.testsLang; @@ -249,7 +254,8 @@ common(program.command('generate').description('audit, then generate Playwright scenarios = checked.scenarios; log(`Scenarios: ${scenarios.length} reviewed business scenario(s) from ${o.scenarios}`); } - const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases, scenarios }); + const fx = o.fixtures ? await approvedFixtures(o.fixtures, r.spec, r.ops) : undefined; + const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases, scenarios, ...(fx ?? {}) }); for (const s of gen.scenarios) log(` ${s.status.padEnd(9)} ${s.name}`); for (const f of gen.removed) log(` REMOVED ${relative(process.cwd(), f).replace(/\\/g, '/')} (generated earlier, no longer produced)`); if (o.run) { @@ -547,6 +553,107 @@ async function aiProposals(doc: any, ops: Operation[], outDir: string, opts: { m log(` ${advisor.summary()}`); } +/** Approved fixtures of a directory; invalid ones are logged and become INVALID_REVIEWED_CONFIG gaps. */ +async function approvedFixtures(dir: string, spec: LoadedSpec, ops: Operation[]): Promise<{ fixtures: LoadedFixture[]; fixtureErrors: { file: string; operationId?: string; errors: string[] }[] }> { + const r = await loadApproved(dir, spec.doc, ops); + log(`Fixtures: ${r.fixtures.length} approved fixture(s) from ${dir}${r.errors.length ? `, ${r.errors.length} invalid (not used)` : ''}`); + for (const e of r.errors) log(` INVALID ${e.file}: ${e.errors.join('; ')}`); + return { fixtures: r.fixtures, fixtureErrors: r.errors }; +} + +async function reviewedInputs(o: { deps?: string; scenarios?: string; fixtures?: string }, spec: LoadedSpec, ops: Operation[]) { + const deps = o.deps ? JSON.parse(await readFile(o.deps, 'utf8')) : undefined; + let scenarios: ResolvedScenario[] | undefined; + if (o.scenarios) { + const checked = validateScenarios(JSON.parse(await readFile(o.scenarios, 'utf8')), ops); + if (checked.errors.length) throw new Error(`${o.scenarios} is invalid:\n${checked.errors.map((e) => ` ${e.pointer || '(root)'}: ${e.reason}`).join('\n')}`); + scenarios = checked.scenarios; + } + const fx = o.fixtures ? await approvedFixtures(o.fixtures, spec, ops) : {}; + return { deps, scenarios, ...fx }; +} + +program + .command('maintain') + .description('after a spec change: diff, regenerate (deterministic), validate, then one Draft PR per suite with a summary; never merges') + .argument('[spec]', 'the new OpenAPI spec (default: API_SPEC_URL)') + .option('--base ', 'the old spec; default: the spec at the Git merge base') + .option('--tests-dir ', 'generated suite', cfg.testsDir) + .addOption(new Option('--lang ', 'language of the suite').choices(['typescript', 'python'])) + .option('--deps ', 'reviewed dependencies') + .option('--scenarios ', 'reviewed business scenarios') + .option('--fixtures ', 'approved fixtures') + .option('--max-cases ', 'request-body negative cases per operation', '60') + .option('-o, --out ', 'report directory', 'reports/api-agent/maintain') + .option('--draft-pr', 'commit to the bot branch and open or update its Draft PR (gh)', false) + .option('--allow-network', 'allow URL specs', false) + .action(async (specArg: string | undefined, o: { base?: string; testsDir: string; lang?: 'typescript' | 'python'; deps?: string; scenarios?: string; fixtures?: string; maxCases: string; out: string; draftPr: boolean; allowNetwork: boolean }) => { + const location = specArg ?? (await findSpec(cfg, log)); + if (!location) throw new Error('No spec found: pass it as an argument or set API_SPEC_URL.'); + const { spec, ops } = await load(location); + const inputs = await reviewedInputs(o, spec, ops); + const r = await maintain({ + location, spec, ops, testsDir: o.testsDir, base: o.base, out: o.out, draftPr: o.draftPr, allowNetwork: o.allowNetwork, log, + generate: { version: VERSION, lang: o.lang ?? cfg.testsLang, maxCases: Number(o.maxCases), ...inputs }, + }); + log(`Summary: ${r.summaryFile}`); + if (!r.valid) process.exitCode = 1; + }); + +const fixturesCmd = program.command('fixtures').description('approved fixtures (strategy B): capture candidates, propose refreshes for review'); +const captureOptions = (c: Command) => + c + .argument('[spec]', 'OpenAPI spec (default: API_SPEC_URL)') + .requiredOption('--operation ', 'the GET list operation to capture') + .option('-u, --base-url ', 'TEST environment to read from (default: API_BASE_URL)') + .option('--query ', 'query parameter of the read (repeatable)', collect, []) + .option('--items ', 'JSON pointer to the array in the response') + .option('--id ', 'field that identifies an element, e.g. /id') + .option('--deps ', 'reviewed deps file: its "collection" mapping supplies items / id / policies / paging') + .option('--approved ', 'approved fixtures (read only)', 'fixtures/approved') + .option('--candidates ', 'where candidates are written', 'fixtures/candidates'); +type CaptureCli = { operation: string; baseUrl?: string; query: string[]; items?: string; id?: string; deps?: string; approved: string; candidates: string }; +async function capture(specArg: string | undefined, o: CaptureCli) { + const location = specArg ?? (await findSpec(cfg, log)); + if (!location) throw new Error('No spec found: pass it as an argument or set API_SPEC_URL.'); + const baseUrl = o.baseUrl ?? cfg.baseUrl; + if (!baseUrl) throw new Error('Pass --base-url (a TEST environment) or set API_BASE_URL.'); + const { spec, ops } = await load(location); + const deps = o.deps ? JSON.parse(await readFile(o.deps, 'utf8')) : undefined; + const r = await captureFixture({ + doc: spec.doc, ops, baseUrl, operationId: o.operation, approvedDir: o.approved, candidatesDir: o.candidates, + query: Object.fromEntries(o.query.map((q) => [q.split('=')[0], q.split('=').slice(1).join('=')])), + ...(o.items !== undefined ? { items: o.items } : {}), + ...(o.id ? { id: o.id } : {}), + collections: (deps?.scenarios ?? []).map((s: any) => s.collection).filter(Boolean), + headers: process.env.API_TOKEN ? { authorization: `Bearer ${process.env.API_TOKEN}` } : {}, + }); + log(`Candidate: ${r.candidateFile} (${r.candidate.expected.length} element(s)); approved fixtures are never written.`); + if (r.diff) log(`Against ${r.approvedFile}: added ${r.diff.added.length}, removed ${r.diff.removed.length}, fields changed ${r.diff.changed.length}`); + return r; +} +captureOptions(fixturesCmd.command('capture').description('read a collection from a test environment and write a CANDIDATE fixture (never an approved one)')).action(async (specArg: string | undefined, o: CaptureCli) => { + await capture(specArg, o); +}); +captureOptions(fixturesCmd.command('refresh').description('capture a candidate and, when it differs from the approved fixture, propose it in a Draft PR (one per operation)')) + .option('--draft-pr', 'commit the candidate to the bot branch and open or update its Draft PR (gh)', false) + .option('-o, --out ', 'report directory', 'reports/api-agent/fixtures') + .action(async (specArg: string | undefined, o: CaptureCli & { draftPr: boolean; out: string }) => { + const r = await capture(specArg, o); + if (r.diff && !r.diff.added.length && !r.diff.removed.length && !r.diff.changed.length) { + log('The candidate matches the approved fixture under its policies: nothing to refresh.'); + return; + } + await mkdir(o.out, { recursive: true }); + const body = join(o.out, `${o.operation}.md`); + await writeFile(body, candidateSummary(r)); + log(`Review summary: ${body}`); + if (o.draftPr) { + const pr = upsertDraftPr({ branch: `api-agent/fixtures-${o.operation}`, files: [r.candidateFile], title: `test(api): fixture candidate for ${o.operation} (review before approving)`, bodyFile: body, commitMessage: [`test(api): fixture candidate for ${o.operation}`, 'Captured by api-test-agent. The approved fixture is unchanged until a person approves this candidate.'] }); + log(pr ? `Draft PR ${pr.updated ? 'updated' : 'opened'}: ${pr.url}` : 'Nothing new to commit: Draft PR unchanged.'); + } + }); + program.parseAsync().catch((err) => { log(err instanceof UnsupportedSpecError ? `Unsupported spec: ${err.message}` : `Error: ${err?.message ?? err}`); process.exitCode = 2; diff --git a/src/contract/contract.py b/src/contract/contract.py index f3ae422..d5199c5 100644 --- a/src/contract/contract.py +++ b/src/contract/contract.py @@ -71,6 +71,141 @@ def _nullable(node: Any) -> Any: return out +# Collection checks (a reviewed "collection" mapping in the deps file). Same semantics as contract-assert.ts. + + +def items_of(body: Any, pointer: str) -> list: + v = read_pointer(body, pointer) if pointer else body + assert isinstance(v, list), f'collection at "{pointer or "(body)"}" is an array' + return v + + +def _id_of(item: Any, ptr: str) -> str: + v = read_pointer(item, ptr) + return str(v).lower() if isinstance(v, bool) else str(v) + + +def expect_contains(items: list, id_ptr: str, rid: Any, what: str = "resource") -> Any: + found = next((i for i in items if _id_of(i, id_ptr) == str(rid)), None) + assert found is not None, f"{what} {rid} is in the collection" + return found + + +def expect_not_contains(items: list, id_ptr: str, rid: Any, what: str = "resource") -> None: + assert not any(_id_of(i, id_ptr) == str(rid) for i in items), f"{what} {rid} is not in the collection" + + +def expect_fields(item: Any, expected: Any, policies: dict) -> None: + """Fields compare by policy: exact, tolerance:; ignore and schema are not compared here.""" + for ptr, policy in policies.items(): + if policy in ("ignore", "schema"): + continue + want = read_pointer(expected, ptr) + if want is None: + continue + got = read_pointer(item, ptr) + if policy.startswith("tolerance:"): + t = float(policy[len("tolerance:"):]) + assert abs(float(got) - float(want)) <= t, f"{ptr} within {t} of {want} (got {got})" + else: + assert got == want, f"{ptr} as sent: expected {want!r}, got {got!r}" + + +def expect_all_match(items: list, ptr: str, match: str, value: Any) -> None: + def ok(i: Any) -> bool: + v = read_pointer(i, ptr) + if match == "contains": + return isinstance(v, list) and str(value) in [str(x) for x in v] + return str(v) == str(value) + + bad = [i for i in items if not ok(i)] + assert not bad, f"{len(bad)} element(s) do not match {ptr} {match} {value}" + + +def expect_unique_by(items: list, ptr: str) -> None: + seen, dups = set(), [] + for i in items: + k = _id_of(i, ptr) + if k in seen: + dups.append(k) + seen.add(k) + assert not dups, f"duplicates by {ptr}: {dups}" + + +def expect_sorted_by(items: list, ptr: str, order: str) -> None: + """Order by plain comparison (code points for strings, numeric for numbers): the API must document this order.""" + for n in range(1, len(items)): + a, b = read_pointer(items[n - 1], ptr), read_pointer(items[n], ptr) + ok = not (b < a) if order == "asc" else not (b > a) + assert ok, f"{ptr} {order} at position {n}: {a} then {b}" + + +def expect_page_size(items: list, limit: int) -> None: + assert len(items) <= limit, f"page size {len(items)} > {limit}" + + +def expect_no_duplicate_across_pages(pages: list, id_ptr: str) -> None: + expect_unique_by([i for p in pages for i in p], id_ptr) + + +def _leaves(v: Any, prefix: str = "") -> list: + if isinstance(v, dict) and v: + return [x for k, item in v.items() for x in _leaves(item, prefix + "/" + _esc(str(k)))] + if isinstance(v, list) and v: + return [x for i, item in enumerate(v) for x in _leaves(item, prefix + "/" + str(i))] + return [prefix] + + +def expect_matches_fixture(items: list, f: dict) -> None: + """Approved fixture (strategy B): every expected element is listed, each field compared by its policy.""" + policies = f.get("policies") or {} + + def policy_of(leaf: str) -> str: + hits = sorted((p for p in policies if leaf == p or leaf.startswith(p + "/")), key=len, reverse=True) + return policies[hits[0]] if hits else f.get("default") or "exact" + + for want in f["expected"]: + rid = read_pointer(want, f["id"]) + got = expect_contains(items, f["id"], rid, "approved fixture element") + for leaf in _leaves(want): + policy = policy_of(leaf) + a, b = read_pointer(got, leaf), read_pointer(want, leaf) + at = f"element {rid} {leaf}" + if policy == "ignore": + continue + if policy == "schema": + assert a is not None, f"{at} is present" + elif policy.startswith("tolerance:"): + t = float(policy[len("tolerance:"):]) + assert abs(float(a) - float(b)) <= t, f"{at} within {t} of {b} (got {a})" + else: + assert a == b, f"{at} as approved: expected {b!r}, got {a!r}" + if f.get("exhaustive"): + assert len(items) == len(f["expected"]), f"the collection holds exactly the approved elements: {len(items)} != {len(f['expected'])}" + + +def poll(fn, done, timeout_ms: int, interval_ms: int): + """Bounded polling for documented eventual consistency: returns the last value; never waits past the timeout.""" + import time + + end = time.monotonic() + timeout_ms / 1000 + v = fn() + while not done(v) and time.monotonic() < end: + time.sleep(interval_ms / 1000) + v = fn() + return v + + +def with_value(payload: Any, ptr: str, value: Any) -> Any: + out = copy.deepcopy(payload) + keys = [k.replace("~1", "/").replace("~0", "~") for k in ptr.split("/")[1:]] + node = out + for k in keys[:-1]: + node = node.setdefault(k, {}) + node[keys[-1]] = value + return out + + def fill_vars(value: Any, saved: dict) -> Any: """Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text.""" import re diff --git a/src/fixtures/capture.ts b/src/fixtures/capture.ts new file mode 100644 index 0000000..f1653a6 --- /dev/null +++ b/src/fixtures/capture.ts @@ -0,0 +1,114 @@ +import { existsSync } from 'node:fs'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import type { OpenApiDoc } from '../spec/loader.js'; +import type { Operation } from '../types.js'; +import { detectItems } from '../generate/collection.js'; +import { requiredRequest } from '../generate/param-cases.js'; +import { diffFixtures, readPointer, validateFixture, type Fixture, type FixtureDiff } from './fixtures.js'; + +/** + * `fixtures capture`: reads a collection (GET only) and writes a CANDIDATE fixture. It never writes the approved + * directory: a candidate is trusted only after a person reviews it and moves it there (`fixtures refresh --draft-pr` + * opens that review). Settings (query, items, id, policies, paging) come from the approved fixture when there is one, + * else from the options and the deps file "collection" mapping. + */ + +export interface CaptureOptions { + doc: OpenApiDoc; + ops: Operation[]; + baseUrl: string; + operationId: string; + approvedDir: string; + candidatesDir: string; + query?: Record; + items?: string; + id?: string; + /** Deps file "collection" entries: items / id / field policies / paging of a reviewed list operation. */ + collections?: { operationId: string; items: string; id: string; fields?: Record; page?: any }[]; + headers?: Record; +} + +export interface CaptureResult { + candidateFile: string; + candidate: Fixture; + approvedFile?: string; + diff?: FixtureDiff; +} + +export async function captureFixture(o: CaptureOptions): Promise { + const op = o.ops.find((x) => x.operationId === o.operationId); + if (!op) throw new Error(`Operation "${o.operationId}" is not in the spec.`); + if (op.method !== 'get') throw new Error(`${op.key} is not a GET: capture only reads data.`); + const approvedFile = join(o.approvedDir, `${o.operationId}.json`); + const approved: Fixture | undefined = existsSync(approvedFile) ? JSON.parse(await readFile(approvedFile, 'utf8')) : undefined; + const coll = o.collections?.find((c) => c.operationId === o.operationId); + const items = approved?.items ?? o.items ?? coll?.items ?? detectItems(o.doc, op); + const id = approved?.id ?? o.id ?? coll?.id; + if (items === undefined) throw new Error(`Cannot tell where the array is in the ${op.key} response: pass --items .`); + if (!id) throw new Error(`Which field identifies an element? Pass --id (e.g. /id).`); + const page = approved?.page ?? (coll?.page ? { ...coll.page } : undefined); + const query = { ...(approved?.query ?? {}), ...(o.query ?? {}) }; + const policies = approved?.policies ?? Object.fromEntries(Object.entries(coll?.fields ?? {}).filter(([, p]) => p !== 'exact')); + + const expected: unknown[] = []; + const size = page?.size ?? 50; + const maxPages = Math.min(page?.maxPages ?? 20, 50); + const url = (i: number) => { + const u = new URL(op.path.replace(/^\//, ''), o.baseUrl.replace(/\/?$/, '/')); + for (const [k, v] of Object.entries({ ...requiredRequest(op).params, ...query })) u.searchParams.set(k, String(v)); + if (page?.style === 'offset') { + u.searchParams.set(page.offsetParam, String(i * size)); + u.searchParams.set(page.limitParam, String(size)); + } else if (page?.style === 'page') { + u.searchParams.set(page.pageParam, String(i + (page.firstPage ?? 1))); + u.searchParams.set(page.sizeParam, String(size)); + } + return u; + }; + if (/\{/.test(op.path)) throw new Error(`${op.key} has path parameters: capture reads collections without them.`); + for (let i = 0; i < (page ? maxPages : 1); i++) { + const res = await fetch(url(i), { headers: { accept: 'application/json', ...(o.headers ?? {}) } }); + if (!res.ok) throw new Error(`${op.key} answered ${res.status}: nothing captured.`); + const body = await res.json(); + const arr = items ? readPointer(body, items) : body; + if (!Array.isArray(arr)) throw new Error(`${op.key}: no array at "${items}".`); + expected.push(...arr); + if (!page || arr.length < size) break; + } + const candidate: Fixture = { + schemaVersion: 1, + operationId: o.operationId, + ...(Object.keys(query).length ? { query } : {}), + items, + id, + ...(Object.keys(policies).length ? { policies } : {}), + default: approved?.default ?? 'exact', + exhaustive: approved?.exhaustive ?? false, + ...(page ? { page } : {}), + expected, + captured: { at: new Date().toISOString(), from: new URL(o.baseUrl).host }, + }; + const v = validateFixture(o.doc, o.ops, candidate); + if (v.errors.length) throw new Error(`The captured candidate is not a valid fixture:\n ${v.errors.join('\n ')}`); + await mkdir(o.candidatesDir, { recursive: true }); + const candidateFile = join(o.candidatesDir, `${o.operationId}.json`); + await writeFile(candidateFile, JSON.stringify(candidate, null, 2) + '\n'); + return { candidateFile, candidate, ...(approved ? { approvedFile, diff: diffFixtures(approved, candidate) } : {}) }; +} + +/** Markdown summary of a candidate for review (Draft PR body). */ +export function candidateSummary(r: CaptureResult): string { + const L = [`## Fixture candidate: ${r.candidate.operationId}`, '', `Captured ${r.candidate.captured?.at} from ${r.candidate.captured?.from}: ${r.candidate.expected.length} element(s).`, '']; + if (!r.diff) L.push(`No approved fixture yet. Review the data, then move \`${r.candidateFile.replace(/\\/g, '/')}\` to \`fixtures/approved/\` in this PR to approve it.`); + else { + L.push(`Compared with the approved \`${r.approvedFile!.replace(/\\/g, '/')}\` under its policies:`, ''); + L.push(`- elements added: ${r.diff.added.length}${r.diff.added.length ? ` (${r.diff.added.slice(0, 10).join(', ')})` : ''}`); + L.push(`- elements removed: ${r.diff.removed.length}${r.diff.removed.length ? ` (${r.diff.removed.slice(0, 10).join(', ')})` : ''}`); + L.push(`- fields changed: ${r.diff.changed.length}`); + for (const c of r.diff.changed.slice(0, 20)) L.push(` - ${c.id} ${c.pointer}: ${JSON.stringify(c.before)} → ${JSON.stringify(c.after)}`); + L.push('', 'The approved fixture is unchanged. If the new data is correct, replace the approved file with the candidate in this PR; if not, the API changed in a way the tests should report.'); + } + L.push('', 'Never merge a fixture refresh without reading it: approving wrong data turns a defect into an expectation.'); + return L.join('\n') + '\n'; +} diff --git a/src/fixtures/fixtures.ts b/src/fixtures/fixtures.ts new file mode 100644 index 0000000..1d89aad --- /dev/null +++ b/src/fixtures/fixtures.ts @@ -0,0 +1,161 @@ +import { existsSync } from 'node:fs'; +import { readdir, readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import type { OpenApiDoc } from '../spec/loader.js'; +import type { Operation } from '../types.js'; +import { resolvePointer } from '../spec/loader.js'; +import { schemaAt } from '../generate/collection.js'; + +/** + * Strategy B: approved fixtures. A fixture is data a human approved as the expected content of a collection + * (e.g. reference data that tests must not create). The generator only reads approved fixtures; capture writes + * candidates to a separate directory, and a candidate becomes approved only when a person moves it (Draft PR). + * + * fixtures/approved/.json: + * { + * "schemaVersion": 1, + * "operationId": "listCategories", + * "query": { "tag": "seed" }, request parameters of the read (documented query parameters) + * "items": "/data", JSON pointer to the array ("" = the body is the array) + * "id": "/id", element field that identifies an expected element + * "policies": { "/updatedAt": "ignore", "/price": "tolerance:0.01", "/slug": "schema" }, + * "default": "exact", policy of every other field: exact | schema | ignore + * "exhaustive": false, true: the collection holds exactly these elements + * "page": { "style": "offset", "offsetParam": "offset", "limitParam": "limit", "size": 50, "maxPages": 20 }, + * "expected": [ { "id": 1, "name": "Hand tools" } ] + * } + * Policies: exact (equal), tolerance: (numbers within n), schema (present; its shape is the contract suite's job), + * ignore (not compared). + */ + +export interface Fixture { + schemaVersion: 1; + operationId: string; + query?: Record; + items: string; + id: string; + policies?: Record; + default?: 'exact' | 'schema' | 'ignore'; + exhaustive?: boolean; + page?: { style: 'offset'; offsetParam: string; limitParam: string; size?: number; maxPages?: number } | { style: 'page'; pageParam: string; sizeParam: string; firstPage?: number; size?: number; maxPages?: number }; + expected: unknown[]; + /** Capture metadata (candidates only; kept when a candidate is approved). */ + captured?: { at: string; from: string }; +} + +export interface LoadedFixture { + file: string; + fixture: Fixture; + op: Operation; +} + +const POLICY = /^(exact|schema|ignore|tolerance:\d+(\.\d+)?)$/; + +export function validateFixture(doc: OpenApiDoc, ops: Operation[], f: Fixture): { op?: Operation; errors: string[] } { + const errors: string[] = []; + if (f?.schemaVersion !== 1) errors.push('schemaVersion must be 1'); + const op = ops.find((o) => o.operationId === f?.operationId); + if (!op) return { errors: [...errors, `operation "${f?.operationId}" is not in the spec`] }; + if (op.method !== 'get') errors.push(`${op.key} is not a GET: fixtures describe data that is read, never written`); + const ok = op.responses.find((r) => /^2\d\d$/.test(r.status)); + const schema = ok ? resolvePointer(doc, `/paths/${op.path.replace(/~/g, '~0').replace(/\//g, '~1')}/get/responses/${ok.status}/content/application~1json/schema`).node : undefined; + if (!schema) errors.push(`${op.key} documents no JSON success schema`); + else { + const arr = schemaAt(doc, schema, f.items ?? ''); + if (!arr || !(arr.type === 'array' || arr.items)) errors.push(`"items" ${f.items} is not an array in the ${op.key} response`); + else if (typeof f.id !== 'string' || !f.id.startsWith('/') || !schemaAt(doc, arr.items, f.id)) errors.push(`"id" ${f.id} is not a field of the ${op.key} elements`); + } + for (const [ptr, p] of Object.entries(f.policies ?? {})) if (!POLICY.test(p)) errors.push(`policy "${p}" of ${ptr} is not exact, schema, ignore or tolerance:`); + if (f.default !== undefined && !['exact', 'schema', 'ignore'].includes(f.default)) errors.push('"default" is exact, schema or ignore'); + for (const k of Object.keys(f.query ?? {})) if (!op.params.some((p) => p.in === 'query' && p.name === k)) errors.push(`query "${k}" is not a query parameter of ${op.key}`); + const missing = op.params.filter((p) => p.required && p.in !== 'header' && !(p.in === 'query' && f.query && p.name in f.query) && p.knownValue === undefined); + if (missing.length) errors.push(`${op.key} needs ${missing.map((p) => `${p.in} "${p.name}"`).join(', ')}`); + if (f.page) { + const names = f.page.style === 'offset' ? [f.page.offsetParam, f.page.limitParam] : f.page.style === 'page' ? [f.page.pageParam, f.page.sizeParam] : []; + if (!names.length) errors.push('page style is offset or page'); + for (const n of names) if (!op.params.some((p) => p.in === 'query' && p.name === n)) errors.push(`page parameter "${n}" is not a query parameter of ${op.key}`); + } + if (!Array.isArray(f.expected) || !f.expected.length) errors.push('"expected" is a non-empty array'); + else { + const ids = f.expected.map((e) => JSON.stringify(readPointer(e, f.id))); + if (ids.some((i) => i === undefined)) errors.push(`every expected element has an "id" at ${f.id}`); + if (new Set(ids).size !== ids.length) errors.push(`expected elements repeat an id at ${f.id}`); + } + return errors.length ? { errors } : { op, errors }; +} + +/** Approved fixtures of a directory (/*.json); an invalid one is reported, never used. */ +export async function loadApproved(dir: string, doc: OpenApiDoc, ops: Operation[]): Promise<{ fixtures: LoadedFixture[]; errors: { file: string; operationId?: string; errors: string[] }[] }> { + const fixtures: LoadedFixture[] = []; + const errors: { file: string; operationId?: string; errors: string[] }[] = []; + if (!existsSync(dir)) return { fixtures, errors }; + for (const name of (await readdir(dir)).filter((n) => n.endsWith('.json')).sort()) { + const file = join(dir, name); + let f: Fixture; + try { + f = JSON.parse(await readFile(file, 'utf8')); + } catch (e) { + errors.push({ file, errors: [`not JSON: ${(e as Error).message}`] }); + continue; + } + const v = validateFixture(doc, ops, f); + if (v.op && fixtures.some((x) => x.op === v.op)) errors.push({ file, operationId: f.operationId, errors: [`a second fixture for ${v.op.key}`] }); + else if (v.op) fixtures.push({ file, fixture: f, op: v.op }); + else errors.push({ file, operationId: f?.operationId, errors: v.errors }); + } + return { fixtures, errors }; +} + +export function readPointer(body: unknown, pointer: string): unknown { + return pointer + .split('/') + .slice(1) + .map((p) => p.replace(/~1/g, '/').replace(/~0/g, '~')) + .reduce((node, key) => (node == null ? undefined : node[key]), body); +} + +/** Leaf pointers of a value (objects and arrays walked; scalars and empty containers are leaves). */ +export function leafPointers(v: unknown, prefix = ''): string[] { + if (v && typeof v === 'object' && Object.keys(v).length) { + return Object.entries(v as Record).flatMap(([k, x]) => leafPointers(x, `${prefix}/${k.replace(/~/g, '~0').replace(/\//g, '~1')}`)); + } + return [prefix]; +} + +/** Policy of one leaf: the longest policy pointer that is the leaf or one of its parents, else the default. */ +export function policyOf(f: Pick, leaf: string): string { + const hit = Object.keys(f.policies ?? {}) + .filter((p) => leaf === p || leaf.startsWith(p + '/')) + .sort((a, b) => b.length - a.length)[0]; + return hit ? f.policies![hit] : f.default ?? 'exact'; +} + +export interface FixtureDiff { + added: string[]; + removed: string[]; + changed: { id: string; pointer: string; before: unknown; after: unknown }[]; +} + +/** Differences between an approved fixture and a candidate that its policies would fail on (ignored fields skipped). */ +export function diffFixtures(approved: Fixture, candidate: Fixture): FixtureDiff { + const key = (e: unknown) => JSON.stringify(readPointer(e, approved.id)); + const before = new Map(approved.expected.map((e) => [key(e), e])); + const after = new Map(candidate.expected.map((e) => [key(e), e])); + const out: FixtureDiff = { added: [...after.keys()].filter((k) => !before.has(k)), removed: [...before.keys()].filter((k) => !after.has(k)), changed: [] }; + for (const [id, b] of before) { + const a = after.get(id); + if (a === undefined) continue; + for (const leaf of [...new Set([...leafPointers(b), ...leafPointers(a)])]) { + const policy = policyOf(approved, leaf); + const x = readPointer(b, leaf); + const y = readPointer(a, leaf); + if (policy === 'ignore') continue; + if (policy === 'schema' ? (x === undefined) !== (y === undefined) : policy.startsWith('tolerance:') ? !(Math.abs(Number(x) - Number(y)) <= Number(policy.slice(10))) : JSON.stringify(x) !== JSON.stringify(y)) { + out.changed.push({ id, pointer: leaf, before: x, after: y }); + } + } + } + return out; +} + +export const fixtureDiffIsEmpty = (d: FixtureDiff) => !d.added.length && !d.removed.length && !d.changed.length; diff --git a/src/generate/collection-render.ts b/src/generate/collection-render.ts new file mode 100644 index 0000000..d7993c3 --- /dev/null +++ b/src/generate/collection-render.ts @@ -0,0 +1,598 @@ +import type { Operation } from '../types.js'; +import { apiCall } from './api-objects.js'; +import { requiredRequest } from './param-cases.js'; +import type { CollectionPlan, CollectionTest } from './collection-tests.js'; +import { expectSuccess, hasFill, optionsWith, pathArgs, testOptions, type ChainPlan, type SuiteInput } from './templates.js'; +import type { LoadedFixture } from '../fixtures/fixtures.js'; +import { assertSuccess, pathExpr, pyLit, pyName, pyRequired, resourceModule, withId } from './python.js'; + +/** + * Renders the collection tests of a list operation (src/generate/collection-tests.ts) for Playwright and pytest. + * Same plan, same checks, same order in both languages; one physical test per case ID. + */ + +export interface CollectionInput { + plan: CollectionPlan; + /** The confirmed chain whose create / update / delete the controlled datasets use. */ + chain: ChainPlan; +} + +const js = (v: unknown) => JSON.stringify(v); +const py = (v: unknown) => pyLit(v); +const leaf = (ptr: string) => ptr.slice(1).replace(/~1/g, '/').replace(/~0/g, '~'); + +/** Query parameters of page `i` (an expression) of size `size` (an expression), as object-literal entries. */ +function pageEntries(plan: CollectionPlan, i: string, size: string, q: (s: string) => string): string | undefined { + const p = plan.c.page; + if (p?.style === 'offset') return `${q(p.offsetParam)}: ${i} * ${size}, ${q(p.limitParam)}: ${size}`; + if (p?.style === 'page') return `${q(p.pageParam)}: ${i} + ${p.firstPage ?? 1}, ${q(p.sizeParam)}: ${size}`; + return undefined; +} + +const sortValue = (v: string | number, lang: 'ts' | 'py') => (typeof v === 'string' ? (lang === 'ts' ? `${js(v)} + marker` : `${py(v)} + marker`) : String(v)); +const filterValue = (t: CollectionTest, which: 'a' | 'b', lang: 'ts' | 'py') => { + const fv = t.filterValues!; + if (fv.kind === 'enum') return lang === 'ts' ? js(fv[which]) : py(fv[which]); + return `marker + ${lang === 'ts' ? js('-' + which) : py('-' + which)}`; +}; + +/* ------------------------------------------------------------------ TypeScript */ + +export const tsCollectionImports = (suite: 'functional' | 'scenario') => [ + 'itemsOf', 'expectContains', 'expectFields', 'poll', 'readPointer', 'withValue', + ...(suite === 'functional' ? ['expectNotContains', 'expectAllMatch', 'expectUniqueBy', 'expectSortedBy', 'expectPageSize', 'expectNoDuplicateAcrossPages'] : ['expectNotContains']), +]; + +/** Module-level helpers of a list operation's suite: list one page, walk the pages, poll, isolate. */ +export function tsCollectionPrelude(s: SuiteInput, ci: CollectionInput): string[] { + const { plan, chain } = ci; + const op = s.op; + const ref = s.refs.get(op)!; + const req = requiredRequest(op).params; + const c = plan.c; + const page = pageEntries(plan, 'i', 'size', js); + const L = [ + `import type { Apis } from '../../_support/api/generated/apis.js';`, + '', + `/* Collection checks: the reviewed "collection" mapping of ${op.operationId ?? op.key} in the deps file. */`, + `const ITEMS = ${js(c.items)};`, + `const ID = ${js(c.id)};`, + `/** Fields the API keeps as sent, with their comparison policy (exact, tolerance:, schema, ignore). */`, + `const FIELDS: Record = ${js(c.fields ?? {})};`, + `/** Bounded polling (documented eventual consistency); 0 = one read. */`, + `const POLL = ${js({ timeoutMs: c.consistency?.pollTimeoutMs ?? 0, intervalMs: c.consistency?.pollIntervalMs ?? 100 })};`, + `const MAX_PAGES = ${c.maxPages};`, + `const WALK = ${plan.walkSize};`, + '', + `/** A value no other data has: the records a test creates carry it, so the test reads only its own records. */`, + `const newMarker = () => 'ata-' + Math.random().toString(36).slice(2, 10).padEnd(8, '0');`, + `const fresh = async (${hasFill(chain) ? 'api: Apis' : '_api: Apis'}) => (await resource.newCreatePayload(${hasFill(chain) ? 'api' : ''})) as Record;`, + ]; + if (plan.iso) { + const f = plan.iso; + L.push( + `/** ${f.param} ${f.match} ${f.field}: the isolating filter. */`, + `const isolate = (payload: T, marker: string): T => withValue(payload, ${js(f.field)}, ${f.match === 'contains' ? '[marker]' : 'marker'});`, + `const ISO = (marker: string): Record => ({ ${js(f.param)}: marker });`, + ); + } + L.push( + '', + `async function listPage(api: Apis, params: Record): Promise {`, + ` const res = await ${apiCall(ref, 'api', pathArgs(op, ref), `{ params: { ...${js(req)}, ...params } as Record }`)};`, + ` ${expectSuccess(op)}`, + ` return itemsOf(await res.json(), ITEMS);`, + `}`, + '', + `/** Every page (at most MAX_PAGES) with these parameters${page ? '' : ': the API has no reviewed paging, so the one response'}. */`, + `async function listPages(api: Apis, params: Record, size = WALK): Promise {`, + ...(page + ? [ + ` const pages: unknown[][] = [];`, + ` for (let i = 0; i < MAX_PAGES; i++) {`, + ` const page = await listPage(api, { ...params, ${page} });`, + ` pages.push(page);`, + ` if (page.length < size) break;`, + ` }`, + ` return pages;`, + ] + : [` void size;`, ` return [await listPage(api, params)];`]), + `}`, + '', + `const listAll = async (api: Apis, params: Record) => (await listPages(api, params)).flat();`, + `const has = (...ids: string[]) => (items: unknown[]) => ids.every((id) => items.some((i) => String(readPointer(i, ID)) === id));`, + `const listUntil = (api: Apis, params: Record, done: (items: unknown[]) => boolean) => poll(() => listAll(api, params), done, POLL.timeoutMs, POLL.intervalMs);`, + '', + ); + return L; +} + +/** Records of a controlled test: created in order, all removed in finally (also when a create in between fails). */ +function tsSeeded(title: string, opts: string, payloads: string[], body: string[]): string[] { + return [ + ` test(${js(title)}, ${opts}, async ({ api }) => {`, + ` const marker = newMarker();`, + ` const payloads = [`, + ...payloads.map((p) => ` ${p},`), + ` ];`, + ` const ids: string[] = [];`, + ` try {`, + ` for (const p of payloads) ids.push((await resource.create(api, p)).id);`, + ...body.map((l) => ` ${l}`), + ` } finally {`, + ` for (const id of ids) await resource.remove(api, id);`, + ` }`, + ` });`, + '', + ]; +} + +export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] { + const { plan } = ci; + const L: string[] = []; + const iso = (p: string) => (plan.iso ? `isolate(${p}, marker)` : p); + const isoParams = plan.iso ? 'ISO(marker)' : '{}'; + plan.tests.forEach((t, n) => { + const opts = testOptions('positive', s.ids?.functional.collection?.[n]); + if (t.kind === 'listed') { + L.push(...tsSeeded(t.title, opts, [iso('await fresh(api)')], [ + `const items = await listUntil(api, ${isoParams}, has(ids[0]));`, + `expectFields(expectContains(items, ID, ids[0], 'created resource'), payloads[0], FIELDS);`, + ])); + } else if (t.kind === 'filter' && t.mode === 'controlled') { + const f = t.filter!; + const set = (which: 'a' | 'b') => { + const v = filterValue(t, which, 'ts'); + const p = `withValue(await fresh(api), ${js(f.field)}, ${f.match === 'contains' ? `[${v}]` : v})`; + return t.filterValues!.kind === 'enum' ? iso(p) : p; + }; + const params = t.filterValues!.kind === 'enum' ? `{ ...ISO(marker), ${js(f.param)}: ${filterValue(t, 'a', 'ts')} }` : `{ ${js(f.param)}: ${filterValue(t, 'a', 'ts')} }`; + L.push(...tsSeeded(t.title, opts, [set('a'), set('b')], [ + `const items = await listUntil(api, ${params}, has(ids[0]));`, + `expectContains(items, ID, ids[0], 'resource matching ${f.param}');`, + `expectNotContains(items, ID, ids[1], 'resource not matching ${f.param}');`, + `expectAllMatch(items, ${js(f.field)}, ${js(f.match)}, ${filterValue(t, 'a', 'ts')});`, + ])); + } else if (t.kind === 'filter') { + const f = t.filter!; + L.push( + ` test(${js(t.title)}, ${opts}, async ({ api }) => {`, + ` const all = await listAll(api, {});`, + ` const value = all.flatMap((i) => { const v = readPointer(i, ${js(f.field)}); return ${f.match === 'contains' ? 'Array.isArray(v) ? v : []' : 'v === undefined || v === null ? [] : [v]'}; })[0];`, + ` test.skip(value === undefined, ${js(`no existing resource has a value in ${f.field} to filter by (read-only check)`)});`, + ` const items = await listAll(api, { ${js(f.param)}: value });`, + ` expect(items.length, 'the filter finds the resource the value came from').toBeGreaterThan(0);`, + ` expectAllMatch(items, ${js(f.field)}, ${js(f.match)}, value);`, + ` });`, + '', + ); + } else if (t.kind === 'sort' && t.mode === 'controlled') { + const so = t.sort!; + L.push(...tsSeeded(t.title, opts, t.sortValues!.map((v) => `withValue(isolate(await fresh(api), marker), ${js(so.field)}, ${sortValue(v, 'ts')})`), [ + `const items = await listUntil(api, { ...ISO(marker), ${js(so.param)}: ${js(so.value)} }, has(...ids));`, + `for (const id of ids) expectContains(items, ID, id);`, + `expectSortedBy(items, ${js(so.field)}, ${js(so.order)});`, + ])); + } else if (t.kind === 'sort') { + const so = t.sort!; + L.push( + ` test(${js(t.title)}, ${opts}, async ({ api }) => {`, + ` const items = await listAll(api, { ${js(so.param)}: ${js(so.value)} });`, + ` test.skip(items.length < 2, 'fewer than 2 resources: the order cannot be checked (read-only check)');`, + ` expectSortedBy(items, ${js(so.field)}, ${js(so.order)});`, + ` });`, + '', + ); + } else if (t.kind === 'pagination' && t.mode === 'controlled') { + const ps = plan.pageSize; + L.push(...tsSeeded(t.title, opts, Array.from({ length: ps + 1 }, () => iso('await fresh(api)')), [ + `const pages = await poll(() => listPages(api, ISO(marker), ${ps}), (p) => has(...ids)(p.flat()), POLL.timeoutMs, POLL.intervalMs);`, + `for (const page of pages) expectPageSize(page, ${ps});`, + `expect(pages[0].length, 'the first page is full').toBe(${ps});`, + `expectNoDuplicateAcrossPages(pages, ID);`, + `for (const id of ids) expectContains(pages.flat(), ID, id);`, + ])); + } else if (t.kind === 'pagination') { + const ps = plan.pageSize; + L.push( + ` test(${js(t.title)}, ${opts}, async ({ api }) => {`, + ` const pages = await listPages(api, {}, ${ps});`, + ` test.skip(pages.flat().length <= ${ps}, 'not more than one page of resources (read-only check)');`, + ` for (const page of pages) expectPageSize(page, ${ps});`, + ` expect(pages[0].length, 'the first page is full').toBe(${ps});`, + ` expectNoDuplicateAcrossPages(pages, ID);`, + ` });`, + '', + ); + } else if (t.kind === 'unique' && t.mode === 'controlled') { + L.push(...tsSeeded(t.title, opts, [iso('await fresh(api)'), iso('await fresh(api)')], [ + `const items = await listUntil(api, ISO(marker), has(...ids));`, + `expectUniqueBy(items, ${js(t.unique)});`, + ])); + } else { + L.push(` test(${js(t.title)}, ${opts}, async ({ api }) => {`, ` expectUniqueBy(await listAll(api, {}), ${js(t.unique)});`, ` });`, ''); + } + }); + return L; +} + +/** create → listed with its fields → update → listed with the new values → delete → no longer listed. */ +export function tsLifecycle(s: SuiteInput, ci: CollectionInput): string[] { + const { plan, chain } = ci; + const ch = chain.chain; + const upd = ch.update!; + const del = ch.delete!; + const call = (o: Operation, options?: string) => { + const ref = s.refs.get(o)!; + return apiCall(ref, 'api', pathArgs(o, ref, ch.param, 'id'), optionsWith(o, options)); + }; + const iso = plan.iso ? 'isolate(await fresh(api), marker)' : 'await fresh(api)'; + const first = plan.iso ? 'ISO(marker)' : '{}'; + const after = plan.lifecycleIso ? first : '{}'; + return [ + ` test('create → list → update → list → delete → list', ${testOptions('positive', s.ids?.scenario.lifecycle)}, async ({ api }) => {`, + ` const marker = newMarker();`, + ` const payload = ${iso};`, + ` const { id } = await resource.create(api, payload);`, + ` let deleted = false;`, + ` try {`, + ` let items = await listUntil(api, ${first}, has(id));`, + ` expectFields(expectContains(items, ID, id, 'created resource'), payload, FIELDS);`, + ` const update = resource.newUpdatePayload();`, + ` const res = await ${call(upd, '{ data: update }')};`, + ` ${expectSuccess(upd)}`, + ` const current = (xs: unknown[]) => {`, + ` try {`, + ` expectFields(xs.find((i) => String(readPointer(i, ID)) === id), update, FIELDS);`, + ` return true;`, + ` } catch {`, + ` return false;`, + ` }`, + ` };`, + ` items = await listUntil(api, ${after}, current);`, + ` expectFields(expectContains(items, ID, id, 'updated resource'), update, FIELDS);`, + ` const removed = await ${call(del)};`, + ` ${expectSuccess(del, 'removed')}`, + ` deleted = true;`, + ...(plan.c.deletedDisappears + ? [` items = await listUntil(api, ${after}, (xs) => !has(id)(xs));`, ` expectNotContains(items, ID, id, 'deleted resource');`] + : [` // Not asserted: the deps file does not confirm that a deleted resource leaves the list ("deletedDisappears").`]), + ` } finally {`, + ` if (!deleted) await resource.remove(api, id);`, + ` }`, + ` });`, + '', + ]; +} + +/* ------------------------------------------------------------------ Python */ + +const PY_IMPORTS = 'from contract import expect_all_match, expect_contains, expect_fields, expect_no_duplicate_across_pages, expect_not_contains, expect_page_size, expect_sorted_by, expect_unique_by, items_of, poll, with_value # noqa: F401'; + +export function pyCollectionPrelude(s: SuiteInput, ci: CollectionInput): string[] { + const { plan } = ci; + const op = s.op; + const c = plan.c; + const req = requiredRequest(op).params; + const page = pageEntries(plan, 'i', 'size', (k) => py(k)); + const L = [ + PY_IMPORTS, + '', + `# Collection checks: the reviewed "collection" mapping of ${op.operationId ?? op.key} in the deps file.`, + `ITEMS = ${py(c.items)}`, + `ID = ${py(c.id)}`, + `# Fields the API keeps as sent, with their comparison policy (exact, tolerance:, schema, ignore).`, + `FIELDS = ${py(c.fields ?? {})}`, + `# Bounded polling (documented eventual consistency); 0 = one read.`, + `POLL_TIMEOUT_MS = ${c.consistency?.pollTimeoutMs ?? 0}`, + `POLL_INTERVAL_MS = ${c.consistency?.pollIntervalMs ?? 100}`, + `MAX_PAGES = ${c.maxPages}`, + `WALK = ${plan.walkSize}`, + '', + '', + 'def _marker():', + ' """A value no other data has: the records a test creates carry it, so the test reads only its own records."""', + ' return "ata-" + uuid.uuid4().hex[:8]', + '', + '', + ]; + if (plan.iso) { + const f = plan.iso; + L.push( + 'def _isolate(payload, marker):', + ` """${f.param} ${f.match} ${f.field}: the isolating filter."""`, + ` return with_value(payload, ${py(f.field)}, ${f.match === 'contains' ? '[marker]' : 'marker'})`, + '', + '', + 'def _iso(marker):', + ` return {${py(f.param)}: marker}`, + '', + '', + ); + } + L.push( + 'def _list_page(api, params):', + ` res = api.${op.method}(${pathExpr(op)}, params={**${py(req)}, **params}${pyRequired(op, ['params'])})`, + ` ${assertSuccess(op)}`, + ' return items_of(res.json(), ITEMS)', + '', + '', + 'def _list_pages(api, params, size=WALK):', + ...(page + ? [ + ' pages = []', + ' for i in range(MAX_PAGES):', + ` page = _list_page(api, {**params, ${page}})`, + ' pages.append(page)', + ' if len(page) < size:', + ' break', + ' return pages', + ] + : [' return [_list_page(api, params)] # no reviewed paging: the one response']), + '', + '', + 'def _list_all(api, params):', + ' return [item for page in _list_pages(api, params) for item in page]', + '', + '', + 'def _has(*ids):', + ' return lambda items: all(any(str(read_pointer(i, ID)) == str(r) for i in items) for r in ids)', + '', + '', + 'def _list_until(api, params, done):', + ' return poll(lambda: _list_all(api, params), done, POLL_TIMEOUT_MS, POLL_INTERVAL_MS)', + '', + '', + ); + return L; +} + +function pySeeded(name: string, mark: string, fx: string, payloads: string[], body: string[]): string[] { + return [ + mark, + `def ${name}(api, ${fx}):`, + ' marker = _marker() # noqa: F841', + ' payloads = [', + ...payloads.map((p) => ` ${p},`), + ' ]', + ' ids = []', + ' try:', + ' for p in payloads:', + ` ids.append(${fx}.create(p)[0])`, + ...body.map((l) => ` ${l}`), + ' finally:', + ' for rid in ids:', + ` ${fx}.remove(rid)`, + '', + '', + ]; +} + +export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] { + const { plan, chain } = ci; + const fx = resourceModule(chain).replace(/_resource$/, ''); + const L: string[] = []; + const iso = (p: string) => (plan.iso ? `_isolate(${p}, marker)` : p); + const isoParams = plan.iso ? '_iso(marker)' : '{}'; + const fresh = `${fx}.new_create_payload()`; + const names = new Set(); + const nameOf = (base: string) => { + let n = pyName(base).replace(/_+/g, '_').replace(/_$/, ''); + while (names.has(n)) n += '_2'; + names.add(n); + return n; + }; + plan.tests.forEach((t, n) => { + const mark = withId('@pytest.mark.positive', s.ids?.functional.collection?.[n]); + if (t.kind === 'listed') { + L.push(...pySeeded(nameOf('test_created_resource_is_listed_with_its_fields'), mark, fx, [iso(fresh)], [ + `found = _list_until(api, ${isoParams}, _has(ids[0]))`, + 'expect_fields(expect_contains(found, ID, ids[0], "created resource"), payloads[0], FIELDS)', + ])); + } else if (t.kind === 'filter' && t.mode === 'controlled') { + const f = t.filter!; + const set = (which: 'a' | 'b') => { + const v = filterValue(t, which, 'py'); + const p = `with_value(${fresh}, ${py(f.field)}, ${f.match === 'contains' ? `[${v}]` : v})`; + return t.filterValues!.kind === 'enum' ? iso(p) : p; + }; + const params = t.filterValues!.kind === 'enum' ? `{**_iso(marker), ${py(f.param)}: ${filterValue(t, 'a', 'py')}}` : `{${py(f.param)}: ${filterValue(t, 'a', 'py')}}`; + L.push(...pySeeded(nameOf(`test_filter_${f.param}_returns_matching_and_leaves_out_other`), mark, fx, [set('a'), set('b')], [ + `found = _list_until(api, ${params}, _has(ids[0]))`, + `expect_contains(found, ID, ids[0], ${py(`resource matching ${f.param}`)})`, + `expect_not_contains(found, ID, ids[1], ${py(`resource not matching ${f.param}`)})`, + `expect_all_match(found, ${py(f.field)}, ${py(f.match)}, ${filterValue(t, 'a', 'py')})`, + ])); + } else if (t.kind === 'filter') { + const f = t.filter!; + const values = f.match === 'contains' ? 'v if isinstance(v, list) else []' : '[] if v is None else [v]'; + L.push( + mark, + `def ${nameOf(`test_filter_${f.param}_returns_only_matching`)}(api):`, + ' candidates = []', + ' for item in _list_all(api, {}):', + ` v = read_pointer(item, ${py(f.field)})`, + ` candidates.extend(${values})`, + ' if not candidates:', + ` pytest.skip(${py(`no existing resource has a value in ${f.field} to filter by (read-only check)`)})`, + ' value = candidates[0]', + ` found = _list_all(api, {${py(f.param)}: value})`, + ' assert found, "the filter finds the resource the value came from"', + ` expect_all_match(found, ${py(f.field)}, ${py(f.match)}, value)`, + '', + '', + ); + } else if (t.kind === 'sort' && t.mode === 'controlled') { + const so = t.sort!; + L.push(...pySeeded(nameOf(`test_sort_${so.param}_${so.value.replace(/^-/, 'desc_')}`), mark, fx, t.sortValues!.map((v) => `with_value(_isolate(${fresh}, marker), ${py(so.field)}, ${sortValue(v, 'py')})`), [ + `found = _list_until(api, {**_iso(marker), ${py(so.param)}: ${py(so.value)}}, _has(*ids))`, + 'for rid in ids:', + ' expect_contains(found, ID, rid)', + `expect_sorted_by(found, ${py(so.field)}, ${py(so.order)})`, + ])); + } else if (t.kind === 'sort') { + const so = t.sort!; + L.push( + mark, + `def ${nameOf(`test_sort_${so.param}_${so.value.replace(/^-/, 'desc_')}`)}(api):`, + ` found = _list_all(api, {${py(so.param)}: ${py(so.value)}})`, + ' if len(found) < 2:', + ' pytest.skip("fewer than 2 resources: the order cannot be checked (read-only check)")', + ` expect_sorted_by(found, ${py(so.field)}, ${py(so.order)})`, + '', + '', + ); + } else if (t.kind === 'pagination' && t.mode === 'controlled') { + const ps = plan.pageSize; + L.push(...pySeeded(nameOf('test_pages_have_requested_size_and_never_repeat'), mark, fx, Array.from({ length: ps + 1 }, () => iso(fresh)), [ + `pages = poll(lambda: _list_pages(api, _iso(marker), ${ps}), lambda p: _has(*ids)([x for page in p for x in page]), POLL_TIMEOUT_MS, POLL_INTERVAL_MS)`, + 'for page in pages:', + ` expect_page_size(page, ${ps})`, + `assert len(pages[0]) == ${ps}, f"the first page is full: {len(pages[0])} of ${ps}"`, + 'expect_no_duplicate_across_pages(pages, ID)', + 'for rid in ids:', + ' expect_contains([x for page in pages for x in page], ID, rid)', + ])); + } else if (t.kind === 'pagination') { + const ps = plan.pageSize; + L.push( + mark, + `def ${nameOf('test_pages_have_requested_size_and_never_repeat')}(api):`, + ` pages = _list_pages(api, {}, ${ps})`, + ` if sum(len(p) for p in pages) <= ${ps}:`, + ' pytest.skip("not more than one page of resources (read-only check)")', + ' for page in pages:', + ` expect_page_size(page, ${ps})`, + ` assert len(pages[0]) == ${ps}, f"the first page is full: {len(pages[0])} of ${ps}"`, + ' expect_no_duplicate_across_pages(pages, ID)', + '', + '', + ); + } else if (t.kind === 'unique' && t.mode === 'controlled') { + L.push(...pySeeded(nameOf(`test_unique_by_${leaf(t.unique!)}`), mark, fx, [iso(fresh), iso(fresh)], [ + `found = _list_until(api, _iso(marker), _has(*ids))`, + `expect_unique_by(found, ${py(t.unique)})`, + ])); + } else { + L.push(mark, `def ${nameOf(`test_unique_by_${leaf(t.unique!)}`)}(api):`, ` expect_unique_by(_list_all(api, {}), ${py(t.unique)})`, '', ''); + } + }); + return L; +} + +export function pyLifecycle(s: SuiteInput, ci: CollectionInput): string[] { + const { plan, chain } = ci; + const ch = chain.chain; + const fx = resourceModule(chain).replace(/_resource$/, ''); + const upd = ch.update!; + const del = ch.delete!; + const first = plan.iso ? '_iso(marker)' : '{}'; + const after = plan.lifecycleIso ? first : '{}'; + return [ + withId('@pytest.mark.positive', s.ids?.scenario.lifecycle), + `def test_create_list_update_list_delete_list(api, ${fx}):`, + ' marker = _marker() # noqa: F841', + ` payload = ${plan.iso ? `_isolate(${fx}.new_create_payload(), marker)` : `${fx}.new_create_payload()`}`, + ` rid, _ = ${fx}.create(payload)`, + ' deleted = False', + ' try:', + ` found = _list_until(api, ${first}, _has(rid))`, + ' expect_fields(expect_contains(found, ID, rid, "created resource"), payload, FIELDS)', + ` update = ${fx}.new_update_payload()`, + ` res = api.${upd.method}(${pathExpr(upd, ch.param, 'rid')}, json=update${pyRequired(upd)})`, + ` ${assertSuccess(upd)}`, + '', + ' def current(xs):', + ' try:', + ' expect_fields(next((i for i in xs if str(read_pointer(i, ID)) == str(rid)), None), update, FIELDS)', + ' return True', + ' except AssertionError:', + ' return False', + '', + ` found = _list_until(api, ${after}, current)`, + ' expect_fields(expect_contains(found, ID, rid, "updated resource"), update, FIELDS)', + ` removed = api.${del.method}(${pathExpr(del, ch.param, 'rid')}${pyRequired(del)})`, + ` ${assertSuccess(del, 'removed')}`, + ' deleted = True', + ...(plan.c.deletedDisappears + ? [` found = _list_until(api, ${after}, lambda xs: not _has(rid)(xs))`, ' expect_not_contains(found, ID, rid, "deleted resource")'] + : [' # Not asserted: the deps file does not confirm that a deleted resource leaves the list ("deletedDisappears").']), + ' finally:', + ' if not deleted:', + ` ${fx}.remove(rid)`, + '', + '', + ]; +} + +/* ------------------------------------------------------------------ approved fixtures (strategy B) */ + +export const fixtureModule = (f: LoadedFixture) => `${f.fixture.operationId.replace(/[^\w-]/g, '_')}`; + +function fixturePage(f: LoadedFixture, i: string, q: (s: string) => string): { entries?: string; size: number; maxPages: number } { + const p = f.fixture.page; + const size = p?.size ?? 50; + const maxPages = Math.min(p?.maxPages ?? 20, 50); + if (p?.style === 'offset') return { entries: `${q(p.offsetParam)}: ${i} * ${size}, ${q(p.limitParam)}: ${size}`, size, maxPages }; + if (p?.style === 'page') return { entries: `${q(p.pageParam)}: ${i} + ${p.firstPage ?? 1}, ${q(p.sizeParam)}: ${size}`, size, maxPages }; + return { size, maxPages }; +} + +const fixturePath = (f: LoadedFixture) => f.file.split('\\').join('/'); + +/** _support/approved/.fixture.ts: the approved fixture, copied so the suite runs on its own. */ +export function tsFixtureModule(f: LoadedFixture, version: string): string { + return `// Approved fixture ${fixturePath(f)}, copied by api-test-agent ${version}. Edit the approved file, not this copy.\nexport const fixture = ${JSON.stringify(f.fixture, null, 2)};\n`; +} + +export const tsFixtureImport = (f: LoadedFixture) => `import { fixture as approved } from '../../_support/approved/${fixtureModule(f)}.fixture.js';`; + +export function tsFixtureTest(s: SuiteInput, f: LoadedFixture): string[] { + const op = s.op; + const ref = s.refs.get(op)!; + const req = requiredRequest(op).params; + const pg = fixturePage(f, 'i', js); + const call = (extra: string) => `await ${apiCall(ref, 'api', pathArgs(op, ref), `{ params: { ...${js(req)}, ...approved.query, ${extra} } as Record }`)}`; + return [ + ` test(${js(`matches the approved fixture ${fixturePath(f)}`)}, ${testOptions('positive', s.ids?.functional.fixture)}, async ({ api }) => {`, + ` const items: unknown[] = [];`, + ...(pg.entries + ? [ + ` for (let i = 0; i < ${pg.maxPages}; i++) {`, + ` const res = ${call(pg.entries)};`, + ` ${expectSuccess(op)}`, + ` const page = itemsOf(await res.json(), approved.items);`, + ` items.push(...page);`, + ` if (page.length < ${pg.size}) break;`, + ` }`, + ] + : [` const res = ${call('')};`, ` ${expectSuccess(op)}`, ` items.push(...itemsOf(await res.json(), approved.items));`]), + ` expectMatchesFixture(items, approved);`, + ` });`, + '', + ]; +} + +export function pyFixtureTest(s: SuiteInput, f: LoadedFixture): string[] { + const op = s.op; + const req = requiredRequest(op).params; + const pg = fixturePage(f, 'i', (k) => py(k)); + const call = (extra: string) => `api.${op.method}(${pathExpr(op)}, params={**${py(req)}, **fixture.get("query", {})${extra ? ', ' + extra : ''}}${pyRequired(op, ['params'])})`; + return [ + 'import pathlib # noqa: E402', + 'from contract import expect_matches_fixture, items_of # noqa: E402,F401', + '', + '', + withId('@pytest.mark.positive', s.ids?.functional.fixture), + 'def test_matches_approved_fixture(api):', + ` """Approved fixture ${fixturePath(f)} (copied to _support/approved)."""`, + ` fixture = json.loads((pathlib.Path(__file__).resolve().parents[2] / "_support" / "approved" / ${py(fixtureModule(f) + '.json')}).read_text(encoding="utf-8"))`, + ' items = []', + ...(pg.entries + ? [` for i in range(${pg.maxPages}):`, ` res = ${call(pg.entries)}`, ` ${assertSuccess(op)}`, ' page = items_of(res.json(), fixture["items"])', ' items.extend(page)', ` if len(page) < ${pg.size}:`, ' break'] + : [` res = ${call('')}`, ` ${assertSuccess(op)}`, ' items.extend(items_of(res.json(), fixture["items"]))']), + ' expect_matches_fixture(items, fixture)', + '', + '', + ]; +} diff --git a/src/generate/collection-tests.ts b/src/generate/collection-tests.ts new file mode 100644 index 0000000..fdb3668 --- /dev/null +++ b/src/generate/collection-tests.ts @@ -0,0 +1,128 @@ +import type { OpenApiDoc } from '../spec/loader.js'; +import type { CoverageGap } from './body-cases.js'; +import { schemaAt, type ResolvedCollection } from './collection.js'; + +/** + * Deep collection tests (strategies A and C). One plan feeds the TypeScript and Python renderers and the case IDs. + * + * Controlled datasets (strategy A, create & verify): when the resource can be created and cleaned up, a test creates + * its own records carrying a unique marker in an isolating filter field and reads the collection through that filter. + * Sorting, paging and uniqueness are then checked on known data (an empty or one-element page would hide the defect), + * and nothing depends on other data on the target. Without creation the same checks run read-only (strategy C) on + * existing data, and a test without enough data is skipped with the reason, never passed silently. + */ + +export type CollectionTestKind = 'listed' | 'filter' | 'sort' | 'pagination' | 'unique'; +type Filter = { param: string; field: string; match: 'equals' | 'contains' }; + +export interface CollectionTest { + kind: CollectionTestKind; + title: string; + mode: 'controlled' | 'read-only'; + filter?: Filter; + /** Controlled filter: the matching and the non-matching value ("marker" = derived from the run's unique marker). */ + filterValues?: { kind: 'marker' } | { kind: 'enum'; a: string | number; b: string | number }; + sort?: { param: string; value: string; field: string; order: 'asc' | 'desc' }; + /** Controlled sort: the sort-field values of the three records, in creation order (strings get the marker appended). */ + sortValues?: (string | number)[]; + unique?: string; +} + +export interface CollectionPlan { + c: ResolvedCollection; + tests: CollectionTest[]; + /** The filter that isolates the test's own records (a unique marker), when one is settable on create. */ + iso?: Filter; + /** create → listed → update → listed → delete → not listed, in the list operation's scenarios. */ + lifecycle: boolean; + /** The update payload leaves the isolating field alone, so the lifecycle can keep reading through the filter. */ + lifecycleIso: boolean; + gaps: CoverageGap[]; + /** Page size used to walk the whole collection (bounded by maxPages). */ + walkSize: number; + /** Page size of the pagination test (its controlled dataset has pageSize + 1 records). */ + pageSize: number; +} + +const typesOf = (s: any): string[] => (s?.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type]); +/** A free-text string field that accepts the marker ("ata-" + 8 characters, plus a short suffix). */ +const markerString = (s: any) => typesOf(s).includes('string') && !s.enum && s.const === undefined && !s.pattern && !s.format && (s.maxLength ?? Infinity) >= 20 && (s.minLength ?? 0) <= 12; + +export function planCollectionTests(doc: OpenApiDoc, c: ResolvedCollection, x: { canCreate: boolean; createSchema?: any; canUpdate: boolean; updatePayload?: unknown; canDelete: boolean }): CollectionPlan { + const gaps: CoverageGap[] = []; + const tests: CollectionTest[] = []; + const top = (ptr: string) => ptr.split('/').length === 2; // controlled data sets top-level fields only + const createField = (ptr: string) => (x.canCreate && x.createSchema && top(ptr) ? schemaAt(doc, x.createSchema, ptr) : undefined); + const markerFilter = (f: Filter) => { + const s = createField(f.field); + if (!s) return false; + return f.match === 'contains' ? typesOf(s).includes('array') && markerString(schemaAt(doc, s, '/*')) && (s.maxItems ?? 1) >= 1 : markerString(s); + }; + const filters = (c.filters ?? []).filter((f, i, all) => all.findIndex((g) => g.param === f.param) === i); + const iso = filters.find(markerFilter); + + const limitParam = c.page?.style === 'offset' ? c.page.limitParam : c.page?.style === 'page' ? c.page.sizeParam : undefined; + const limitSchema: any = limitParam ? c.op.params.find((p) => p.name === limitParam)?.schema : undefined; + const minSize = typeof limitSchema?.minimum === 'number' ? limitSchema.minimum : 1; + const maxSize = typeof limitSchema?.maximum === 'number' ? limitSchema.maximum : 50; + const walkSize = Math.max(minSize, Math.min(maxSize, 50)); + const pageSize = Math.min(Math.max(2, minSize), maxSize); + + if (x.canCreate) tests.push({ kind: 'listed', title: 'a created resource is listed with the fields it was created with', mode: 'controlled' }); + else gaps.push({ code: 'MISSING_CLEANUP', location: 'operation', reason: `${c.op.key}: membership of a created resource needs a confirmed create with cleanup (strategy A); only read-only checks run` }); + + for (const f of filters) { + const s = createField(f.field); + let filterValues: CollectionTest['filterValues']; + if (markerFilter(f)) filterValues = { kind: 'marker' }; + else if (iso && s && f.match === 'equals' && Array.isArray(s.enum) && s.enum.length >= 2) filterValues = { kind: 'enum', a: s.enum[0], b: s.enum[1] }; + tests.push({ + kind: 'filter', + title: filterValues ? `filter ${f.param} returns the matching resource and leaves out the other` : `filter ${f.param} returns only matching resources`, + mode: filterValues ? 'controlled' : 'read-only', + filter: f, + ...(filterValues ? { filterValues } : {}), + }); + if (!filterValues && x.canCreate) gaps.push({ code: 'CANNOT_ISOLATE_RULE', location: `request.query#/${f.param}`, reason: `filter ${f.param}: ${f.field} cannot be set to a value no other data has, so it is checked read-only on existing data` }); + } + for (const s of (c.sorts ?? []).filter((v, i, all) => all.findIndex((w) => w.param === v.param && w.value === v.value) === i)) { + const field = iso ? createField(s.field) : undefined; + let sortValues: (string | number)[] | undefined; + if (field && !field.enum) { + if (typesOf(field).some((t) => t === 'integer' || t === 'number')) { + const lo = typeof field.minimum === 'number' ? field.minimum + (field.exclusiveMinimum === true ? 1 : 0) : 1; + if (typeof field.maximum !== 'number' || field.maximum >= lo + 2) sortValues = [lo + 2, lo, lo + 1]; + } else if (markerString(field)) sortValues = ['sort-c-', 'sort-a-', 'sort-b-']; + } + tests.push({ kind: 'sort', title: `sort ${s.param}=${s.value} orders by ${s.field} ${s.order === 'asc' ? 'ascending' : 'descending'}`, mode: sortValues ? 'controlled' : 'read-only', sort: s, ...(sortValues ? { sortValues } : {}) }); + } + if (c.page) { + const controlled = !!iso && pageSize <= 5; + tests.push({ kind: 'pagination', title: `pages of ${pageSize} have the requested size and never repeat a resource`, mode: controlled ? 'controlled' : 'read-only' }); + } else gaps.push({ code: 'UNCONFIRMED_BUSINESS_RULE', location: 'operation', reason: `${c.op.key}: no reviewed paging mapping ("page"): page size and cross-page duplicates are not checked` }); + for (const u of [...new Set(c.unique ?? [])]) tests.push({ kind: 'unique', title: `resources are unique by ${u}`, mode: iso ? 'controlled' : 'read-only', unique: u }); + if (!iso && x.canCreate) gaps.push({ code: 'CANNOT_ISOLATE_RULE', location: 'operation', reason: `${c.op.key}: no filter can isolate the test's own records, so sorting, paging and uniqueness run read-only on existing data` }); + + const lifecycle = x.canCreate && x.canUpdate && x.canDelete && Object.keys(c.fields ?? {}).length > 0; + if (!lifecycle) gaps.push({ code: 'UNCONFIRMED_BUSINESS_RULE', location: 'lifecycle', reason: `${c.op.key}: create → list → update → list → delete → list needs a confirmed create, update (with an example payload) and delete, and confirmed field persistence ("fields")` }); + else if (!c.deletedDisappears) gaps.push({ code: 'UNCONFIRMED_BUSINESS_RULE', location: 'lifecycle', reason: `${c.op.key}: that a deleted resource leaves the list is not confirmed ("deletedDisappears"), so the last step is not asserted` }); + const isoKey = iso?.field.slice(1).replace(/~1/g, '/').replace(/~0/g, '~'); + const lifecycleIso = !!iso && !(x.updatePayload && typeof x.updatePayload === 'object' && isoKey! in (x.updatePayload as object)); + return { c, tests, ...(iso ? { iso } : {}), lifecycle, lifecycleIso, gaps, walkSize, pageSize }; +} + +/** Strategy recorded in coverage for a list operation, with the reasons. */ +export function collectionStrategy(plan: CollectionPlan | undefined, why: string[], fixture = false): { strategy: 'create-verify' | 'read-only' | 'fixtures' | 'contract-only'; strategies: string[]; reasons: string[] } { + const r = base(plan, why); + if (!fixture) return { ...r, strategies: [r.strategy] }; + const reasons = [...r.reasons, 'approved fixture compared field by field (strategy B)']; + return r.strategy === 'contract-only' || r.strategy === 'read-only' ? { strategy: 'fixtures', strategies: ['fixtures', ...(r.strategy === 'read-only' ? ['read-only'] : [])], reasons } : { strategy: r.strategy, strategies: [r.strategy, 'fixtures'], reasons }; +} + +function base(plan: CollectionPlan | undefined, why: string[]): { strategy: 'create-verify' | 'read-only' | 'contract-only'; reasons: string[] } { + if (!plan) return { strategy: 'contract-only', reasons: why }; + if (plan.tests.some((t) => t.mode === 'controlled')) { + return { strategy: 'create-verify', reasons: [`controlled dataset${plan.iso ? ` isolated by ${plan.iso.param}` : ''}; ${plan.tests.filter((t) => t.mode === 'read-only').map((t) => `${t.kind} read-only`).join(', ') || 'every check on own data'}`] }; + } + return { strategy: 'read-only', reasons: ['no confirmed create with cleanup or no isolating filter: properties are checked on existing data, tests without enough data are skipped'] }; +} diff --git a/src/generate/collection.ts b/src/generate/collection.ts new file mode 100644 index 0000000..650256f --- /dev/null +++ b/src/generate/collection.ts @@ -0,0 +1,140 @@ +import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; +import type { Operation } from '../types.js'; +import type { CoverageGap } from './body-cases.js'; + +/** + * Collection endpoints (GET lists): how a reviewed deps file describes them, and the strict check of that + * description against the spec. Nothing here is inferred from endpoint names. + * + * "collection": { + * "operationId": "listItems", + * "items": "/items", JSON pointer to the array in the response ("" = the body is the array) + * "id": "/id", element field holding the identifier the create returns + * "fields": { "/name": "exact", "/price": "tolerance:0.001", "/createdAt": "ignore" }, persistence confirmed + * "unique": ["/id"], uniqueness the API guarantees + * "filters": [{ "param": "tag", "field": "/tags", "match": "contains" }], + * "sorts": [{ "param": "sort", "value": "price", "field": "/price", "order": "asc" }], + * "page": { "style": "offset", "offsetParam": "offset", "limitParam": "limit", "maxPages": 20 }, + * "consistency": { "pollTimeoutMs": 5000, "pollIntervalMs": 250 }, eventual consistency, bounded polling + * "deletedDisappears": true a deleted resource is guaranteed to leave the list + * } + */ + +export type FieldPolicy = 'exact' | 'schema' | 'ignore' | `tolerance:${number}`; + +export interface CollectionConfig { + operationId: string; + items: string; + id: string; + fields?: Record; + unique?: string[]; + filters?: { param: string; field: string; match: 'equals' | 'contains' }[]; + sorts?: { param: string; value: string; field: string; order: 'asc' | 'desc' }[]; + page?: { style: 'offset'; offsetParam: string; limitParam: string; maxPages?: number } | { style: 'page'; pageParam: string; sizeParam: string; firstPage?: number; maxPages?: number }; + consistency?: { pollTimeoutMs: number; pollIntervalMs: number }; + deletedDisappears?: boolean; +} + +export interface ResolvedCollection extends CollectionConfig { + op: Operation; + maxPages: number; + /** Schema of one element (for checks that need a type). */ + itemSchema: any; +} + +const deref = (doc: OpenApiDoc, s: any, depth = 0): any => (s?.$ref && depth < 20 ? deref(doc, resolvePointer(doc, s.$ref.slice(1)).node, depth + 1) : s); +const typesOf = (s: any): string[] => (s?.type === undefined ? (s?.properties ? ['object'] : s?.items ? ['array'] : []) : Array.isArray(s.type) ? s.type : [s.type]); + +/** Follows a JSON pointer through a schema (properties, array items for "*"), $refs and allOf resolved. */ +export function schemaAt(doc: OpenApiDoc, schema: any, pointer: string): any { + let node = deref(doc, schema); + for (const raw of pointer.split('/').slice(1)) { + const seg = raw.replace(/~1/g, '/').replace(/~0/g, '~'); + if (!node) return undefined; + if (Array.isArray(node.allOf)) node = Object.assign({}, ...node.allOf.map((p: any) => deref(doc, p)), { properties: Object.assign({}, ...node.allOf.map((p: any) => deref(doc, p)?.properties ?? {}), node.properties ?? {}) }); + node = deref(doc, seg === '*' ? node.items : node.properties?.[seg]); + } + return node; +} + +/** The array a collection response holds: the body itself, or its single array property. Never guessed by name. */ +export function detectItems(doc: OpenApiDoc, op: Operation): string | undefined { + const ok = op.responses.find((r) => /^2\d\d$/.test(r.status)); + const schema = ok ? resolvePointer(doc, `/paths/${op.path.replace(/~/g, '~0').replace(/\//g, '~1')}/${op.method}/responses/${ok.status}/content/application~1json/schema`).node : undefined; + const s = deref(doc, schema); + if (!s) return undefined; + if (typesOf(s).includes('array')) return ''; + const arrays = Object.entries(s.properties ?? {}).filter(([, p]) => typesOf(deref(doc, p)).includes('array')); + return arrays.length === 1 ? `/${arrays[0][0]}` : undefined; +} + +export function resolveCollection(doc: OpenApiDoc, ops: Operation[], cfg: CollectionConfig): { collection?: ResolvedCollection; errors: string[] } { + const errors: string[] = []; + const op = ops.find((o) => o.operationId === cfg?.operationId); + if (!op) return { errors: [`collection: operation "${cfg?.operationId}" is not in the spec`] }; + if (op.method !== 'get') errors.push(`collection: ${op.key} is not a GET`); + const ok = op.responses.find((r) => /^2\d\d$/.test(r.status)); + const response = ok ? resolvePointer(doc, `/paths/${op.path.replace(/~/g, '~0').replace(/\//g, '~1')}/get/responses/${ok.status}/content/application~1json/schema`).node : undefined; + if (!response) return { errors: [...errors, `collection: ${op.key} documents no JSON success schema`] }; + if (typeof cfg.items !== 'string' || !(cfg.items === '' || cfg.items.startsWith('/'))) errors.push('collection: "items" is a JSON pointer ("" for an array body)'); + const arr = schemaAt(doc, response, cfg.items ?? ''); + if (!arr || !typesOf(arr).includes('array')) errors.push(`collection: "${cfg.items}" is not an array in the ${op.key} response`); + const itemSchema = deref(doc, arr?.items); + const field = (ptr: string, what: string) => { + if (typeof ptr !== 'string' || !ptr.startsWith('/')) errors.push(`collection: ${what} "${ptr}" is not a JSON pointer`); + else if (itemSchema && !schemaAt(doc, itemSchema, ptr)) errors.push(`collection: ${what} "${ptr}" is not a field of the ${op.key} elements`); + }; + field(cfg.id, '"id"'); + for (const [ptr, policy] of Object.entries(cfg.fields ?? {})) { + field(ptr, 'field'); + if (!/^(exact|schema|ignore|tolerance:\d+(\.\d+)?)$/.test(policy)) errors.push(`collection: policy "${policy}" of ${ptr} is not exact, schema, ignore or tolerance:`); + } + for (const u of cfg.unique ?? []) field(u, 'unique'); + const query = (name: string, what: string) => { + if (!op.params.some((p) => p.in === 'query' && p.name === name)) errors.push(`collection: ${what} "${name}" is not a query parameter of ${op.key}`); + }; + for (const f of cfg.filters ?? []) { + query(f.param, 'filter parameter'); + field(f.field, 'filter field'); + if (f.match !== 'equals' && f.match !== 'contains') errors.push(`collection: filter match "${f.match}" is equals or contains`); + } + for (const s of cfg.sorts ?? []) { + query(s.param, 'sort parameter'); + field(s.field, 'sort field'); + const p = op.params.find((x) => x.name === s.param); + const allowed = (p?.schema as any)?.enum; + if (Array.isArray(allowed) && !allowed.map(String).includes(String(s.value))) errors.push(`collection: sort value "${s.value}" is not documented for "${s.param}"`); + if (s.order !== 'asc' && s.order !== 'desc') errors.push('collection: sort order is asc or desc'); + } + if (cfg.page) { + if (cfg.page.style === 'offset') { + query(cfg.page.offsetParam, 'offset parameter'); + query(cfg.page.limitParam, 'limit parameter'); + } else if (cfg.page.style === 'page') { + query(cfg.page.pageParam, 'page parameter'); + query(cfg.page.sizeParam, 'size parameter'); + } else errors.push('collection: page style is offset or page (cursor is not supported yet)'); + } + const c = cfg.consistency; + if (c && !(c.pollTimeoutMs > 0 && c.pollTimeoutMs <= 60_000 && c.pollIntervalMs > 0 && c.pollIntervalMs <= c.pollTimeoutMs)) errors.push('collection: consistency needs 0 < pollIntervalMs <= pollTimeoutMs <= 60000'); + if (errors.length) return { errors }; + return { collection: { ...cfg, op, itemSchema, maxPages: Math.min(cfg.page?.maxPages ?? 10, 50) }, errors }; +} + +/** The array holds resources (objects with properties), not scalar values. */ +function collectionOfObjects(doc: OpenApiDoc, op: Operation, items: string): boolean { + const ok = op.responses.find((r) => /^2\d\d$/.test(r.status)); + const schema = ok ? resolvePointer(doc, `/paths/${op.path.replace(/~/g, '~0').replace(/\//g, '~1')}/get/responses/${ok.status}/content/application~1json/schema`).node : undefined; + const el = schemaAt(doc, schema, items + '/*'); + return !!el && (typesOf(el).includes('object') || !!el.allOf); +} + +/** What deeper collection checks are missing for a GET list, and why (no config, no create, …). */ +export function collectionGaps(doc: OpenApiDoc, op: Operation, configured: boolean): CoverageGap[] { + // A path ending in a parameter reads one resource; its array fields (e.g. tags) are not a collection. + if (op.method !== 'get' || configured || /\}$/.test(op.path)) return []; + const items = detectItems(doc, op); + if (items === undefined) return []; + if (!collectionOfObjects(doc, op, items)) return []; + return [{ code: 'UNCONFIRMED_BUSINESS_RULE', location: 'operation', reason: `collection${items ? ` at ${items}` : ''}: membership, filters, sorting and pagination need a reviewed "collection" mapping in the deps file (identifier field, filter / sort semantics, paging)` }]; +} diff --git a/src/generate/coverage.ts b/src/generate/coverage.ts index c1e2b0b..b4495f3 100644 --- a/src/generate/coverage.ts +++ b/src/generate/coverage.ts @@ -23,6 +23,7 @@ export const GAP_CODES = [ 'UNSAFE_LIVE_CHECK', 'DEPRECATED_OPERATION', 'NO_DOCUMENTED_REJECTION', + 'INVALID_REVIEWED_CONFIG', ] as const; /** The code behind a positive-blocked reason the generator writes in prose. */ diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 2ca8f2c..8df3a52 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -15,6 +15,10 @@ import { isUrl } from '../change/network.js'; import { bodyCasesDetailed, compositionGaps, type CoverageGap } from './body-cases.js'; import { paramCasesDetailed, sendable } from './param-cases.js'; import { errorPlan } from './error-cases.js'; +import { collectionGaps, resolveCollection } from './collection.js'; +import { collectionStrategy, planCollectionTests } from './collection-tests.js'; +import { tsFixtureModule, fixtureModule, type CollectionInput } from './collection-render.js'; +import type { LoadedFixture } from '../fixtures/fixtures.js'; import { positiveCode, uncheckedRequest, uncheckedStatuses } from './coverage.js'; import type { ResolvedScenario } from '../scenarios/dsl.js'; import { bodyCases, documentedRejections, nonexistentIdExpr, type NegCase } from './negative.js'; @@ -41,6 +45,9 @@ export interface GenerateOptions { maxCases?: number; /** Reviewed business scenarios (validated with validateScenarios against the same operations). */ scenarios?: ResolvedScenario[]; + /** Approved fixtures (strategy B), already validated against the spec; invalid ones arrive as fixtureErrors. */ + fixtures?: LoadedFixture[]; + fixtureErrors?: { file: string; operationId?: string; errors: string[] }[]; } export interface Scenario { @@ -91,6 +98,8 @@ export interface Coverage { uncheckedRequestContentTypes: string[]; /** Security alternatives beyond the one the suite uses. */ uncheckedSecurityAlternatives: string[][]; + /** List operations: how the collection is tested (create-verify / read-only / contract-only) and why. */ + collection?: { strategy: string; reasons: string[]; tests: { kind: string; mode: string }[] }; } function jsonBodySchema(spec: LoadedSpec, op: Operation): any { @@ -223,6 +232,21 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp if (op && !chainBlock.has(op)) chainBlock.set(op, c.question); } } + // Reviewed collection mappings (deps "collection"): checked strictly against the spec; errors become gaps. + const collectionOf = new Map['collection']> }>(); + const collectionErrors = new Map(); + for (const chain of chains) { + if (!chain.collection) continue; + const r = resolveCollection(spec.doc, ops, chain.collection); + const key = ops.find((x) => x.operationId === chain.collection!.operationId)?.key ?? ''; + const p = plans.find((x) => x.chain === chain); + if (r.collection && p) collectionOf.set(r.collection.op, { plan: p, c: r.collection }); + else { + const gaps: CoverageGap[] = r.errors.map((reason) => ({ code: 'INVALID_REVIEWED_CONFIG', location: 'operation', reason })); + if (r.collection && !p) gaps.push({ code: 'MISSING_CLEANUP', location: 'operation', reason: `collection of ${chain.name}: the chain is blocked, so no collection tests are generated` }); + collectionErrors.set(key, [...(collectionErrors.get(key) ?? []), ...gaps]); + } + } const planOf = (op: Operation) => plans.find((p) => [p.chain.create, p.chain.read, p.chain.update, p.chain.delete].includes(op)); const helperFile = (p: ChainPlan) => (py ? join(support, `${resourceModule(p)}.py`) : join(support, `${operationFolder(p.chain.create).resource}.resource.ts`)); for (const p of plans) await write(helperFile(p), py ? renderPyResource(p, meta) : renderResourceHelpers(p, refs, meta)); @@ -255,7 +279,9 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const dir = join(out, resource, action); const name = `${resource}/${action}`; const plan = planOf(op); - const helpers = plan ? posix(relative(dir, helperFile(plan))).replace(/\.ts$/, '.js') : undefined; + const coll = collectionOf.get(op); + const helperPlan = plan ?? coll?.plan; + const helpers = helperPlan ? posix(relative(dir, helperFile(helperPlan))).replace(/\.ts$/, '.js') : undefined; const safe = SAFE_METHODS.includes(op.method); const pathParams = op.params.filter((p) => p.in === 'path'); const unresolvedPath = pathParams.filter((p) => p.knownValue === undefined && p.name !== plan?.chain.param); @@ -333,9 +359,19 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp if (firstWith405) paths405.add(op.path); const errors = op.deprecated ? { gaps: [] } : errorPlan({ doc: spec.doc, op, ops, chain: plan?.chain, role: errRole, hasUpdatePayload: plan?.updatePayload !== undefined, reachable, firstWith405 }); const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors, business: (o.scenarios ?? []).filter((b) => b.primaryOp === op) }; + let collPlan: ReturnType | undefined; + if (coll && input.positive && !op.deprecated) { + const ch = coll.plan.chain; + collPlan = planCollectionTests(spec.doc, coll.c, { canCreate: !!ch.delete, createSchema: jsonBodySchema(spec, ch.create), canUpdate: !!ch.update && coll.plan.updatePayload !== undefined, updatePayload: coll.plan.updatePayload, canDelete: !!ch.delete }); + input.collection = { plan: collPlan, chain: coll.plan } satisfies CollectionInput; + } + const fixture = input.positive && !op.deprecated ? o.fixtures?.find((f) => f.op === op) : undefined; + if (fixture) input.fixture = fixture; + const fixtureGaps: CoverageGap[] = (o.fixtureErrors ?? []).filter((e) => e.operationId && e.operationId === op.operationId).flatMap((e) => e.errors.map((reason) => ({ code: 'INVALID_REVIEWED_CONFIG', location: 'operation', reason: `${e.file}: ${reason}` }))); + const collGaps: CoverageGap[] = [...fixtureGaps, ...(collectionErrors.get(op.key) ?? []), ...(collPlan?.gaps ?? []), ...(coll ? [] : collectionGaps(spec.doc, op, false))]; const counts = suiteCounts(input); const variants = input.positive && !plan && op.method === 'get' ? queryVariants(op) : []; - const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants, errors, business: input.business }, uidOf); + const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants, errors, business: input.business, collection: collPlan, collectionChain: coll?.plan.chain, fixture: !!fixture }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. // oneOf / anyOf in a payload that is sent: the other branches are reported (never dropped silently). @@ -362,7 +398,8 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp positiveBlockedCode: pCode, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, - gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps], + gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps, ...collGaps], + ...(coll || fixture || collGaps.length ? { collection: { ...collectionStrategy(collPlan, collGaps.map((g) => g.reason), !!fixture), tests: [...(collPlan?.tests ?? []).map((t) => ({ kind: t.kind, mode: t.mode })), ...(fixture ? [{ kind: 'fixture', mode: 'approved' }] : [])] } } : {}), ...(bodyStats ? { bodyCases: bodyStats } : {}), suites: { functional: { generated: counts.functional, missingCode: counts.functional ? null : pCode ?? 'NO_DOCUMENTED_REJECTION' }, @@ -415,6 +452,11 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp } } + // Approved fixtures used by this run, copied next to the suite (the suite runs without the agent). + for (const f of o.fixtures ?? []) { + if (!coverage.some((c) => c.operation === f.op.key && c.collection?.tests.some((t) => t.kind === 'fixture'))) continue; + await write(join(support, 'approved', py ? `${fixtureModule(f)}.json` : `${fixtureModule(f)}.fixture.ts`), py ? JSON.stringify(f.fixture, null, 2) + '\n' : tsFixtureModule(f, o.version)); + } if (files.length && py) { // Self-contained support code: the generated suite runs without the agent installed. await write(join(support, 'contract.py'), await readFile(fileURLToPath(new URL('../../src/contract/contract.py', import.meta.url)), 'utf8')); @@ -437,6 +479,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp await write(join(apiDir, 'generated', `${g.className}Base.ts`), renderApiBaseClass(g, refs, o.version)); const child = join(apiDir, `${g.className}.ts`); if (!existsSync(child)) await write(child, renderApiChildClass(g)); + else hashes.set(child, fileHash(await readFile(child, 'utf8'))); // kept in the manifest as hand-written, never rewritten } await write(join(apiDir, 'generated', 'apis.ts'), renderApis(groups, o.version)); await write(join(support, 'openapi.snapshot.ts'), `// Snapshot of ${spec.location} (hash ${spec.hash}). Regenerated with the tests.\nexport const spec: any = ${JSON.stringify(spec.doc, null, 2)};\n`); diff --git a/src/generate/graph.ts b/src/generate/graph.ts index 8becfcc..733d109 100644 --- a/src/generate/graph.ts +++ b/src/generate/graph.ts @@ -1,6 +1,7 @@ import type { Operation } from '../types.js'; import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; import { operationPointer } from '../spec/catalog.js'; +import type { CollectionConfig } from './collection.js'; /** * A CRUD chain: create → read → update → delete for one resource. @@ -23,6 +24,8 @@ export interface CrudChain { conflictOn?: string[]; /** Create body fields the create response returns unchanged (a reviewed mapping): asserted in the create test. */ echoes?: string[]; + /** The reviewed list operation that shows this resource (deps file "collection"), checked in resolveCollection. */ + collection?: CollectionConfig; } export interface FillRule { @@ -54,6 +57,8 @@ export interface DepsFile { conflictOn?: string[]; /** Fields the create response returns as sent. */ echoes?: string[]; + /** The list operation of this resource and its confirmed semantics (src/generate/collection.ts). */ + collection?: CollectionConfig; }[]; } @@ -79,6 +84,7 @@ export function findChains(doc: OpenApiDoc, ops: Operation[], deps?: DepsFile): ...(s.fill ? { fill: Object.entries(s.fill).map(([field, f]) => ({ field, fromId: f?.from, from: byId.get(f?.from), pointer: f?.pointer })) } : {}), ...(Array.isArray(s.conflictOn) && s.conflictOn.length ? { conflictOn: s.conflictOn.map(String) } : {}), ...(Array.isArray(s.echoes) && s.echoes.length ? { echoes: s.echoes.map(String) } : {}), + ...(s.collection && typeof s.collection === 'object' ? { collection: s.collection } : {}), }); } diff --git a/src/generate/python.ts b/src/generate/python.ts index 828cb5d..74eced2 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -2,6 +2,7 @@ import type { Operation } from '../types.js'; import { requiredRequest } from './param-cases.js'; import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/dsl.js'; import type { CrudChain } from './graph.js'; +import { pyCollectionPrelude, pyCollectionTests, pyFixtureTest, pyLifecycle } from './collection-render.js'; import { hasFill, queryVariants, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; /** @@ -35,7 +36,7 @@ export function pyLit(v: unknown, indent = 0): string { return `{\n${entries.map(([k, x]) => `${pad} ${str(k)}: ${pyLit(x, indent + 4)},`).join('\n')}\n${pad}}`; } -function assertSuccess(op: Operation, v = 'res'): string { +export function assertSuccess(op: Operation, v = 'res'): string { const ok = successCodes(op); return ok.length === 1 ? `assert ${v}.status_code == ${ok[0]}, f"documented success status of ${label(op)} is ${ok[0]}, got {${v}.status_code}"` @@ -43,7 +44,7 @@ function assertSuccess(op: Operation, v = 'res'): string { } /** Python f-string for the request path; the chain parameter comes from `idVar`. */ -function pathExpr(op: Operation, chainParam?: string, idVar = 'resource_id'): string { +export function pathExpr(op: Operation, chainParam?: string, idVar = 'resource_id'): string { let p = op.path.replace(/^\//, '').replace(/[{}]/g, (c) => c + c); // escape braces for the f-string for (const param of op.params.filter((x) => x.in === 'path')) { // Inner literals use single quotes: the f-string itself is double-quoted (Python < 3.12 forbids reuse). @@ -55,7 +56,7 @@ function pathExpr(op: Operation, chainParam?: string, idVar = 'resource_id'): st } /** Keyword arguments with the operation's required query / header / cookie parameters (documented values). */ -function pyRequired(op: Operation, skip: ('params' | 'headers')[] = []): string { +export function pyRequired(op: Operation, skip: ('params' | 'headers')[] = []): string { const r = requiredRequest(op); return [ Object.keys(r.params).length && !skip.includes('params') ? `, params=${pyLit(r.params, 4)}` : '', @@ -354,7 +355,7 @@ ${fixtures}`; const POS = '@pytest.mark.positive'; const NEG = '@pytest.mark.negative'; /** The polarity marker plus, when known, the stable case ID marker (registered in conftest.py). */ -const withId = (mark: string, id?: string) => (id ? `${mark}\n@pytest.mark.api_case_id(${str(id)})` : mark); +export const withId = (mark: string, id?: string) => (id ? `${mark}\n@pytest.mark.api_case_id(${str(id)})` : mark); const paramMarks = (id?: string) => (id ? `, marks=pytest.mark.api_case_id(${str(id)})` : ''); function pyHeader(suite: SuiteType, s: SuiteInput, meta: Meta, extra: string[]): string[] { @@ -448,6 +449,11 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { if (s.notFound) L.push(...pyNotFound(s, 'test_returns_documented_404_for_unknown_id', withId(NEG, s.ids?.functional.notFound), statusIs(op, '404'))); if (s.unauthorized) L.push(...pyAnonymous(s, 'test_returns_documented_401_without_credentials', withId(NEG, s.ids?.functional.unauthorized), statusIs(op, '401'))); L.push(...pyErrorTests(s)); + if (s.collection?.plan.tests.length) { + L.splice(L.indexOf(`pytestmark = pytest.mark.functional`), 0, ...pyCollectionPrelude(s, s.collection)); + L.push(...pyCollectionTests(s, s.collection)); + } + if (s.fixture) L.push(...pyFixtureTest(s, s.fixture)); return finish(L); } @@ -623,6 +629,10 @@ export function renderPyScenarios(s: SuiteInput, meta: Meta): string { if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = pyHeader('scenario', s, meta, extra); const id = `created_${res}`; + if (s.collection?.plan.lifecycle) { + L.splice(L.indexOf(`pytestmark = pytest.mark.scenario`), 0, ...pyCollectionPrelude(s, s.collection)); + L.push(...pyLifecycle(s, s.collection)); + } if (sc.deleteTwice) { // A repeated delete of the same resource gets the documented 404. L.push( diff --git a/src/generate/templates.ts b/src/generate/templates.ts index 3ca0eb3..421d725 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -7,6 +7,8 @@ import { requiredRequest, type ParamRequest } from './param-cases.js'; import type { ErrorPlan } from './error-cases.js'; import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/dsl.js'; import { boundaryValues } from './boundaries.js'; +import { tsCollectionImports, tsCollectionPrelude, tsCollectionTests, tsFixtureImport, tsFixtureTest, tsLifecycle, type CollectionInput } from './collection-render.js'; +import type { LoadedFixture } from '../fixtures/fixtures.js'; /** Payloads and assumptions for one confirmed resource chain. */ export interface ChainPlan { @@ -50,7 +52,7 @@ const lit = (v: unknown) => JSON.stringify(v, null, 2); const label = (op: Operation) => op.operationId ?? op.key; const successCodes = (op: Operation) => op.responses.map((r) => r.status).filter((s) => /^2\d\d$/.test(s)); -function expectSuccess(op: Operation, v = 'res') { +export function expectSuccess(op: Operation, v = 'res') { const ok = successCodes(op); return ok.length === 1 ? `expect(${v}.status(), 'documented success status of ${label(op)}').toBe(${ok[0]});` @@ -102,7 +104,7 @@ function header(kind: string, op: Operation, meta: Meta, extra: string[]): strin /* ------------------------------------------------------------------ helpers per resource */ /** Arguments for an API object method: path parameters in order; the chain parameter comes from `idVar`. */ -function pathArgs(op: Operation, ref: ApiRef, chainParam?: string, idVar = 'id'): string[] { +export function pathArgs(op: Operation, ref: ApiRef, chainParam?: string, idVar = 'id'): string[] { return ref.pathParams.map((name) => { if (name === chainParam) return idVar; const p = op.params.find((x) => x.in === 'path' && x.name === name); @@ -228,6 +230,10 @@ export interface SuiteInput { errors?: ErrorPlan; /** Reviewed business scenarios whose primary step is this operation (stage 8). */ business?: ResolvedScenario[]; + /** A list operation with a reviewed "collection" mapping: deep collection tests and the list lifecycle. */ + collection?: CollectionInput; + /** An approved fixture of this list operation (strategy B). */ + fixture?: LoadedFixture; } export type Role = 'create' | 'read' | 'update' | 'delete'; @@ -256,10 +262,14 @@ export function suiteCounts(s: SuiteInput): Record { const extra = (s.notFound ? 1 : 0) + (s.unauthorized ? 1 : 0); const sc = scenarioCases(s); const e = s.errors; - return { + const base = { functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0) + (e?.invalidCredentials ? 1 : 0) + (e?.methodNotAllowed ? 1 : 0) + (e?.preconditionFailed && s.plan ? 1 : 0), contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length + (e?.unsupportedMediaType && s.plan ? 1 : 0), - scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0) + (sc.conflict ? 1 : 0) + (sc.deleteTwice ? 1 : 0) + (s.business?.length ?? 0), + }; + return { + contract: base.contract, + functional: base.functional + (s.collection?.plan.tests.length ?? 0) + (s.fixture ? 1 : 0), + scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0) + (sc.conflict ? 1 : 0) + (sc.deleteTwice ? 1 : 0) + (s.business?.length ?? 0) + (s.collection?.plan.lifecycle ? 1 : 0), }; } @@ -356,11 +366,12 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { const chain = plan?.chain; const role = roleOf(op, plan); const fx = chain ? 'api' : apiFixture(op); - const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan); + const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan) || !!s.collection?.plan.tests.length; const errorStatus = !!(s.errors?.invalidCredentials || s.errors?.methodNotAllowed || s.errors?.preconditionFailed); - const names = ['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : [])]; - const L = suiteHeader('functional', s, meta, ['Checks the behavior of the endpoint: status and result. The response schema is checked in contract.spec.ts.']); - L.push(...imports(s, names, usesHelpers), '', `test.describe('${op.key} · functional', { tag: '@functional' }, () => {`); + const coll = s.collection?.plan.tests.length ? s.collection : undefined; + const names = [...new Set(['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : []), ...(coll ? tsCollectionImports('functional') : []), ...(s.fixture ? ['itemsOf', 'expectMatchesFixture'] : [])])]; + const L = suiteHeader('functional', s, meta, ['Checks the behavior of the endpoint: status and result. The response schema is checked in contract.spec.ts.', ...(coll ? ['Collection checks run on records the tests create (controlled datasets) or, where marked read-only, on existing data.'] : [])]); + L.push(...imports(s, names, usesHelpers), ...(s.fixture ? [tsFixtureImport(s.fixture)] : []), ...(coll ? ['', ...tsCollectionPrelude(s, coll)] : ['']), `test.describe('${op.key} · functional', { tag: '@functional' }, () => {`); if (s.positive) { const titles: Record = { @@ -406,6 +417,8 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { L.push(` test('returns documented 401 without credentials', ${testOptions('negative', s.ids?.functional.unauthorized)}, async ({ publicApi }) => {`, anonymousCall(s), ` expectStatus(res, ['401'], '${op.method}', ${q(op.path)});`, ` });`, ''); } L.push(...errorTests(s)); + if (coll) L.push(...tsCollectionTests(s, coll)); + if (s.fixture) L.push(...tsFixtureTest(s, s.fixture)); return close(L); } @@ -597,8 +610,10 @@ export function renderScenarios(s: SuiteInput, meta: Meta): string { if (business.length) extra.push('Business scenarios come from the reviewed scenarios file: steps, expected statuses and cleanup as written there.'); if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = suiteHeader('scenario', s, meta, extra); - const names = ['expect', ...(sc.createRead || business.length ? ['readPointer'] : []), ...(sc.conflict || sc.deleteTwice || business.length ? ['expectStatus'] : []), ...(business.length ? ['fillVars', 'reportCleanupFailure'] : [])]; - L.push(...imports(s, names, !!plan, false), '', `test.describe('${op.key} · scenarios', { tag: '@scenario' }, () => {`); + const life = s.collection?.plan.lifecycle ? s.collection : undefined; + const names = [...new Set(['expect', ...(sc.createRead || business.length ? ['readPointer'] : []), ...(sc.conflict || sc.deleteTwice || business.length ? ['expectStatus'] : []), ...(business.length ? ['fillVars', 'reportCleanupFailure'] : []), ...(life ? tsCollectionImports('scenario') : [])])]; + L.push(...imports(s, names, !!plan || !!life, false), ...(life ? ['', ...tsCollectionPrelude(s, life)] : ['']), `test.describe('${op.key} · scenarios', { tag: '@scenario' }, () => {`); + if (life) L.push(...tsLifecycle(s, life)); if (sc.deleteTwice) { // A repeated delete of the same resource gets the documented 404. L.push( @@ -758,6 +773,128 @@ export async function expectRejected(res: APIResponse, documented: string[], met return expectContract(res, method, path); } +/* Collection checks (a reviewed "collection" mapping in the deps file). Same semantics in contract.py. */ + +/** The array a collection response holds ("" = the body itself). */ +export function itemsOf(body: unknown, pointer: string): unknown[] { + const v = pointer ? readPointer(body, pointer) : body; + expect(Array.isArray(v), 'collection at "' + (pointer || '(body)') + '" is an array').toBe(true); + return v as unknown[]; +} +const idOf = (item: unknown, ptr: string) => String(readPointer(item, ptr)); + +/** The resource with this id is in the collection; returns it. */ +export function expectContains(items: unknown[], idPtr: string, id: unknown, what = 'resource'): unknown { + const found = items.find((i) => idOf(i, idPtr) === String(id)); + expect(found, what + ' ' + String(id) + ' is in the collection').toBeDefined(); + return found; +} + +export function expectNotContains(items: unknown[], idPtr: string, id: unknown, what = 'resource'): void { + expect(items.some((i) => idOf(i, idPtr) === String(id)), what + ' ' + String(id) + ' is not in the collection').toBe(false); +} + +/** Fields compare by policy: exact, tolerance:; ignore and schema are not compared here (schema: contract suite). */ +export function expectFields(item: unknown, expected: unknown, policies: Record): void { + for (const [ptr, policy] of Object.entries(policies)) { + if (policy === 'ignore' || policy === 'schema') continue; + const want = readPointer(expected, ptr); + if (want === undefined) continue; + const got = readPointer(item, ptr); + if (policy.startsWith('tolerance:')) { + const t = Number(policy.slice('tolerance:'.length)); + expect(Math.abs(Number(got) - Number(want)), ptr + ' within ' + t + ' of ' + String(want) + ' (got ' + String(got) + ')').toBeLessThanOrEqual(t); + } else expect(got, ptr + ' as sent').toEqual(want); + } +} + +/** Every element matches a filter: equals (the field is the value) or contains (the array field holds it). */ +export function expectAllMatch(items: unknown[], ptr: string, match: 'equals' | 'contains', value: unknown): void { + const bad = items.filter((i) => { + const v = readPointer(i, ptr); + return match === 'contains' ? !(Array.isArray(v) && v.map(String).includes(String(value))) : String(v) !== String(value); + }); + expect(bad.length, bad.length + ' element(s) do not match ' + ptr + ' ' + match + ' ' + String(value)).toBe(0); +} + +export function expectUniqueBy(items: unknown[], ptr: string): void { + const seen = new Set(); + const dups = items.map((i) => idOf(i, ptr)).filter((k) => (seen.has(k) ? true : (seen.add(k), false))); + expect(dups, 'duplicates by ' + ptr).toEqual([]); +} + +/** Order by plain comparison (code points for strings, numeric for numbers): the API must document this order. */ +export function expectSortedBy(items: unknown[], ptr: string, order: 'asc' | 'desc'): void { + for (let i = 1; i < items.length; i++) { + const a = readPointer(items[i - 1], ptr) as any; + const b = readPointer(items[i], ptr) as any; + const ok = order === 'asc' ? !(b < a) : !(b > a); + expect(ok, ptr + ' ' + order + ' at position ' + i + ': ' + String(a) + ' then ' + String(b)).toBe(true); + } +} + +export function expectPageSize(items: unknown[], max: number): void { + expect(items.length, 'page size').toBeLessThanOrEqual(max); +} + +export function expectNoDuplicateAcrossPages(pages: unknown[][], idPtr: string): void { + expectUniqueBy(pages.flat(), idPtr); +} + +/** Leaf pointers of a value (objects and arrays walked). */ +function leaves(v: unknown, prefix = ''): string[] { + if (v && typeof v === 'object' && Object.keys(v).length) return Object.entries(v as Record).flatMap(([k, x]) => leaves(x, prefix + '/' + k.replace(/~/g, '~0').replace(/\\//g, '~1'))); + return [prefix]; +} + +/** + * Approved fixture (strategy B): every expected element is in the collection, each field compared by its policy + * (the longest matching policy pointer, else the default): exact, tolerance:, schema (present), ignore. + * exhaustive: the collection holds exactly the expected elements. + */ +export function expectMatchesFixture(items: unknown[], f: { id: string; expected: unknown[]; policies?: Record; default?: string; exhaustive?: boolean }): void { + const policyOf = (leaf: string) => { + const hit = Object.keys(f.policies ?? {}).filter((p) => leaf === p || leaf.startsWith(p + '/')).sort((a, b) => b.length - a.length)[0]; + return hit ? f.policies![hit] : f.default ?? 'exact'; + }; + for (const want of f.expected) { + const id = readPointer(want, f.id); + const got = expectContains(items, f.id, id, 'approved fixture element'); + for (const leaf of leaves(want)) { + const policy = policyOf(leaf); + const a = readPointer(got, leaf); + const b = readPointer(want, leaf); + const at = 'element ' + String(id) + ' ' + leaf; + if (policy === 'ignore') continue; + if (policy === 'schema') expect(a, at + ' is present').not.toBeUndefined(); + else if (policy.startsWith('tolerance:')) expect(Math.abs(Number(a) - Number(b)), at + ' within ' + policy.slice(10) + ' of ' + String(b) + ' (got ' + String(a) + ')').toBeLessThanOrEqual(Number(policy.slice(10))); + else expect(a, at + ' as approved').toEqual(b); + } + } + if (f.exhaustive) expect(items.length, 'the collection holds exactly the approved elements').toBe(f.expected.length); +} + +/** Bounded polling for documented eventual consistency: returns the last value; never waits past timeoutMs. */ +export async function poll(fn: () => Promise, done: (v: T) => boolean, timeoutMs: number, intervalMs: number): Promise { + const end = Date.now() + timeoutMs; + let v = await fn(); + while (!done(v) && Date.now() < end) { + await new Promise((r) => setTimeout(r, intervalMs)); + v = await fn(); + } + return v; +} + +/** A copy of a payload with one field (JSON pointer through objects) set. */ +export function withValue(payload: T, ptr: string, value: unknown): T { + const out = structuredClone(payload) as any; + const keys = ptr.split('/').slice(1).map((k) => k.replace(/~1/g, '/').replace(/~0/g, '~')); + let node = out; + for (const k of keys.slice(0, -1)) node = node[k] ??= {}; + node[keys[keys.length - 1]] = value; + return out; +} + /** Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text. */ export function fillVars(value: T, vars: Record): T { const sub = (v: any): any => { diff --git a/src/maintain.ts b/src/maintain.ts new file mode 100644 index 0000000..2516096 --- /dev/null +++ b/src/maintain.ts @@ -0,0 +1,172 @@ +import { existsSync } from 'node:fs'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { join, relative } from 'node:path'; +import type { LoadedSpec } from './spec/loader.js'; +import type { Operation } from './types.js'; +import { generate, type GenerateOptions, type GenerateResult } from './generate/generate.js'; +import { summarize } from './generate/coverage.js'; +import { runDiff } from './change/diff.js'; +import type { OpenApiChange } from './change/types.js'; +import { normalizeSpec } from './change/normalize.js'; +import { readSource } from './change/network.js'; +import { validateManifest, validateRegistry } from './cases/validate.js'; +import { upsertDraftPr } from './pr.js'; + +/** + * Automated test maintenance: spec diff → regenerate (deterministic, so only affected files change) → validate → + * one Draft PR per suite with a short summary. Never merges, never runs tests against an environment, never + * changes approved fixtures. + */ + +export interface MaintainOptions { + location: string; + spec: LoadedSpec; + ops: Operation[]; + generate: Omit; + testsDir: string; + base?: string; + out: string; + draftPr: boolean; + allowNetwork: boolean; + log: (m: string) => void; +} + +export interface MaintainResult { + changed: boolean; + valid: boolean; + summaryFile: string; + pr?: { url: string; updated: boolean }; + files: { added: string[]; updated: string[]; headerOnly: string[]; removed: string[] }; + cases: { added: string[]; retired: string[] }; +} + +/** File content without the lines that only name the spec and generator (they change with every spec hash). */ +const substance = (text: string) => + text + .split('\n') + .filter((l) => !/(Spec: .*\(hash [0-9a-f]+\)|Generated by api-test-agent|^\s*"?(specHash|hash|capturedRevision|source|revision|generatorVersion)"?\s*[:=])/.test(l)) + .join('\n'); + +async function contents(testsDir: string, files: Iterable): Promise> { + const out = new Map(); + for (const f of files) { + const p = join(testsDir, f); + if (existsSync(p)) out.set(f, substance(await readFile(p, 'utf8'))); + } + return out; +} + +async function snapshot(testsDir: string): Promise<{ files: Map; cases: Map }> { + const manifestFile = join(testsDir, '_support', 'generation-manifest.json'); + const registryFile = join(testsDir, '_support', 'cases.json'); + const manifest = existsSync(manifestFile) ? JSON.parse(await readFile(manifestFile, 'utf8')) : { files: {} }; + const registry = existsSync(registryFile) ? JSON.parse(await readFile(registryFile, 'utf8')) : { cases: {} }; + return { + files: new Map(Object.entries(manifest.files ?? {}).map(([f, e]) => [f, e.sha256])), + cases: new Map(Object.entries(registry.cases ?? {}).map(([id, c]) => [id, c.status])), + }; +} + +const fmt = (v: unknown) => (v === undefined ? '—' : JSON.stringify(v)); + +export async function maintain(o: MaintainOptions): Promise { + await mkdir(o.out, { recursive: true }); + // 1. What changed in the spec (oasdiff). Without a baseline or the engine, everything is regenerated and said so. + let changes: OpenApiChange[] = []; + let diffNote = ''; + try { + const d = await runDiff({ head: o.location, base: o.base, out: join(o.out, 'diff'), format: 'markdown', failOn: ['never'], allowEngineVersionMismatch: true, testsDir: o.testsDir, allowNetwork: o.allowNetwork, allowHosts: [], log: () => {} }); + changes = d.set.changes; + if (d.set.blocked.length) diffNote = `diff blocked: ${d.set.blocked.map((b) => b.code).join(', ')}; the whole suite was regenerated`; + } catch (e) { + diffNote = `diff unavailable (${(e as Error).message.split('\n')[0]}); the whole suite was regenerated`; + } + const relevant = changes.filter((c) => c.testRelevant); + o.log(`Spec changes: ${changes.length} (test-relevant ${relevant.length})${diffNote ? ` · ${diffNote}` : ''}`); + + // 2. Regenerate the whole suite: deterministic output, so unaffected files keep their bytes and hashes. + const before = await snapshot(o.testsDir); + const oldText = await contents(o.testsDir, before.files.keys()); + const previousCoverage = join(o.out, 'coverage-gaps.json'); + const oldGaps: Record | undefined = existsSync(previousCoverage) ? JSON.parse(await readFile(previousCoverage, 'utf8')).summary?.gapsByCode ?? {} : undefined; + const gen: GenerateResult = await generate(o.spec, o.ops, { ...o.generate, outDir: o.testsDir }); + const after = await snapshot(o.testsDir); + const newGaps = summarize(gen.coverage); + await writeFile(previousCoverage, JSON.stringify({ spec: o.location, hash: o.spec.hash, summary: { gapsByCode: newGaps }, operations: gen.coverage }, null, 2) + '\n'); + + const newText = await contents(o.testsDir, after.files.keys()); + const touched = [...after.files.keys()].filter((f) => before.files.has(f) && before.files.get(f) !== after.files.get(f)); + const files = { + added: [...after.files.keys()].filter((f) => !before.files.has(f)), + updated: touched.filter((f) => oldText.get(f) !== newText.get(f)), + /** Only the spec hash / generator lines changed: committed, but not a change a reviewer needs to read. */ + headerOnly: touched.filter((f) => oldText.get(f) === newText.get(f)), + // A file is removed only when it is gone from disk (hand-written files are never deleted by the generator). + removed: [...before.files.keys()].filter((f) => !after.files.has(f) && !existsSync(join(o.testsDir, f))), + }; + const active = (m: Map) => new Set([...m].filter(([, s]) => s !== 'retired').map(([id]) => id)); + const was = active(before.cases); + const now = active(after.cases); + const cases = { added: [...now].filter((id) => !was.has(id)), retired: [...was].filter((id) => !now.has(id)) }; + const changed = files.added.length + files.updated.length + files.headerOnly.length + files.removed.length > 0; + + // 3. Validate what was generated: registry against the head spec, manifest hashes. + const problems: string[] = []; + const registryFile = join(o.testsDir, '_support', 'cases.json'); + if (existsSync(registryFile)) { + const reg = validateRegistry(await readFile(registryFile, 'utf8'), normalizeSpec(await readSource(o.location, { allowNetwork: o.allowNetwork, allowHosts: [] }), o.location)); + problems.push(...reg.errors.map((e) => `registry ${e.code} ${e.pointer}: ${e.reason}`), ...reg.blocked.map((b) => `registry BLOCKED ${b.code}: ${b.reason}`)); + } + const man = await validateManifest(o.testsDir); + problems.push(...man.findings.filter((f) => f.code !== 'CASE_REGISTRY_CHANGED').map((f) => `manifest ${f.code}: ${f.reason}`)); + const valid = problems.length === 0; + + // 4. Summary for the reviewer. + const gapCodes = [...new Set([...Object.keys(oldGaps ?? {}), ...Object.keys(newGaps)])].sort(); + const gapRows = oldGaps + ? gapCodes.filter((c) => (oldGaps[c] ?? 0) !== (newGaps[c] ?? 0)).map((c) => `| ${c} | ${oldGaps[c] ?? 0} | ${newGaps[c] ?? 0} |`) + : gapCodes.map((c) => `| ${c} | unknown | ${newGaps[c]} |`); + const needsReview = gen.coverage.flatMap((c) => c.gaps.filter((g) => g.code === 'INVALID_REVIEWED_CONFIG').map((g) => `- ${c.operation}: ${g.reason}`)); + const expectations = relevant.filter((c) => c.before !== undefined || c.after !== undefined); + const fixtures = gen.files.filter((f) => /[\\/]_support[\\/]approved[\\/]/.test(f)).map((f) => relative(o.testsDir, f).replace(/\\/g, '/')); + const L = [ + `## API test maintenance: ${o.spec.doc.info?.title ?? o.location}`, + '', + `Spec \`${o.location}\` (hash ${o.spec.hash.slice(0, 12)}). ${diffNote || `${changes.length} change(s), ${relevant.length} test-relevant.`}`, + '', + '### Changed operations', + ...(relevant.length ? [...new Set(relevant.map((c) => c.operationKey))].map((k) => `- ${k}: ${relevant.filter((c) => c.operationKey === k).map((c) => c.kind + (c.breaking === 'yes' ? ' (breaking)' : '')).join(', ')}`) : ['- none detected']), + '', + '### Tests', + `- files added ${files.added.length}, updated ${files.updated.length}, removed ${files.removed.length}; ${files.headerOnly.length} only got the new spec hash in their header`, + `- cases added ${cases.added.length}, retired ${cases.retired.length}`, + ...[...files.added.map((f) => ` - added \`${f}\``), ...files.updated.map((f) => ` - updated \`${f}\``), ...files.removed.map((f) => ` - removed \`${f}\``)].slice(0, 40), + '', + '### Expectations old → new', + ...(expectations.length ? expectations.slice(0, 30).map((c) => `- ${c.operationKey} ${c.kind}${c.facet ? ` ${c.facet}` : ''}${c.pointer ? ` at ${c.pointer}` : ''}: ${fmt(c.before)} → ${fmt(c.after)}`) : ['- none']), + '', + '### Fixtures', + ...(fixtures.length ? fixtures.map((f) => `- uses approved \`${f}\` (approved fixtures are never changed here; refresh them with \`fixtures refresh\`)`) : ['- none used']), + '', + ...(needsReview.length ? ['### Needs review: reviewed configuration no longer matches the spec', ...needsReview, '(these checks are not generated until the deps / fixture file is updated)', ''] : []), + `### Coverage gaps${oldGaps ? '' : ' (no earlier report in this output directory: before is unknown)'}`, + ...(gapRows.length ? ['| code | before | after |', '|---|---|---|', ...gapRows] : ['- unchanged']), + '', + '### Validation', + ...(valid ? ['- case registry and generation manifest: valid'] : problems.slice(0, 20).map((p) => `- FAILED ${p}`)), + '- generated tests were not run here: CI runs them on this branch. Review assertions; never edit one just to make it pass.', + ]; + const summaryFile = join(o.out, 'maintenance-summary.md'); + await writeFile(summaryFile, L.join('\n') + '\n'); + await writeFile(join(o.out, 'maintenance-summary.json'), JSON.stringify({ changes: relevant.length, files, cases, gaps: { before: oldGaps, after: newGaps }, valid, problems }, null, 2) + '\n'); + o.log(`Tests: ${files.added.length} added, ${files.updated.length} updated (${files.headerOnly.length} header-only), ${files.removed.length} removed · cases +${cases.added.length} / retired ${cases.retired.length} · validation ${valid ? 'passed' : 'FAILED'}`); + + let pr: MaintainResult['pr']; + if (o.draftPr && changed && valid) { + const branch = `api-agent/maintain-${o.testsDir.replace(/[^\w-]+/g, '-').replace(/^-|-$/g, '')}`; + const list = [...files.added, ...files.updated, ...files.headerOnly, ...files.removed, '_support/generation-manifest.json', '_support/cases.json'].map((f) => join(o.testsDir, f)); + pr = upsertDraftPr({ branch, files: list, title: `test(api): update generated tests for ${o.spec.doc.info?.title ?? 'the API'} (${o.spec.hash.slice(0, 8)})`, bodyFile: summaryFile, commitMessage: [`test(api): regenerate after spec change ${o.spec.hash.slice(0, 8)}`, 'Generated by api-test-agent maintain. Review before merging.'] }); + o.log(pr ? `Draft PR ${pr.updated ? 'updated' : 'opened'}: ${pr.url}` : 'Nothing to commit: Draft PR skipped.'); + } else if (o.draftPr) o.log(!changed ? 'Tests are up to date: no Draft PR.' : 'Validation failed: no Draft PR (see the summary).'); + return { changed, valid, summaryFile, ...(pr ? { pr } : {}), files, cases }; +} diff --git a/src/pr.ts b/src/pr.ts index ef3458c..39978a0 100644 --- a/src/pr.ts +++ b/src/pr.ts @@ -23,3 +23,38 @@ export async function openDraftPr(o: { files: string[]; title: string; bodyFile: git('switch', base); } } + +const ghOut = (args: string[]) => execFileSync('gh', args, { encoding: 'utf8' }).trim(); + +/** + * One Draft PR per bot branch: commits the files on `branch` (recreated from the current HEAD), force-pushes it + * with a lease, and updates the open PR of that branch instead of opening a second one. Never merges. + * Returns undefined when the files have no changes to commit. + */ +export function upsertDraftPr(o: { branch: string; files: string[]; title: string; bodyFile: string; commitMessage: string[] }): { url: string; updated: boolean } | undefined { + const base = git('rev-parse', '--abbrev-ref', 'HEAD'); + if (base === o.branch) throw new Error(`Run from the base branch, not from ${o.branch}.`); + const existing = ghOut(['pr', 'list', '--head', o.branch, '--state', 'open', '--json', 'url', '--jq', '.[0].url']) || undefined; + try { + git('fetch', '-q', 'origin', o.branch); + } catch { + /* the branch does not exist on the remote yet */ + } + git('switch', '-q', '-C', o.branch); + try { + const present = o.files.filter((f) => existsSync(f)); + const gone = o.files.filter((f) => !existsSync(f)); + if (present.length) git('add', '--', ...present); + if (gone.length) git('rm', '--cached', '--ignore-unmatch', '-q', '--', ...gone); + if (!git('diff', '--cached', '--name-only')) return undefined; + git('commit', '-q', ...o.commitMessage.flatMap((m) => ['-m', m])); + git('push', '-q', '--force-with-lease', '-u', 'origin', o.branch); + if (existing) { + ghOut(['pr', 'edit', existing, '--title', o.title, '--body-file', o.bodyFile]); + return { url: existing, updated: true }; + } + return { url: ghOut(['pr', 'create', '--draft', '--base', base, '--head', o.branch, '--title', o.title, '--body-file', o.bodyFile]), updated: false }; + } finally { + git('switch', '-q', base); + } +} diff --git a/tests/fixtures/coverage/kitchen-sink.expected-gaps.json b/tests/fixtures/coverage/kitchen-sink.expected-gaps.json index 0ed1f7a..8c38cd1 100644 --- a/tests/fixtures/coverage/kitchen-sink.expected-gaps.json +++ b/tests/fixtures/coverage/kitchen-sink.expected-gaps.json @@ -1,7 +1,7 @@ { "CANNOT_ISOLATE_RULE": 6, "MISSING_CLEANUP": 1, - "UNCONFIRMED_BUSINESS_RULE": 1, + "UNCONFIRMED_BUSINESS_RULE": 2, "UNCOVERED_VARIANT": 2, "UNREACHABLE_RESPONSE_STATUS": 1, "UNSAFE_LIVE_CHECK": 1, diff --git a/tests/unit/collection.test.ts b/tests/unit/collection.test.ts new file mode 100644 index 0000000..e911676 --- /dev/null +++ b/tests/unit/collection.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { generate } from '../../src/generate/generate.js'; +import { collectionGaps, resolveCollection, type CollectionConfig } from '../../src/generate/collection.js'; +import { planCollectionTests } from '../../src/generate/collection-tests.js'; +import { parseCaseId } from '../../src/cases/ids.js'; +import { diffFixtures, loadApproved, policyOf, validateFixture, type Fixture } from '../../src/fixtures/fixtures.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { normalizeSpec } from '../../src/change/normalize.js'; + +/** Collection testing (docs/SUPPORT_MATRIX.md, "Collections"): reviewed mapping, strategies, fixtures, IDs. */ + +const demo = await loadSpec('demo-api/openapi.yaml'); +const ops = buildCatalog(demo.doc); +const deps = JSON.parse(await readFile('demo-api/deps.json', 'utf8')); +const cfg: CollectionConfig = deps.scenarios[0].collection; +const approved: Fixture = JSON.parse(await readFile('demo-api/fixtures/approved/listItems.json', 'utf8')); +const createSchema = { $ref: '#/components/schemas/ItemInput' }; + +async function gen(lang: 'typescript' | 'python', withFixtures = true) { + const dir = await mkdtemp(join(tmpdir(), 'ata-coll-')); + const fx = withFixtures ? await loadApproved('demo-api/fixtures/approved', demo.doc, ops) : undefined; + const r = await generate(demo, ops, { outDir: dir, version: 'test', lang, deps, ...(fx ? { fixtures: fx.fixtures, fixtureErrors: fx.errors } : {}) }); + return { dir, r, read: (f: string) => readFile(join(dir, f), 'utf8') }; +} +const idsIn = (text: string) => [...text.matchAll(/(?:description: |caseId: )'([^']+)'|api_case_id\("([^"]+)"\)/g)].map((m) => m[1] ?? m[2]).filter((x) => x !== 'c.caseId'); + +describe('reviewed collection mapping', () => { + it('resolves the demo mapping against the spec', () => { + const r = resolveCollection(demo.doc, ops, cfg); + expect(r.errors).toEqual([]); + expect(r.collection?.op.key).toBe('GET /items'); + expect(r.collection?.maxPages).toBe(20); + }); + + it('rejects every part that does not match the spec, never guessing', () => { + const bad = { + ...cfg, + items: '/total', + id: '/nope', + fields: { '/name': 'roughly' }, + filters: [{ param: 'colour', field: '/tags', match: 'like' as any }], + sorts: [{ param: 'sort', value: 'weight', field: '/price', order: 'up' as any }], + page: { style: 'offset' as const, offsetParam: 'skip', limitParam: 'limit' }, + consistency: { pollTimeoutMs: 120_000, pollIntervalMs: 10 }, + }; + const errors = resolveCollection(demo.doc, ops, bad).errors.join('\n'); + for (const part of ['"/total" is not an array', 'policy "roughly"', 'filter parameter "colour"', 'match "like"', 'sort value "weight"', 'sort order', 'offset parameter "skip"', 'consistency']) expect(errors).toContain(part); + expect(resolveCollection(demo.doc, ops, { ...cfg, operationId: 'createItem' }).errors.join()).toContain('not a GET'); + }); + + it('flags only real collections without a mapping (a single resource with an array field is not one)', () => { + const op = (k: string) => ops.find((o) => o.key === k)!; + expect(collectionGaps(demo.doc, op('GET /items'), false).map((g) => g.code)).toEqual(['UNCONFIRMED_BUSINESS_RULE']); + expect(collectionGaps(demo.doc, op('GET /items/{itemId}'), false)).toEqual([]); + expect(collectionGaps(demo.doc, op('GET /items'), true)).toEqual([]); + }); +}); + +describe('strategy selection', () => { + const c = resolveCollection(demo.doc, ops, cfg).collection!; + + it('create & verify: every check on records the test creates, isolated by a filter', () => { + const p = planCollectionTests(demo.doc, c, { canCreate: true, createSchema, canUpdate: true, updatePayload: { name: 'x', price: 1 }, canDelete: true }); + expect(p.iso?.param).toBe('tag'); + expect(p.tests.map((t) => `${t.kind}:${t.mode}`)).toEqual(['listed:controlled', 'filter:controlled', 'sort:controlled', 'sort:controlled', 'sort:controlled', 'sort:controlled', 'pagination:controlled', 'unique:controlled']); + expect(p.tests.find((t) => t.sort?.value === 'price')?.sortValues).toEqual([2, 0, 1]); // distinct, created out of order + expect(p.lifecycle && p.lifecycleIso).toBe(true); + expect(p.pageSize).toBe(2); + }); + + it('read-only without a create: the same properties on existing data, reasons as gaps', () => { + const p = planCollectionTests(demo.doc, c, { canCreate: false, canUpdate: false, canDelete: false }); + expect(p.tests.every((t) => t.mode === 'read-only')).toBe(true); + expect(p.tests.some((t) => t.kind === 'listed')).toBe(false); + expect(p.gaps.map((g) => g.code)).toEqual(['MISSING_CLEANUP', 'UNCONFIRMED_BUSINESS_RULE']); + }); + + it('an update that changes the isolating field makes the lifecycle read the unfiltered list', () => { + const p = planCollectionTests(demo.doc, c, { canCreate: true, createSchema, canUpdate: true, updatePayload: { tags: ['other'] }, canDelete: true }); + expect(p.lifecycleIso).toBe(false); + }); +}); + +describe('generated collection tests', () => { + it('TypeScript and Python have the same collection cases, each a valid v3 case ID', async () => { + const ts = await gen('typescript'); + const py = await gen('python'); + const tsIds = idsIn(await ts.read('items/get/functional.spec.ts')).concat(idsIn(await ts.read('items/get/scenarios.spec.ts'))).sort(); + const pyIds = idsIn(await py.read('items/get/test_functional.py')).concat(idsIn(await py.read('items/get/test_scenarios.py'))).sort(); + expect(pyIds).toEqual(tsIds); + expect(new Set(tsIds).size).toBe(tsIds.length); + const rules = tsIds.map((id) => (parseCaseId(id) as any).parts.rule); + for (const r of ['collection-contains', 'filter', 'sort', 'pagination', 'unique', 'fixture', 'crud']) expect(rules).toContain(r); + for (const id of tsIds) expect(parseCaseId(id).ok, id).toBe(true); + const reg = validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('demo-api/openapi.yaml', 'utf8'), 'demo-api/openapi.yaml')); + expect(reg.errors).toEqual([]); + }); + + it('records the strategy per list operation in coverage', async () => { + const { r } = await gen('typescript'); + const c = r.coverage.find((x) => x.operation === 'GET /items')!; + expect(c.collection?.strategy).toBe('create-verify'); + expect((c.collection as any).strategies).toEqual(['create-verify', 'fixtures']); + expect(c.collection?.tests.filter((t) => t.kind === 'fixture')).toHaveLength(1); + }); + + it('controlled tests clean up in finally and poll only within the documented bound', async () => { + const text = await (await gen('typescript', false)).read('items/get/functional.spec.ts'); + expect(text).toContain('for (const id of ids) await resource.remove(api, id);'); + expect(text).toContain('const POLL = {"timeoutMs":0,"intervalMs":100};'); + expect(text).toContain('const MAX_PAGES = 20;'); + }); +}); + +describe('approved fixtures (strategy B)', () => { + + it('the demo fixture is valid; a broken one is reported, never used', () => { + expect(validateFixture(demo.doc, ops, approved).errors).toEqual([]); + const errors = validateFixture(demo.doc, ops, { ...approved, operationId: 'createItem' }).errors.join(); + expect(errors).toContain('not a GET'); + const dup = validateFixture(demo.doc, ops, { ...approved, expected: [approved.expected[0], approved.expected[0]], query: { colour: 'red' } }).errors.join('\n'); + expect(dup).toContain('repeat an id'); + expect(dup).toContain('query "colour"'); + }); + + it('policies: the longest matching pointer wins, else the default', () => { + expect(policyOf({ policies: { '/a': 'ignore', '/a/b': 'exact' }, default: 'schema' }, '/a/b/c')).toBe('exact'); + expect(policyOf({ policies: { '/a': 'ignore' }, default: 'schema' }, '/a/x')).toBe('ignore'); + expect(policyOf({ policies: {}, default: 'schema' }, '/z')).toBe('schema'); + }); + + it('a candidate is compared under the approved policies (ignored and tolerated differences are not changes)', () => { + const candidate = structuredClone(approved); + (candidate.expected[0] as any).createdAt = '2030-01-01T00:00:00Z'; // ignore + (candidate.expected[0] as any).price += 0.0005; // within tolerance:0.001 + expect(diffFixtures(approved, candidate)).toEqual({ added: [], removed: [], changed: [] }); + (candidate.expected[1] as any).name = 'Renamed'; + candidate.expected.push({ id: 'new' }); + const d = diffFixtures(approved, candidate); + expect(d.added).toEqual(['"new"']); + expect(d.changed).toEqual([{ id: JSON.stringify((approved.expected[1] as any).id), pointer: '/name', before: 'Catalog screwdriver', after: 'Renamed' }]); + }); +}); diff --git a/tests/unit/core.test.ts b/tests/unit/core.test.ts index cdad314..4d2cc02 100644 --- a/tests/unit/core.test.ts +++ b/tests/unit/core.test.ts @@ -152,7 +152,7 @@ describe('negative cases', () => { it('derives query cases from parameter bounds', () => { const r = paramCasesDetailed(demo.doc, op('GET /items'), { allowPath: true, allowOthers: true }); - expect(r.cases.map((c) => c.request?.params)).toEqual([{ limit: 'not-a-number' }, { limit: 0 }, { limit: 101 }]); + expect(r.cases.map((c) => c.request?.params)).toEqual([{ limit: 'not-a-number' }, { limit: 0 }, { limit: 101 }, { offset: 'not-a-number' }, { offset: -1 }, { tag: '' }, { tag: 'x'.repeat(31) }, { sort: '__not_in_enum__' }]); }); it('breaks exclusive bounds, minItems and query minLength, one rule per case', () => { diff --git a/tests/unit/coverage-report.test.ts b/tests/unit/coverage-report.test.ts index ef3965c..b1b2702 100644 --- a/tests/unit/coverage-report.test.ts +++ b/tests/unit/coverage-report.test.ts @@ -34,7 +34,7 @@ describe('stage 10: coverage report', () => { }); it('the demo API has exactly the expected gaps', async () => { - const r = await run('demo-api/openapi.yaml', undefined, 'demo-api/scenarios.json'); + const r = await run('demo-api/openapi.yaml', 'demo-api/deps.json', 'demo-api/scenarios.json'); expect(summarize(r.coverage)).toEqual(JSON.parse(await readFile('demo-api/expected-gaps.json', 'utf8'))); }); diff --git a/tests/unit/coverage.test.ts b/tests/unit/coverage.test.ts index 1335d5f..eae46ab 100644 --- a/tests/unit/coverage.test.ts +++ b/tests/unit/coverage.test.ts @@ -32,7 +32,7 @@ const idsIn = (text: string) => [...text.matchAll(/(?:description: |caseId: )'([ describe('stage 2: one case ID per physical test', () => { const withSort = () => { const d = parse(stringify(demo.doc)); - d.paths['/items'].get.parameters.push({ name: 'sort', in: 'query', required: false, schema: { type: 'string', enum: ['asc', 'desc', 'asc'] } }); + d.paths['/items'].get.parameters.push({ name: 'order', in: 'query', required: false, schema: { type: 'string', enum: ['asc', 'desc', 'asc'] } }); d.paths['/items'].get.parameters.push({ name: 'flag', in: 'query', required: false, schema: { enum: [true, 'true', 1] } }); return d; }; @@ -42,7 +42,7 @@ describe('stage 2: one case ID per physical test', () => { const text = await read('items/get/functional.spec.ts'); const uid = operationUid('GET', '/items'); for (const v of ['asc', 'desc', 'true', '1']) { - const loc = v === 'asc' || v === 'desc' ? `request.query#/sort/${v}` : `request.query#/flag/${v}`; + const loc = v === 'asc' || v === 'desc' ? `request.query#/order/${v}` : `request.query#/flag/${v}`; expect(text).toContain(`'ata:${uid}:functional:positive:${loc}:accepted-value'`); } expect(text.match(/accepts documented flag=/g)).toHaveLength(2); // true and "true" are one value @@ -73,21 +73,21 @@ describe('stage 2: one case ID per physical test', () => { it('accepted-value: a value the spec does not document is an invalid location', () => { const d = withSort(); const uid = operationUid('GET', '/items'); - const id = `ata:${uid}:functional:positive:request.query#/sort/random:accepted-value`; + const id = `ata:${uid}:functional:positive:request.query#/order/random:accepted-value`; const parsed = parseCaseId(id); expect(parsed.ok).toBe(true); const reg = { schemaVersion: 1, caseRuleVocabularyVersion: 2, operations: { [uid]: { method: 'GET', path: '/items', normalizedPath: '/items' } }, cases: { [id]: (parsed as any).parts }, scenarios: {}, externalIdAliases: {}, externalScenarioIdAliases: {} }; expect(validateRegistry(canonicalJson(reg), normalizeSpec(stringify(d), 'x')).errors.map((e) => e.code)).toEqual(['INVALID_CASE_LOCATION']); - expect(parseCaseId(`ata:${uid}:functional:positive:request.query#/sort:accepted-value`).ok).toBe(false); // needs a value - expect(parseCaseId(`ata:${uid}:contract:negative:request.query#/sort/asc:enum`).ok).toBe(false); // constraint rules: one segment + expect(parseCaseId(`ata:${uid}:functional:positive:request.query#/order:accepted-value`).ok).toBe(false); // needs a value + expect(parseCaseId(`ata:${uid}:contract:negative:request.query#/order/asc:enum`).ok).toBe(false); // constraint rules: one segment }); it('a case the generator no longer produces becomes a tombstone; producing it again reactivates it', async () => { const { dir } = await gen(withSort()); const uid = operationUid('GET', '/items'); - const id = `ata:${uid}:functional:positive:request.query#/sort/desc:accepted-value`; + const id = `ata:${uid}:functional:positive:request.query#/order/desc:accepted-value`; const without = withSort(); - without.paths['/items'].get.parameters.find((p: any) => p.name === 'sort').schema.enum = ['asc']; + without.paths['/items'].get.parameters.find((p: any) => p.name === 'order').schema.enum = ['asc']; await generate({ ...demo, doc: without } as any, buildCatalog(without), { outDir: dir, version: 'test' }); const reg1 = JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')); expect(reg1.cases[id].status).toBe('retired'); From 6e9ecc8626096be695a69a40d962b1ea4c81d6b1 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 23:10:22 +0100 Subject: [PATCH 2/6] feat(collections): shared environments, found on Toolshop - "strategy": "read-only" in a collection mapping: no records are created for the checks even when a create is confirmed; - page-number paging with a fixed page size (no size parameter); - read-only checks of a public list go through publicApi, never a login; - read-only filter tests take up to 5 values from the list and require the filtered result to be a subset of the unfiltered list (re-read once); - a sort case ID may carry a reviewed value the spec does not enumerate. The subset check catches the defect of Toolshop's deliberately defective build (by_brand=1 returns rentals 27-29 the list never shows) and passes on the regular build, in TypeScript and Python. Demo fault injection stays 6/6. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/SUPPORT_MATRIX.md | 8 +++- src/cases/validate.ts | 2 + src/contract/contract.py | 7 +++ src/fixtures/capture.ts | 2 +- src/fixtures/fixtures.ts | 5 ++- src/generate/collection-render.ts | 73 ++++++++++++++++++++----------- src/generate/collection-tests.ts | 8 +++- src/generate/collection.ts | 16 +++++-- src/generate/templates.ts | 7 +++ tests/unit/collection.test.ts | 28 ++++++++++++ 11 files changed, 123 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d217ce5..5901bfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - **`maintain`:** spec diff → deterministic regeneration → registry and manifest validation → one Draft PR per suite with a summary (changed operations, files and cases, expectations old → new, fixtures, stale reviewed configuration, gaps before → after). Never merges; no PR when validation fails or nothing changed. - **Fault injection:** the demo API simulates six list defects (`DEMO_FAULT`); `scripts/mutation-check.ts` runs a generated suite against each, and CI requires 6/6 detected in TypeScript and Python. The previous generator detected 0/6. - Demo API: `offset`, `tag` and `sort` on `GET /items`; two reference items tagged `catalog` (the approved demo fixture). +- **Shared environments (found on Toolshop):** `"strategy": "read-only"` in a collection mapping; page-number paging with a fixed page size; read-only checks of a public list go through `publicApi` (no login); read-only filter tests take up to 5 values from the list and require the filtered result to be a subset of the unfiltered list, which catches the rental leak of Toolshop's defective build; a `sort` case ID may carry a reviewed value the spec does not enumerate. - Fixes: a GET of a single resource with an array field is no longer reported as an unconfigured collection; hand-written `_support/api/*Api.ts` stay in the generation manifest after the first run. - **Coverage completeness** (see docs/SUPPORT_MATRIX.md): diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 68b8787..510693f 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -147,19 +147,23 @@ A list operation is tested deeply only from a reviewed `collection` mapping in t } ``` +Page-number paging: `{ "style": "page", "pageParam": "page", "sizeParam": "per_page" }`, or, when the API fixes the size and has no size parameter, `{ "style": "page", "pageParam": "page", "size": 9 }`. `"strategy": "read-only"` forbids creating records for these checks even when a create is confirmed (shared environments). Sort values come from the reviewed mapping; the spec can only rule one out with an `enum`. + Strategy per list operation (recorded in `coverage-gaps.json` → `collection.strategy` / `strategies` / `reasons`): | Strategy | When | What it checks | |---|---|---| | A · create & verify | confirmed create + delete; an isolating filter whose field can carry a unique marker | the test creates its own records (marker in the filter field), reads only them, removes them in `finally`; non-trivial datasets: 2 records for a filter (one must be left out), 3 with distinct values created out of order for a sort, page size + 1 for paging | | B · approved fixtures | `--fixtures ` holds `.json` approved by a person | every approved element is listed, each field by policy (`exact`, `tolerance:`, `schema` = present, `ignore`); `exhaustive` = nothing else | -| C · read-only | no confirmed create / cleanup or no isolating filter | the same properties on existing data; a test without enough data is skipped with the reason | +| C · read-only | no confirmed create / cleanup, no isolating filter, or `"strategy": "read-only"` | the same properties on existing data; filters with up to 5 values that occur in the list, each result also a subset of the unfiltered list (re-read once, shared data moves); a test without enough data is skipped with the reason | | contract-only | no mapping | schema and status only; the gap says what is missing | | Assertion | State | Notes | |---|---|---| | created resource is listed (`collection-contains`) with its persisted fields | ✅ | strategy A; field policies | | filter returns the match and leaves out the non-match, all results match (`filter`) | ✅ | `equals` / `contains`; enum filters with an isolating marker | +| a filter only narrows: no resource the unfiltered list does not show (`filter`, read-only) | ✅ | values that occur in the list only: a value that only hidden resources have cannot be reached read-only | +| range filters (`between=price,10,30`), boolean flags with a default scope (`is_rental`) | ❌ | not mapped yet | | sort order (`sort`) | ✅ | one case per documented sort value; plain comparison (code points / numbers): the API must document that order | | page size, no duplicates across pages, union holds every record (`pagination`) | ✅ | offset and page/size styles; cursor paging ❌ (not yet) | | uniqueness (`unique`) | ✅ | | @@ -168,6 +172,8 @@ Strategy per list operation (recorded in `coverage-gaps.json` → `collection.st | bounded polling | ✅ | only with `consistency`; never longer than `pollTimeoutMs` (≤ 60 s); otherwise one read | | fixture capture / refresh | ✅ | `fixtures capture` writes candidates only; `fixtures refresh --draft-pr` proposes a candidate in one Draft PR per operation; approved files are never written by the agent | +Defect detection on a real API: Toolshop's deliberately defective build (`api-with-bugs.practicesoftwaretesting.com`) returns rental products for `by_brand=1` that its product list never shows. The read-only `by_brand` test fails on it (`by_brand=1 returns resources the unfiltered collection does not show: 27, 28, 29`) and passes on the regular build, in TypeScript and Python. `by_category=12` has the same defect but only rentals carry that category, so a read-only test cannot reach it. + Defect detection on the demo API (`scripts/mutation-check.ts`, TypeScript and Python identical): | Injected defect (`DEMO_FAULT`) | Previous generator (65 tests) | Collection tests | diff --git a/src/cases/validate.ts b/src/cases/validate.ts index a0d5db9..6079ecf 100644 --- a/src/cases/validate.ts +++ b/src/cases/validate.ts @@ -198,6 +198,8 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine if (rawValue !== undefined) { // accepted-value: the value must be one the spec documents for this parameter. const value = String(decodeSegment(rawValue)); + // sort: the value comes from the reviewed collection mapping; the spec can only rule it out with an enum. + if (rule === 'sort' && !Array.isArray(p.schema?.enum) && p.schema?.const === undefined) return undefined; const allowed = Array.isArray(p.schema?.enum) ? p.schema.enum.map(String) : p.schema?.const !== undefined ? [String(p.schema.const)] : boundaryValues(p.schema).map(String); return allowed.includes(value) ? undefined : bad(`"${value}" is not a documented value or valid limit of ${m[1]} "${name}"`); } diff --git a/src/contract/contract.py b/src/contract/contract.py index d5199c5..53f7bd4 100644 --- a/src/contract/contract.py +++ b/src/contract/contract.py @@ -122,6 +122,13 @@ def ok(i: Any) -> bool: assert not bad, f"{len(bad)} element(s) do not match {ptr} {match} {value}" +def expect_subset_of(items: list, base: list, id_ptr: str, what: str) -> None: + """A filtered result holds only resources the unfiltered collection shows (a filter narrows, never adds).""" + known = {_id_of(i, id_ptr) for i in base} + extra = [_id_of(i, id_ptr) for i in items if _id_of(i, id_ptr) not in known] + assert not extra, f"{what} returns resources the unfiltered collection does not show: {extra}" + + def expect_unique_by(items: list, ptr: str) -> None: seen, dups = set(), [] for i in items: diff --git a/src/fixtures/capture.ts b/src/fixtures/capture.ts index f1653a6..4098057 100644 --- a/src/fixtures/capture.ts +++ b/src/fixtures/capture.ts @@ -62,7 +62,7 @@ export async function captureFixture(o: CaptureOptions): Promise u.searchParams.set(page.limitParam, String(size)); } else if (page?.style === 'page') { u.searchParams.set(page.pageParam, String(i + (page.firstPage ?? 1))); - u.searchParams.set(page.sizeParam, String(size)); + if (page.sizeParam !== undefined) u.searchParams.set(page.sizeParam, String(size)); } return u; }; diff --git a/src/fixtures/fixtures.ts b/src/fixtures/fixtures.ts index 1d89aad..cf6e779 100644 --- a/src/fixtures/fixtures.ts +++ b/src/fixtures/fixtures.ts @@ -37,7 +37,7 @@ export interface Fixture { policies?: Record; default?: 'exact' | 'schema' | 'ignore'; exhaustive?: boolean; - page?: { style: 'offset'; offsetParam: string; limitParam: string; size?: number; maxPages?: number } | { style: 'page'; pageParam: string; sizeParam: string; firstPage?: number; size?: number; maxPages?: number }; + page?: { style: 'offset'; offsetParam: string; limitParam: string; size?: number; maxPages?: number } | { style: 'page'; pageParam: string; sizeParam?: string; firstPage?: number; size?: number; maxPages?: number }; expected: unknown[]; /** Capture metadata (candidates only; kept when a candidate is approved). */ captured?: { at: string; from: string }; @@ -71,7 +71,8 @@ export function validateFixture(doc: OpenApiDoc, ops: Operation[], f: Fixture): const missing = op.params.filter((p) => p.required && p.in !== 'header' && !(p.in === 'query' && f.query && p.name in f.query) && p.knownValue === undefined); if (missing.length) errors.push(`${op.key} needs ${missing.map((p) => `${p.in} "${p.name}"`).join(', ')}`); if (f.page) { - const names = f.page.style === 'offset' ? [f.page.offsetParam, f.page.limitParam] : f.page.style === 'page' ? [f.page.pageParam, f.page.sizeParam] : []; + const names = f.page.style === 'offset' ? [f.page.offsetParam, f.page.limitParam] : f.page.style === 'page' ? [f.page.pageParam, ...(f.page.sizeParam !== undefined ? [f.page.sizeParam] : [])] : []; + if (f.page.style === 'page' && f.page.sizeParam === undefined && !(Number.isInteger(f.page.size) && f.page.size! > 0)) errors.push('page style "page" without "sizeParam" needs the fixed page "size"'); if (!names.length) errors.push('page style is offset or page'); for (const n of names) if (!op.params.some((p) => p.in === 'query' && p.name === n)) errors.push(`page parameter "${n}" is not a query parameter of ${op.key}`); } diff --git a/src/generate/collection-render.ts b/src/generate/collection-render.ts index d7993c3..ae22126 100644 --- a/src/generate/collection-render.ts +++ b/src/generate/collection-render.ts @@ -2,7 +2,7 @@ import type { Operation } from '../types.js'; import { apiCall } from './api-objects.js'; import { requiredRequest } from './param-cases.js'; import type { CollectionPlan, CollectionTest } from './collection-tests.js'; -import { expectSuccess, hasFill, optionsWith, pathArgs, testOptions, type ChainPlan, type SuiteInput } from './templates.js'; +import { expectSuccess, hasFill, isPublic, optionsWith, pathArgs, testOptions, type ChainPlan, type SuiteInput } from './templates.js'; import type { LoadedFixture } from '../fixtures/fixtures.js'; import { assertSuccess, pathExpr, pyLit, pyName, pyRequired, resourceModule, withId } from './python.js'; @@ -18,6 +18,11 @@ export interface CollectionInput { } const js = (v: unknown) => JSON.stringify(v); + +/** Read-only checks of a public list operation are sent without credentials (as its success test), never through a login. */ +const roFixture = (op: Operation) => (isPublic(op) ? 'publicApi: api' : 'api'); +const pyRoFixture = (op: Operation) => (isPublic(op) ? 'anonymous_api' : 'api'); +const pyRoAlias = (op: Operation) => (isPublic(op) ? [' api = anonymous_api'] : []); const py = (v: unknown) => pyLit(v); const leaf = (ptr: string) => ptr.slice(1).replace(/~1/g, '/').replace(/~0/g, '~'); @@ -25,7 +30,7 @@ const leaf = (ptr: string) => ptr.slice(1).replace(/~1/g, '/').replace(/~0/g, '~ function pageEntries(plan: CollectionPlan, i: string, size: string, q: (s: string) => string): string | undefined { const p = plan.c.page; if (p?.style === 'offset') return `${q(p.offsetParam)}: ${i} * ${size}, ${q(p.limitParam)}: ${size}`; - if (p?.style === 'page') return `${q(p.pageParam)}: ${i} + ${p.firstPage ?? 1}, ${q(p.sizeParam)}: ${size}`; + if (p?.style === 'page') return `${q(p.pageParam)}: ${i} + ${p.firstPage ?? 1}` + (p.sizeParam !== undefined ? `, ${q(p.sizeParam)}: ${size}` : ''); return undefined; } @@ -39,7 +44,7 @@ const filterValue = (t: CollectionTest, which: 'a' | 'b', lang: 'ts' | 'py') => /* ------------------------------------------------------------------ TypeScript */ export const tsCollectionImports = (suite: 'functional' | 'scenario') => [ - 'itemsOf', 'expectContains', 'expectFields', 'poll', 'readPointer', 'withValue', + 'itemsOf', 'expectContains', 'expectFields', 'poll', 'readPointer', 'withValue', ...(suite === 'functional' ? ['expectSubsetOf'] : []), ...(suite === 'functional' ? ['expectNotContains', 'expectAllMatch', 'expectUniqueBy', 'expectSortedBy', 'expectPageSize', 'expectNoDuplicateAcrossPages'] : ['expectNotContains']), ]; @@ -156,13 +161,19 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] } else if (t.kind === 'filter') { const f = t.filter!; L.push( - ` test(${js(t.title)}, ${opts}, async ({ api }) => {`, - ` const all = await listAll(api, {});`, - ` const value = all.flatMap((i) => { const v = readPointer(i, ${js(f.field)}); return ${f.match === 'contains' ? 'Array.isArray(v) ? v : []' : 'v === undefined || v === null ? [] : [v]'}; })[0];`, - ` test.skip(value === undefined, ${js(`no existing resource has a value in ${f.field} to filter by (read-only check)`)});`, - ` const items = await listAll(api, { ${js(f.param)}: value });`, - ` expect(items.length, 'the filter finds the resource the value came from').toBeGreaterThan(0);`, - ` expectAllMatch(items, ${js(f.field)}, ${js(f.match)}, value);`, + ` test(${js(t.title)}, ${opts}, async ({ ${roFixture(s.op)} }) => {`, + ` let all = await listAll(api, {});`, + ` // Up to 5 different values that existing resources have: each must find them, and only within the list.`, + ` const values = [...new Map(all.flatMap((i) => { const v = readPointer(i, ${js(f.field)}); return ${f.match === 'contains' ? 'Array.isArray(v) ? v : []' : 'v === undefined || v === null ? [] : [v]'}; }).map((v) => [String(v), v])).values()].slice(0, 5);`, + ` test.skip(!values.length, ${js(`no existing resource has a value in ${f.field} to filter by (read-only check)`)});`, + ` for (const value of values) {`, + ` const items = await listAll(api, { ${js(f.param)}: value as string });`, + ` expect(items.length, 'the filter finds the resources the value ' + String(value) + ' came from').toBeGreaterThan(0);`, + ` expectAllMatch(items, ${js(f.field)}, ${js(f.match)}, value);`, + ` // A filter narrows the list: a resource the unfiltered list does not show must not appear (re-read once: shared data moves).`, + ` if (items.some((i) => !all.some((a) => String(readPointer(a, ID)) === String(readPointer(i, ID))))) all = await listAll(api, {});`, + ` expectSubsetOf(items, all, ID, ${js(`${f.param}=`)} + String(value));`, + ` }`, ` });`, '', ); @@ -176,7 +187,7 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] } else if (t.kind === 'sort') { const so = t.sort!; L.push( - ` test(${js(t.title)}, ${opts}, async ({ api }) => {`, + ` test(${js(t.title)}, ${opts}, async ({ ${roFixture(s.op)} }) => {`, ` const items = await listAll(api, { ${js(so.param)}: ${js(so.value)} });`, ` test.skip(items.length < 2, 'fewer than 2 resources: the order cannot be checked (read-only check)');`, ` expectSortedBy(items, ${js(so.field)}, ${js(so.order)});`, @@ -195,7 +206,7 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] } else if (t.kind === 'pagination') { const ps = plan.pageSize; L.push( - ` test(${js(t.title)}, ${opts}, async ({ api }) => {`, + ` test(${js(t.title)}, ${opts}, async ({ ${roFixture(s.op)} }) => {`, ` const pages = await listPages(api, {}, ${ps});`, ` test.skip(pages.flat().length <= ${ps}, 'not more than one page of resources (read-only check)');`, ` for (const page of pages) expectPageSize(page, ${ps});`, @@ -210,7 +221,7 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] `expectUniqueBy(items, ${js(t.unique)});`, ])); } else { - L.push(` test(${js(t.title)}, ${opts}, async ({ api }) => {`, ` expectUniqueBy(await listAll(api, {}), ${js(t.unique)});`, ` });`, ''); + L.push(` test(${js(t.title)}, ${opts}, async ({ ${roFixture(s.op)} }) => {`, ` expectUniqueBy(await listAll(api, {}), ${js(t.unique)});`, ` });`, ''); } }); return L; @@ -267,7 +278,7 @@ export function tsLifecycle(s: SuiteInput, ci: CollectionInput): string[] { /* ------------------------------------------------------------------ Python */ -const PY_IMPORTS = 'from contract import expect_all_match, expect_contains, expect_fields, expect_no_duplicate_across_pages, expect_not_contains, expect_page_size, expect_sorted_by, expect_unique_by, items_of, poll, with_value # noqa: F401'; +const PY_IMPORTS = 'from contract import expect_all_match, expect_contains, expect_fields, expect_no_duplicate_across_pages, expect_not_contains, expect_page_size, expect_sorted_by, expect_subset_of, expect_unique_by, items_of, poll, with_value # noqa: F401'; export function pyCollectionPrelude(s: SuiteInput, ci: CollectionInput): string[] { const { plan } = ci; @@ -408,17 +419,25 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] const values = f.match === 'contains' ? 'v if isinstance(v, list) else []' : '[] if v is None else [v]'; L.push( mark, - `def ${nameOf(`test_filter_${f.param}_returns_only_matching`)}(api):`, + `def ${nameOf(`test_filter_${f.param}_returns_only_matching`)}(${pyRoFixture(s.op)}):`, + ...pyRoAlias(s.op), ' candidates = []', ' for item in _list_all(api, {}):', ` v = read_pointer(item, ${py(f.field)})`, ` candidates.extend(${values})`, ' if not candidates:', ` pytest.skip(${py(`no existing resource has a value in ${f.field} to filter by (read-only check)`)})`, - ' value = candidates[0]', - ` found = _list_all(api, {${py(f.param)}: value})`, - ' assert found, "the filter finds the resource the value came from"', - ` expect_all_match(found, ${py(f.field)}, ${py(f.match)}, value)`, + ' base = _list_all(api, {})', + ' values = list({str(v): v for v in candidates}.values())[:5]', + ' for value in values:', + ` found = _list_all(api, {${py(f.param)}: value})`, + ' assert found, f"the filter finds the resources the value {value} came from"', + ` expect_all_match(found, ${py(f.field)}, ${py(f.match)}, value)`, + ' # A filter narrows the list: a resource the unfiltered list does not show must not appear (re-read once).', + ' known = {str(read_pointer(i, ID)) for i in base}', + ' if any(str(read_pointer(i, ID)) not in known for i in found):', + ' base = _list_all(api, {})', + ` expect_subset_of(found, base, ID, ${py(`${f.param}=`)} + str(value))`, '', '', ); @@ -434,7 +453,8 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] const so = t.sort!; L.push( mark, - `def ${nameOf(`test_sort_${so.param}_${so.value.replace(/^-/, 'desc_')}`)}(api):`, + `def ${nameOf(`test_sort_${so.param}_${so.value.replace(/^-/, 'desc_')}`)}(${pyRoFixture(s.op)}):`, + ...pyRoAlias(s.op), ` found = _list_all(api, {${py(so.param)}: ${py(so.value)}})`, ' if len(found) < 2:', ' pytest.skip("fewer than 2 resources: the order cannot be checked (read-only check)")', @@ -457,7 +477,8 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] const ps = plan.pageSize; L.push( mark, - `def ${nameOf('test_pages_have_requested_size_and_never_repeat')}(api):`, + `def ${nameOf('test_pages_have_requested_size_and_never_repeat')}(${pyRoFixture(s.op)}):`, + ...pyRoAlias(s.op), ` pages = _list_pages(api, {}, ${ps})`, ` if sum(len(p) for p in pages) <= ${ps}:`, ' pytest.skip("not more than one page of resources (read-only check)")', @@ -474,7 +495,7 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] `expect_unique_by(found, ${py(t.unique)})`, ])); } else { - L.push(mark, `def ${nameOf(`test_unique_by_${leaf(t.unique!)}`)}(api):`, ` expect_unique_by(_list_all(api, {}), ${py(t.unique)})`, '', ''); + L.push(mark, `def ${nameOf(`test_unique_by_${leaf(t.unique!)}`)}(${pyRoFixture(s.op)}):`, ...pyRoAlias(s.op), ` expect_unique_by(_list_all(api, {}), ${py(t.unique)})`, '', ''); } }); return L; @@ -533,8 +554,9 @@ function fixturePage(f: LoadedFixture, i: string, q: (s: string) => string): { e const p = f.fixture.page; const size = p?.size ?? 50; const maxPages = Math.min(p?.maxPages ?? 20, 50); + if (p?.style === 'page' && p.sizeParam === undefined) return { entries: `${q(p.pageParam)}: ${i} + ${p.firstPage ?? 1}`, size, maxPages }; if (p?.style === 'offset') return { entries: `${q(p.offsetParam)}: ${i} * ${size}, ${q(p.limitParam)}: ${size}`, size, maxPages }; - if (p?.style === 'page') return { entries: `${q(p.pageParam)}: ${i} + ${p.firstPage ?? 1}, ${q(p.sizeParam)}: ${size}`, size, maxPages }; + if (p?.style === 'page') return { entries: `${q(p.pageParam)}: ${i} + ${p.firstPage ?? 1}, ${q(p.sizeParam!)}: ${size}`, size, maxPages }; return { size, maxPages }; } @@ -554,7 +576,7 @@ export function tsFixtureTest(s: SuiteInput, f: LoadedFixture): string[] { const pg = fixturePage(f, 'i', js); const call = (extra: string) => `await ${apiCall(ref, 'api', pathArgs(op, ref), `{ params: { ...${js(req)}, ...approved.query, ${extra} } as Record }`)}`; return [ - ` test(${js(`matches the approved fixture ${fixturePath(f)}`)}, ${testOptions('positive', s.ids?.functional.fixture)}, async ({ api }) => {`, + ` test(${js(`matches the approved fixture ${fixturePath(f)}`)}, ${testOptions('positive', s.ids?.functional.fixture)}, async ({ ${roFixture(s.op)} }) => {`, ` const items: unknown[] = [];`, ...(pg.entries ? [ @@ -584,7 +606,8 @@ export function pyFixtureTest(s: SuiteInput, f: LoadedFixture): string[] { '', '', withId('@pytest.mark.positive', s.ids?.functional.fixture), - 'def test_matches_approved_fixture(api):', + `def test_matches_approved_fixture(${pyRoFixture(s.op)}):`, + ...pyRoAlias(s.op), ` """Approved fixture ${fixturePath(f)} (copied to _support/approved)."""`, ` fixture = json.loads((pathlib.Path(__file__).resolve().parents[2] / "_support" / "approved" / ${py(fixtureModule(f) + '.json')}).read_text(encoding="utf-8"))`, ' items = []', diff --git a/src/generate/collection-tests.ts b/src/generate/collection-tests.ts index fdb3668..65d9a39 100644 --- a/src/generate/collection-tests.ts +++ b/src/generate/collection-tests.ts @@ -52,6 +52,8 @@ export function planCollectionTests(doc: OpenApiDoc, c: ResolvedCollection, x: { const gaps: CoverageGap[] = []; const tests: CollectionTest[] = []; const top = (ptr: string) => ptr.split('/').length === 2; // controlled data sets top-level fields only + // "strategy": "read-only" in the reviewed mapping: nothing is created for these checks, even with a confirmed create. + if (c.strategy === 'read-only') x = { ...x, canCreate: false, canUpdate: false, canDelete: false }; const createField = (ptr: string) => (x.canCreate && x.createSchema && top(ptr) ? schemaAt(doc, x.createSchema, ptr) : undefined); const markerFilter = (f: Filter) => { const s = createField(f.field); @@ -61,12 +63,14 @@ export function planCollectionTests(doc: OpenApiDoc, c: ResolvedCollection, x: { const filters = (c.filters ?? []).filter((f, i, all) => all.findIndex((g) => g.param === f.param) === i); const iso = filters.find(markerFilter); + const fixed = c.page?.style === 'page' && c.page.sizeParam === undefined ? c.page.size : undefined; const limitParam = c.page?.style === 'offset' ? c.page.limitParam : c.page?.style === 'page' ? c.page.sizeParam : undefined; const limitSchema: any = limitParam ? c.op.params.find((p) => p.name === limitParam)?.schema : undefined; const minSize = typeof limitSchema?.minimum === 'number' ? limitSchema.minimum : 1; const maxSize = typeof limitSchema?.maximum === 'number' ? limitSchema.maximum : 50; - const walkSize = Math.max(minSize, Math.min(maxSize, 50)); - const pageSize = Math.min(Math.max(2, minSize), maxSize); + // A fixed page size (no size parameter) is the only size there is, for walking and for the paging test. + const walkSize = fixed ?? Math.max(minSize, Math.min(maxSize, 50)); + const pageSize = fixed ?? Math.min(Math.max(2, minSize), maxSize); if (x.canCreate) tests.push({ kind: 'listed', title: 'a created resource is listed with the fields it was created with', mode: 'controlled' }); else gaps.push({ code: 'MISSING_CLEANUP', location: 'operation', reason: `${c.op.key}: membership of a created resource needs a confirmed create with cleanup (strategy A); only read-only checks run` }); diff --git a/src/generate/collection.ts b/src/generate/collection.ts index 650256f..4692d15 100644 --- a/src/generate/collection.ts +++ b/src/generate/collection.ts @@ -15,8 +15,14 @@ import type { CoverageGap } from './body-cases.js'; * "filters": [{ "param": "tag", "field": "/tags", "match": "contains" }], * "sorts": [{ "param": "sort", "value": "price", "field": "/price", "order": "asc" }], * "page": { "style": "offset", "offsetParam": "offset", "limitParam": "limit", "maxPages": 20 }, + * or { "style": "page", "pageParam": "page", "sizeParam": "per_page" } or, when the API fixes the size, + * { "style": "page", "pageParam": "page", "size": 9 } (no size parameter: the reviewed fixed page size) + * or { "style": "page", "pageParam": "page", "sizeParam": "per_page" } or, when the API fixes the size, + * { "style": "page", "pageParam": "page", "size": 9 } (no size parameter: the reviewed fixed page size) * "consistency": { "pollTimeoutMs": 5000, "pollIntervalMs": 250 }, eventual consistency, bounded polling - * "deletedDisappears": true a deleted resource is guaranteed to leave the list + * "deletedDisappears": true, a deleted resource is guaranteed to leave the list + * "strategy": "read-only" never create records for these checks (shared environments), even with a + * confirmed create; the checks then run on existing data (strategy C) * } */ @@ -30,9 +36,10 @@ export interface CollectionConfig { unique?: string[]; filters?: { param: string; field: string; match: 'equals' | 'contains' }[]; sorts?: { param: string; value: string; field: string; order: 'asc' | 'desc' }[]; - page?: { style: 'offset'; offsetParam: string; limitParam: string; maxPages?: number } | { style: 'page'; pageParam: string; sizeParam: string; firstPage?: number; maxPages?: number }; + page?: { style: 'offset'; offsetParam: string; limitParam: string; maxPages?: number } | { style: 'page'; pageParam: string; sizeParam?: string; size?: number; firstPage?: number; maxPages?: number }; consistency?: { pollTimeoutMs: number; pollIntervalMs: number }; deletedDisappears?: boolean; + strategy?: 'read-only'; } export interface ResolvedCollection extends CollectionConfig { @@ -112,9 +119,12 @@ export function resolveCollection(doc: OpenApiDoc, ops: Operation[], cfg: Collec query(cfg.page.limitParam, 'limit parameter'); } else if (cfg.page.style === 'page') { query(cfg.page.pageParam, 'page parameter'); - query(cfg.page.sizeParam, 'size parameter'); + if (cfg.page.sizeParam !== undefined) query(cfg.page.sizeParam, 'size parameter'); + else if (!(Number.isInteger(cfg.page.size) && cfg.page.size! > 0)) errors.push('collection: page style "page" needs "sizeParam", or the fixed page size "size" the API uses'); } else errors.push('collection: page style is offset or page (cursor is not supported yet)'); } + if (cfg.strategy !== undefined && cfg.strategy !== 'read-only') errors.push('collection: "strategy" can only be "read-only"'); + if (cfg.strategy !== undefined && cfg.strategy !== 'read-only') errors.push('collection: "strategy" can only be "read-only"'); const c = cfg.consistency; if (c && !(c.pollTimeoutMs > 0 && c.pollTimeoutMs <= 60_000 && c.pollIntervalMs > 0 && c.pollIntervalMs <= c.pollTimeoutMs)) errors.push('collection: consistency needs 0 < pollIntervalMs <= pollTimeoutMs <= 60000'); if (errors.length) return { errors }; diff --git a/src/generate/templates.ts b/src/generate/templates.ts index 421d725..f7f009f 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -817,6 +817,13 @@ export function expectAllMatch(items: unknown[], ptr: string, match: 'equals' | expect(bad.length, bad.length + ' element(s) do not match ' + ptr + ' ' + match + ' ' + String(value)).toBe(0); } +/** A filtered result holds only resources the unfiltered collection shows (a filter narrows, never adds). */ +export function expectSubsetOf(items: unknown[], base: unknown[], idPtr: string, what: string): void { + const known = new Set(base.map((i) => idOf(i, idPtr))); + const extra = items.map((i) => idOf(i, idPtr)).filter((id) => !known.has(id)); + expect(extra, what + ' returns resources the unfiltered collection does not show').toEqual([]); +} + export function expectUniqueBy(items: unknown[], ptr: string): void { const seen = new Set(); const dups = items.map((i) => idOf(i, ptr)).filter((k) => (seen.has(k) ? true : (seen.add(k), false))); diff --git a/tests/unit/collection.test.ts b/tests/unit/collection.test.ts index e911676..def488e 100644 --- a/tests/unit/collection.test.ts +++ b/tests/unit/collection.test.ts @@ -146,3 +146,31 @@ describe('approved fixtures (strategy B)', () => { expect(d.changed).toEqual([{ id: JSON.stringify((approved.expected[1] as any).id), pointer: '/name', before: 'Catalog screwdriver', after: 'Renamed' }]); }); }); + +describe('shared environments (found on Toolshop)', () => { + it('"strategy": "read-only" never creates records, even with a confirmed create', () => { + const c = resolveCollection(demo.doc, ops, { ...cfg, strategy: 'read-only' }).collection!; + const p = planCollectionTests(demo.doc, c, { canCreate: true, createSchema, canUpdate: true, updatePayload: { name: 'x' }, canDelete: true }); + expect(p.tests.every((t) => t.mode === 'read-only')).toBe(true); + expect(p.lifecycle).toBe(false); + expect(resolveCollection(demo.doc, ops, { ...cfg, strategy: 'write' as any }).errors.join()).toContain('"strategy" can only be "read-only"'); + }); + + it('page-number paging with a fixed page size (no size parameter)', () => { + const fixed = { ...cfg, page: { style: 'page' as const, pageParam: 'offset', size: 9 } }; + const c = resolveCollection(demo.doc, ops, fixed).collection!; + const p = planCollectionTests(demo.doc, c, { canCreate: false, canUpdate: false, canDelete: false }); + expect([p.pageSize, p.walkSize]).toEqual([9, 9]); + expect(resolveCollection(demo.doc, ops, { ...cfg, page: { style: 'page', pageParam: 'offset' } }).errors.join()).toContain('fixed page size'); + }); + + it('a read-only filter test checks several values and that the filter only narrows the list', async () => { + const ro = { scenarios: [{ ...deps.scenarios[0], collection: { ...cfg, strategy: 'read-only' } }] }; + const dir = await mkdtemp(join(tmpdir(), 'ata-coll-')); + await generate(demo, ops, { outDir: dir, version: 'test', deps: ro }); + const text = await readFile(join(dir, 'items/get/functional.spec.ts'), 'utf8'); + expect(text).toContain('expectSubsetOf(items, all, ID'); + expect(text).toContain('.slice(0, 5)'); + expect(text).toContain('async ({ publicApi: api })'); // a public list is read without logging in + }); +}); From 038bf38d8198fbbfa5724a2081f0774af00f254c Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 23:37:12 +0100 Subject: [PATCH 3/6] feat(account): API_TEST_ACCOUNT=auto registers a test account only when the .env one is missing or refused The .env account is used while it works. When it is missing or its login is refused (401/403/422, e.g. the test environment reset its data), the agent registers one account before --run and the generated tests reuse it; a worker of a standalone run registers at most once. A working account never causes a registration; .env is never changed. Verified on the demo API: wrong password -> 1 registration in an agent run, 1 per worker standalone; right password -> none. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/GUIDE.md | 3 ++- src/audit/account.ts | 12 +++++---- src/cli.ts | 24 +++++++++++++++++- src/contract/fixtures.ts | 51 +++++++++++++++++++++++++++++++++----- tests/unit/account.test.ts | 3 ++- 6 files changed, 80 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5901bfe..083133c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - **Fault injection:** the demo API simulates six list defects (`DEMO_FAULT`); `scripts/mutation-check.ts` runs a generated suite against each, and CI requires 6/6 detected in TypeScript and Python. The previous generator detected 0/6. - Demo API: `offset`, `tag` and `sort` on `GET /items`; two reference items tagged `catalog` (the approved demo fixture). - **Shared environments (found on Toolshop):** `"strategy": "read-only"` in a collection mapping; page-number paging with a fixed page size; read-only checks of a public list go through `publicApi` (no login); read-only filter tests take up to 5 values from the list and require the filtered result to be a subset of the unfiltered list, which catches the rental leak of Toolshop's defective build; a `sort` case ID may carry a reviewed value the spec does not enumerate. +- **Test account `auto`:** `API_TEST_ACCOUNT=auto` / `--test-account auto` uses the `.env` account and registers a new one only when it is missing or refused (401 / 403 / 422), e.g. after Toolshop reset its data; the agent registers once before `--run` and the generated tests reuse that account; a worker of a standalone run registers at most once. `.env` is never changed. - Fixes: a GET of a single resource with an array field is no longer reported as an unconfigured collection; hand-written `_support/api/*Api.ts` stay in the generation manifest after the first run. - **Coverage completeness** (see docs/SUPPORT_MATRIX.md): diff --git a/docs/GUIDE.md b/docs/GUIDE.md index f137baa..9f4d63c 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -71,6 +71,7 @@ API_PASSWORD=... Before `generate` and `audit` log in, they ask: **Do you have a test account?** - **Yes** (`existing`): the credentials above are read from `.env`. +- **Auto** (`auto`, only with `API_TEST_ACCOUNT=auto` or `--test-account auto`): the account from `.env` while it works. Only when it is missing or its login is refused (401 / 403 / 422, e.g. the test environment reset its data) is a new one registered: by the agent before `--run` (the generated tests then use that one), or by a Playwright worker that hits the refusal (one per such worker). A working account never causes a registration, and `.env` is never changed. Needs `--allow-write` for the agent's registration. - **No** (`new`): **new accounts are registered on every run** and left on the server (nothing deletes them): the generated suite registers **one per Playwright worker** (the `testAccount` worker fixture in `_support/fixtures.ts`), so parallel workers never share user data; the agent registers one more only for its own `--probe/--schemathesis`. Emails (`api-test-@example.com`) and passwords are generated and kept in memory only. Needs `--allow-write`. Playwright starts a fresh worker after a failed test, and that worker registers its own account too. ``` @@ -78,7 +79,7 @@ API_REGISTER=POST /users/register API_REGISTER_BODY={"first_name":"Api","last_name":"Test","email":"${API_USER}","password":"${API_PASSWORD}"} ``` -`API_REGISTER_BODY` must use the same `${VAR}`s as `API_LOGIN_BODY`; `${UNIQUE}` is a per-run suffix for other unique fields. To skip the question (CI): `API_TEST_ACCOUNT=existing|new` or `--test-account existing|new`. Without a terminal and without the setting, an account in `.env` means `existing`; otherwise the run stops with an explanation. +`API_REGISTER_BODY` must use the same `${VAR}`s as `API_LOGIN_BODY`; `${UNIQUE}` is a per-run suffix for other unique fields. To skip the question (CI): `API_TEST_ACCOUNT=existing|new|auto` or `--test-account existing|new|auto`. Python suites support `existing` only (for now). Without a terminal and without the setting, an account in `.env` means `existing`; otherwise the run stops with an explanation. You need at least one of: a spec, a Postman collection, or existing tests. With none of them there is nothing to analyse. diff --git a/src/audit/account.ts b/src/audit/account.ts index 793306d..020487d 100644 --- a/src/audit/account.ts +++ b/src/audit/account.ts @@ -18,8 +18,8 @@ import { randomBytes } from 'node:crypto'; import { expandTemplate, loginConfig } from './login.js'; -export type AccountMode = 'existing' | 'new'; -export const ACCOUNT_MODES: AccountMode[] = ['existing', 'new']; +export type AccountMode = 'existing' | 'new' | 'auto'; +export const ACCOUNT_MODES: AccountMode[] = ['existing', 'new', 'auto']; /** ${VAR} names used by the login body (credentials of the test account). */ export function loginVars(env: NodeJS.ProcessEnv = process.env): string[] { @@ -35,8 +35,8 @@ export function missingLoginVars(env: NodeJS.ProcessEnv = process.env): string[] export function parseAccountMode(raw: string | undefined): AccountMode | undefined { const v = raw?.trim().toLowerCase(); if (!v) return undefined; - if (v === 'existing' || v === 'new') return v; - throw new Error(`API_TEST_ACCOUNT / --test-account must be "existing" or "new", got "${raw}".`); + if (v === 'existing' || v === 'new' || v === 'auto') return v; + throw new Error(`API_TEST_ACCOUNT / --test-account must be "existing", "new" or "auto", got "${raw}".`); } /** Text shown before the question: what each answer means, in particular that "new" registers an account every run. */ @@ -53,7 +53,9 @@ export function accountNotice(env: NodeJS.ProcessEnv = process.env): string { ' one per Playwright worker (parallel test process), plus one for --probe/--schemathesis.', ' They stay on the server; nothing deletes them.', ' Emails and passwords are generated and kept in memory for the run only (not saved to .env).', - ' Skip this question next time: API_TEST_ACCOUNT=existing|new in .env (npm run test:api reads it too), or --test-account.', + ' auto (API_TEST_ACCOUNT=auto) = the account from .env, and a new one only when it is missing or refused', + ' (e.g. the test environment was reset): no registration while the account works.', + ' Skip this question next time: API_TEST_ACCOUNT=existing|new|auto in .env (npm run test:api reads it too), or --test-account.', '', ].join('\n'); } diff --git a/src/cli.ts b/src/cli.ts index dd65385..78ab3c5 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -75,7 +75,7 @@ function common(cmd: Command) { .option('-o, --out ', 'output directory for reports', `reports/api-agent/${cmd.name()}`) .addOption(new Option('--fail-on ', 'exit non-zero on').choices(['mismatch', 'blocked', 'never']).default('mismatch')) .option('--schemathesis-bin ', 'path to the schemathesis executable') - .addOption(new Option('--test-account ', 'with API_LOGIN: use the account from .env (existing) or register a new one on every run (new). Default: API_TEST_ACCOUNT, else asked').choices(ACCOUNT_MODES)); + .addOption(new Option('--test-account ', 'with API_LOGIN: the account from .env (existing), a new one on every run (new), or the .env account and a new one only when it is refused (auto). Default: API_TEST_ACCOUNT, else asked').choices(ACCOUNT_MODES)); } async function load(location: string): Promise<{ spec: LoadedSpec; ops: Operation[] }> { @@ -119,6 +119,28 @@ async function prepareAccount(o: CommonOpts, agentLogin: boolean, suiteRun = fal } } process.env.API_TEST_ACCOUNT = mode; // the generated suite started by --run reads it too + if (mode === 'auto') { + // The account from .env while it works; a new one only when it is missing or refused (e.g. after a reset). + const missing = missingLoginVars(); + let why = missing.length ? `${missing.join(', ')} not set` : ''; + if (!why) { + try { + await applyLogin(o.baseUrl, log); + log('Test account: auto, the account from .env works (nothing registered).'); + return; + } catch (e) { + const status = /HTTP (\d+)/.exec((e as Error).message)?.[1]; + if (!status || !['401', '403', '422'].includes(status)) throw e; + why = `the account from .env is refused (HTTP ${status})`; + } + } + if (!o.allowWrite) throw new Error(`Test account: ${why}. Registering a new one writes to the API: add --allow-write (test environments only), or fix the account in .env.`); + checkRegisterConfig(); + const acc = await registerAccount(o.baseUrl); + log(`Test account: auto, ${why}: registered ${acc.label} (stays on the server). This run, and the generated tests it starts, use it; .env is not changed.`); + await applyLogin(o.baseUrl, log); + return; + } if (mode === 'existing') { const missing = missingLoginVars(); if (missing.length) throw new Error(`Test account: put its credentials into .env: ${missing.map((v) => `${v}=...`).join(', ')}. Or use --test-account new to register one on every run.`); diff --git a/src/contract/fixtures.ts b/src/contract/fixtures.ts index b8f1def..88de6f3 100644 --- a/src/contract/fixtures.ts +++ b/src/contract/fixtures.ts @@ -13,6 +13,9 @@ * - API_TEST_ACCOUNT=new: every Playwright WORKER registers its own NEW account through * API_REGISTER / API_REGISTER_BODY at the start of every run. Accounts are never deleted. * Generated email/password live in the worker's memory only. + * - API_TEST_ACCOUNT=auto: the account from .env; only when it is missing or its login is refused + * (401 / 403 / 422, e.g. the test environment was reset) does a worker register a new one, once, + * and log in with it. A working account never causes a registration. * The login happens lazily: a test that only uses publicApi never logs in. * Without API_LOGIN the static API_TOKEN from playwright.config (or none) is used unchanged. */ @@ -28,7 +31,7 @@ try { type Credentials = Record; export interface TestAccount { - mode: 'none' | 'existing' | 'new'; + mode: 'none' | 'existing' | 'new' | 'auto'; /** Values for the ${VAR}s of API_LOGIN_BODY. */ credentials: Credentials; /** Email-like identifier, for logs (never the password). */ @@ -63,6 +66,8 @@ async function resolveAccount(playwright: PlaywrightWorkerArgs['playwright'], ba if (!process.env.API_LOGIN) return { mode: 'none', credentials: {} }; const vars = loginVars(); const mode = (process.env.API_TEST_ACCOUNT ?? 'existing').trim().toLowerCase(); + // auto: whatever .env has; TokenSource registers a new account only if this one is missing or refused. + if (mode === 'auto') return { mode: 'auto', credentials: Object.fromEntries(vars.filter((v) => process.env[v]).map((v) => [v, process.env[v]!])) }; if (mode !== 'new') { if (mode !== 'existing') throw new Error(`API_TEST_ACCOUNT must be "existing" or "new", got "${mode}"`); const missing = vars.filter((v) => !process.env[v]); @@ -70,7 +75,12 @@ async function resolveAccount(playwright: PlaywrightWorkerArgs['playwright'], ba return { mode: 'existing', credentials: Object.fromEntries(vars.map((v) => [v, process.env[v]!])) }; } - // A new account for this worker: generated email/password fill the same ${VAR}s as the login body. + return registerNew(playwright, baseURL, worker); +} + +/** A new account for this worker: generated email/password fill the same ${VAR}s as the login body. */ +async function registerNew(playwright: PlaywrightWorkerArgs['playwright'], baseURL: string | undefined, worker: number): Promise { + const vars = loginVars(); const reg = splitRequest(process.env.API_REGISTER, 'API_REGISTER'); const template = process.env.API_REGISTER_BODY; if (!template) throw new Error('API_TEST_ACCOUNT=new needs API_REGISTER_BODY (use the same ${VAR}s as API_LOGIN_BODY)'); @@ -94,16 +104,45 @@ class TokenSource { private token?: string; private expiresAt = 0; - constructor(private readonly account: TestAccount) {} + private registered = false; + + constructor( + private account: TestAccount, + private readonly worker = 0, + ) {} async get(playwright: PlaywrightWorkerArgs['playwright'], baseURL: string | undefined): Promise { if (this.token && Date.now() < this.expiresAt - 30_000) return this.token; + if (this.account.mode === 'auto' && !this.registered) { + const missing = loginVars().filter((v) => !this.account.credentials[v]); + if (missing.length) await this.registerInstead(playwright, baseURL, `${missing.join(', ')} not set`); + else { + try { + return await this.login(playwright, baseURL); + } catch (e) { + const status = /answered (\d+)/.exec((e as Error).message)?.[1]; + if (!status || !['401', '403', '422'].includes(status)) throw e; + await this.registerInstead(playwright, baseURL, `the account from .env is refused (${status})`); + } + } + } + return this.login(playwright, baseURL); + } + + /** auto: one new account for this worker, used for the rest of the run. */ + private async registerInstead(playwright: PlaywrightWorkerArgs['playwright'], baseURL: string | undefined, why: string): Promise { + console.log(`[test-account] worker ${this.worker}: ${why}; registering a new account`); + this.account = await registerNew(playwright, baseURL, this.worker); + this.registered = true; + } + + private async login(playwright: PlaywrightWorkerArgs['playwright'], baseURL: string | undefined): Promise { const { method, path } = splitRequest(process.env.API_LOGIN, 'API_LOGIN'); const body = fill(process.env.API_LOGIN_BODY ?? '{}', { ...process.env, ...this.account.credentials }, 'API_LOGIN_BODY'); const ctx = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { accept: 'application/json' } }); try { const res = await ctx.fetch(path, { method, data: body }); - if (!res.ok()) throw new Error(`Login failed: ${method} /${path} answered ${res.status()} (${this.account.mode === 'new' ? 'freshly registered account' : 'check the test account in .env'})`); + if (!res.ok()) throw new Error(`Login failed: ${method} /${path} answered ${res.status()} (${this.account.mode === 'new' ? 'freshly registered account' : this.account.mode === 'auto' ? 'account from .env' : 'check the test account in .env'})`); const json = await res.json(); const pointer = process.env.API_TOKEN_POINTER || '/access_token'; const token = readPointer(json, pointer); @@ -127,8 +166,8 @@ export const test = base.extend<{ api: Apis; publicApi: Apis }, { testAccount: T { scope: 'worker' }, ], tokenSource: [ - async ({ testAccount }, use) => { - await use(new TokenSource(testAccount)); + async ({ testAccount }, use, workerInfo) => { + await use(new TokenSource(testAccount, workerInfo.workerIndex)); }, { scope: 'worker' }, ], diff --git a/tests/unit/account.test.ts b/tests/unit/account.test.ts index 5e5fef5..0f57f1e 100644 --- a/tests/unit/account.test.ts +++ b/tests/unit/account.test.ts @@ -17,8 +17,9 @@ describe('test account', () => { it('accepts only existing/new', () => { expect(parseAccountMode(' New ')).toBe('new'); + expect(parseAccountMode('auto')).toBe('auto'); expect(parseAccountMode('')).toBeUndefined(); - expect(() => parseAccountMode('maybe')).toThrow(/existing" or "new/); + expect(() => parseAccountMode('maybe')).toThrow(/"existing", "new" or "auto"/); }); it('says plainly that "no" registers an account on every run', () => { From 85d32fe4ff901466335ede046ef9d97f557d83e0 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 23:40:58 +0100 Subject: [PATCH 4/6] feat(account): one auto registration per run through a generated Playwright globalSetup Playwright starts a fresh worker after a failed test, so per-worker registration in auto mode registered an account per failure (4 for 3 failures on Toolshop). _support/global-setup.ts now settles the account once in the main process and hands the credentials to every worker through the environment (memory only). init adds it to playwright.config.ts when present. Verified on Toolshop: one registration for a run with failures and restarted workers. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/GUIDE.md | 2 +- src/contract/fixtures.ts | 28 ++++++++++++++++++++++++---- src/generate/generate.ts | 13 +++++++++++++ src/init.ts | 5 ++++- 5 files changed, 43 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 083133c..01cee81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ - **Fault injection:** the demo API simulates six list defects (`DEMO_FAULT`); `scripts/mutation-check.ts` runs a generated suite against each, and CI requires 6/6 detected in TypeScript and Python. The previous generator detected 0/6. - Demo API: `offset`, `tag` and `sort` on `GET /items`; two reference items tagged `catalog` (the approved demo fixture). - **Shared environments (found on Toolshop):** `"strategy": "read-only"` in a collection mapping; page-number paging with a fixed page size; read-only checks of a public list go through `publicApi` (no login); read-only filter tests take up to 5 values from the list and require the filtered result to be a subset of the unfiltered list, which catches the rental leak of Toolshop's defective build; a `sort` case ID may carry a reviewed value the spec does not enumerate. -- **Test account `auto`:** `API_TEST_ACCOUNT=auto` / `--test-account auto` uses the `.env` account and registers a new one only when it is missing or refused (401 / 403 / 422), e.g. after Toolshop reset its data; the agent registers once before `--run` and the generated tests reuse that account; a worker of a standalone run registers at most once. `.env` is never changed. +- **Test account `auto`:** `API_TEST_ACCOUNT=auto` / `--test-account auto` uses the `.env` account and registers a new one only when it is missing or refused (401 / 403 / 422), e.g. after Toolshop reset its data; the agent registers once before `--run` and the generated tests reuse that account; with the generated `_support/global-setup.ts` as Playwright's `globalSetup` (added by `init`), a standalone run decides once in the main process, so a run registers at most one account even when Playwright restarts workers after failures; without it, at most one per worker. `.env` is never changed. - Fixes: a GET of a single resource with an array field is no longer reported as an unconfigured collection; hand-written `_support/api/*Api.ts` stay in the generation manifest after the first run. - **Coverage completeness** (see docs/SUPPORT_MATRIX.md): diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 9f4d63c..269e81f 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -71,7 +71,7 @@ API_PASSWORD=... Before `generate` and `audit` log in, they ask: **Do you have a test account?** - **Yes** (`existing`): the credentials above are read from `.env`. -- **Auto** (`auto`, only with `API_TEST_ACCOUNT=auto` or `--test-account auto`): the account from `.env` while it works. Only when it is missing or its login is refused (401 / 403 / 422, e.g. the test environment reset its data) is a new one registered: by the agent before `--run` (the generated tests then use that one), or by a Playwright worker that hits the refusal (one per such worker). A working account never causes a registration, and `.env` is never changed. Needs `--allow-write` for the agent's registration. +- **Auto** (`auto`, only with `API_TEST_ACCOUNT=auto` or `--test-account auto`): the account from `.env` while it works. Only when it is missing or its login is refused (401 / 403 / 422, e.g. the test environment reset its data) is a new one registered: by the agent before `--run` (the generated tests then use that one), or, in a standalone Playwright run, once in `_support/global-setup.ts` (Playwright `globalSetup`; `init` adds it to `playwright.config.ts`), and every worker reuses that account, also the fresh worker Playwright starts after a failed test. Without the global setup each worker that hits the refusal registers one. A working account never causes a registration, and `.env` is never changed. Needs `--allow-write` for the agent's registration. - **No** (`new`): **new accounts are registered on every run** and left on the server (nothing deletes them): the generated suite registers **one per Playwright worker** (the `testAccount` worker fixture in `_support/fixtures.ts`), so parallel workers never share user data; the agent registers one more only for its own `--probe/--schemathesis`. Emails (`api-test-@example.com`) and passwords are generated and kept in memory only. Needs `--allow-write`. Playwright starts a fresh worker after a failed test, and that worker registers its own account too. ``` diff --git a/src/contract/fixtures.ts b/src/contract/fixtures.ts index 88de6f3..3880b4f 100644 --- a/src/contract/fixtures.ts +++ b/src/contract/fixtures.ts @@ -15,7 +15,9 @@ * Generated email/password live in the worker's memory only. * - API_TEST_ACCOUNT=auto: the account from .env; only when it is missing or its login is refused * (401 / 403 / 422, e.g. the test environment was reset) does a worker register a new one, once, - * and log in with it. A working account never causes a registration. + * and log in with it. A working account never causes a registration. With _support/global-setup.ts as + * Playwright's globalSetup this is decided ONCE per run in the main process, and every worker (also the + * fresh worker Playwright starts after a failed test) reuses that account: at most one registration per run. * The login happens lazily: a test that only uses publicApi never logs in. * Without API_LOGIN the static API_TOKEN from playwright.config (or none) is used unchanged. */ @@ -84,7 +86,7 @@ async function registerNew(playwright: PlaywrightWorkerArgs['playwright'], baseU const reg = splitRequest(process.env.API_REGISTER, 'API_REGISTER'); const template = process.env.API_REGISTER_BODY; if (!template) throw new Error('API_TEST_ACCOUNT=new needs API_REGISTER_BODY (use the same ${VAR}s as API_LOGIN_BODY)'); - const unique = `${Date.now().toString(36)}w${worker}${randomBytes(3).toString('hex')}`; + const unique = `${Date.now().toString(36)}${worker < 0 ? 'r' : `w${worker}`}${randomBytes(3).toString('hex')}`; const password = `Qa-${randomBytes(12).toString('base64url')}-7x!`; const credentials: Credentials = Object.fromEntries(vars.map((v) => [v, /pass/i.test(v) ? password : `api-test-${unique}@example.com`])); const ctx = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { accept: 'application/json' } }); @@ -96,7 +98,7 @@ async function registerNew(playwright: PlaywrightWorkerArgs['playwright'], baseU await ctx.dispose(); } const label = Object.entries(credentials).find(([k]) => !/pass/i.test(k))?.[1]; - console.log(`[test-account] worker ${worker}: registered new account ${label ?? ''} (stays on the server)`); + console.log(`[test-account] ${worker < 0 ? 'run' : `worker ${worker}`}: registered new account ${label ?? ''} (stays on the server)`); return { mode: 'new', credentials, label }; } @@ -131,11 +133,16 @@ class TokenSource { /** auto: one new account for this worker, used for the rest of the run. */ private async registerInstead(playwright: PlaywrightWorkerArgs['playwright'], baseURL: string | undefined, why: string): Promise { - console.log(`[test-account] worker ${this.worker}: ${why}; registering a new account`); + console.log(`[test-account] ${this.worker < 0 ? 'run' : `worker ${this.worker}`}: ${why}; registering a new account`); this.account = await registerNew(playwright, baseURL, this.worker); this.registered = true; } + /** Credentials in use (after an auto registration: the new account's). */ + get credentials(): Credentials { + return this.account.credentials; + } + private async login(playwright: PlaywrightWorkerArgs['playwright'], baseURL: string | undefined): Promise { const { method, path } = splitRequest(process.env.API_LOGIN, 'API_LOGIN'); const body = fill(process.env.API_LOGIN_BODY ?? '{}', { ...process.env, ...this.account.credentials }, 'API_LOGIN_BODY'); @@ -190,4 +197,17 @@ export const test = base.extend<{ api: Apis; publicApi: Apis }, { testAccount: T }, }); +/** + * Playwright globalSetup (see global-setup.ts): with API_TEST_ACCOUNT=auto, log in once in the main process and, + * only if the .env account is missing or refused, register ONE account for the whole run. Its credentials go into + * process.env, which every worker inherits; nothing is written to disk. + */ +export async function prepareRunAccount(playwright: PlaywrightWorkerArgs['playwright'], baseURL: string | undefined): Promise { + if (!process.env.API_LOGIN || (process.env.API_TEST_ACCOUNT ?? '').trim().toLowerCase() !== 'auto') return; + const vars = loginVars(); + const source = new TokenSource({ mode: 'auto', credentials: Object.fromEntries(vars.filter((v) => process.env[v]).map((v) => [v, process.env[v]!])) }, -1); + await source.get(playwright, baseURL); + for (const [k, v] of Object.entries(source.credentials)) process.env[k] = v; +} + export { expect }; diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 8df3a52..7affc0c 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -190,6 +190,18 @@ function planChain(spec: LoadedSpec, chain: CrudChain): { ok: true; plan: ChainP const posix = (p: string) => p.replace(/\\/g, '/'); +/** Playwright globalSetup of a generated suite: the run's test account (API_TEST_ACCOUNT=auto) decided once. */ +const GLOBAL_SETUP = `// Generated by api-test-agent. Playwright globalSetup: settles the run's test account once (API_TEST_ACCOUNT=auto). +// Use it in playwright.config.ts: globalSetup: './/_support/global-setup.ts' +import { request, type FullConfig } from '@playwright/test'; +import { prepareRunAccount } from './fixtures.js'; + +export default async function globalSetup(config: FullConfig): Promise { + const baseURL = (config.projects[0]?.use as { baseURL?: string } | undefined)?.baseURL ?? process.env.API_BASE_URL; + await prepareRunAccount({ request } as Parameters[0], baseURL); +} +`; + export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOptions): Promise { const meta: Meta = { spec: spec.location, hash: spec.hash, version: o.version }; const py = o.lang === 'python'; @@ -472,6 +484,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp await write(join(support, 'contract.ts'), validatorSrc); await write(join(support, 'contract-assert.ts'), CONTRACT_ASSERT); await write(join(support, 'fixtures.ts'), await readFile(fileURLToPath(new URL('../../src/contract/fixtures.ts', import.meta.url)), 'utf8')); + await write(join(support, 'global-setup.ts'), GLOBAL_SETUP); // API objects: generated bases are rewritten; the hand-written subclasses are created once and kept. const apiDir = join(support, 'api'); await write(join(apiDir, 'generated', 'ApiBase.ts'), API_BASE(o.version)); diff --git a/src/init.ts b/src/init.ts index 1f5e3c8..9d2e0d2 100644 --- a/src/init.ts +++ b/src/init.ts @@ -106,7 +106,8 @@ function envBody(values: Partial>, withComments: boolean) return lines.join('\n') + '\n'; } -const PLAYWRIGHT_CONFIG = (testsDir: string) => `import { defineConfig } from '@playwright/test'; +const PLAYWRIGHT_CONFIG = (testsDir: string) => `import { existsSync } from 'node:fs'; +import { defineConfig } from '@playwright/test'; // Settings come from .env (created by api-test-agent init) or from CI environment variables. try { @@ -120,6 +121,8 @@ if (process.env.API_TOKEN) extraHTTPHeaders.authorization = \`Bearer \${process. export default defineConfig({ testDir: '${testsDir}', + // Settles the test account once per run (API_TEST_ACCOUNT=auto); written by api-test-agent generate. + globalSetup: existsSync('${testsDir}/_support/global-setup.ts') ? './${testsDir}/_support/global-setup.ts' : undefined, fullyParallel: true, retries: 0, reporter: [['list'], ['html', { open: 'never' }]], From 201fa34e381333495ceca305252f7b3ff4addb03 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 23:44:22 +0100 Subject: [PATCH 5/6] feat(account): an agent run leaves the auto registration to the suite's globalSetup when it has no register settings Co-Authored-By: Claude Opus 5.5 --- src/cli.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cli.ts b/src/cli.ts index 78ab3c5..5b5025d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -135,6 +135,12 @@ async function prepareAccount(o: CommonOpts, agentLogin: boolean, suiteRun = fal } } if (!o.allowWrite) throw new Error(`Test account: ${why}. Registering a new one writes to the API: add --allow-write (test environments only), or fix the account in .env.`); + // Only the generated suite logs in, and the project configures registration for it (e.g. defaults in + // playwright.config.ts): its globalSetup registers the one account of the run. + if (!agentLogin && (!process.env.API_REGISTER || !process.env.API_REGISTER_BODY)) { + log(`Test account: auto, ${why}; the generated tests register one account for the run (their globalSetup).`); + return; + } checkRegisterConfig(); const acc = await registerAccount(o.baseUrl); log(`Test account: auto, ${why}: registered ${acc.label} (stays on the server). This run, and the generated tests it starts, use it; .env is not changed.`); From 41bfc6edc98da5392b825af7f6f5005cf4a73175 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 23:58:34 +0100 Subject: [PATCH 6/6] feat(account): Python suites support API_TEST_ACCOUNT=new and auto The generated conftest registers at most one account per pytest session: new always, auto only when the .env account is missing or refused (401/403/422). Credentials stay in memory; .env is never changed. The CLI no longer refuses new accounts for Python. Verified on the demo API: auto with a wrong password -> 1 registration, with the right one -> none, new -> 1; an agent-driven Python run in auto mode registers once and the suite reuses it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/GUIDE.md | 2 +- src/cli.ts | 3 -- src/generate/python.ts | 95 ++++++++++++++++++++++++++++++++------ tests/unit/account.test.ts | 11 +++++ 5 files changed, 93 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01cee81..7cc060f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ - **Fault injection:** the demo API simulates six list defects (`DEMO_FAULT`); `scripts/mutation-check.ts` runs a generated suite against each, and CI requires 6/6 detected in TypeScript and Python. The previous generator detected 0/6. - Demo API: `offset`, `tag` and `sort` on `GET /items`; two reference items tagged `catalog` (the approved demo fixture). - **Shared environments (found on Toolshop):** `"strategy": "read-only"` in a collection mapping; page-number paging with a fixed page size; read-only checks of a public list go through `publicApi` (no login); read-only filter tests take up to 5 values from the list and require the filtered result to be a subset of the unfiltered list, which catches the rental leak of Toolshop's defective build; a `sort` case ID may carry a reviewed value the spec does not enumerate. -- **Test account `auto`:** `API_TEST_ACCOUNT=auto` / `--test-account auto` uses the `.env` account and registers a new one only when it is missing or refused (401 / 403 / 422), e.g. after Toolshop reset its data; the agent registers once before `--run` and the generated tests reuse that account; with the generated `_support/global-setup.ts` as Playwright's `globalSetup` (added by `init`), a standalone run decides once in the main process, so a run registers at most one account even when Playwright restarts workers after failures; without it, at most one per worker. `.env` is never changed. +- **Test account `auto`:** `API_TEST_ACCOUNT=auto` / `--test-account auto` uses the `.env` account and registers a new one only when it is missing or refused (401 / 403 / 422), e.g. after Toolshop reset its data; the agent registers once before `--run` and the generated tests reuse that account; with the generated `_support/global-setup.ts` as Playwright's `globalSetup` (added by `init`), a standalone run decides once in the main process, so a run registers at most one account even when Playwright restarts workers after failures; without it, at most one per worker. `.env` is never changed. Python suites (conftest) support `new` and `auto` too, with at most one registration per pytest session. - Fixes: a GET of a single resource with an array field is no longer reported as an unconfigured collection; hand-written `_support/api/*Api.ts` stay in the generation manifest after the first run. - **Coverage completeness** (see docs/SUPPORT_MATRIX.md): diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 269e81f..6acdaa6 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -79,7 +79,7 @@ API_REGISTER=POST /users/register API_REGISTER_BODY={"first_name":"Api","last_name":"Test","email":"${API_USER}","password":"${API_PASSWORD}"} ``` -`API_REGISTER_BODY` must use the same `${VAR}`s as `API_LOGIN_BODY`; `${UNIQUE}` is a per-run suffix for other unique fields. To skip the question (CI): `API_TEST_ACCOUNT=existing|new|auto` or `--test-account existing|new|auto`. Python suites support `existing` only (for now). Without a terminal and without the setting, an account in `.env` means `existing`; otherwise the run stops with an explanation. +`API_REGISTER_BODY` must use the same `${VAR}`s as `API_LOGIN_BODY`; `${UNIQUE}` is a per-run suffix for other unique fields. To skip the question (CI): `API_TEST_ACCOUNT=existing|new|auto` or `--test-account existing|new|auto`. Python suites support all three: one registration at most per pytest session. Without a terminal and without the setting, an account in `.env` means `existing`; otherwise the run stops with an explanation. You need at least one of: a spec, a Postman collection, or existing tests. With none of them there is nothing to analyse. diff --git a/src/cli.ts b/src/cli.ts index 5b5025d..17a0fa0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -266,9 +266,6 @@ common(program.command('generate').description('audit, then generate Playwright log(`Test language: ${o.lang}`); if (o.run && (!o.baseUrl || !o.allowWrite)) throw new Error('--run creates and deletes data: it needs --base-url and --allow-write.'); await prepareAccount(o, o.probe || o.schemathesis, o.run); - if (o.run && o.lang === 'python' && process.env.API_LOGIN && process.env.API_TEST_ACCOUNT === 'new') { - throw new Error('A new account per run is supported for TypeScript suites only (for now): use an existing account for Python.'); - } const r = await runAudit(location, o); const deps = o.deps ? JSON.parse(await readFile(o.deps, 'utf8')) : undefined; if (o.ai) await aiProposals(r.spec.doc, r.ops, o.out, { maxCalls: Number(o.aiMaxCalls), model: o.aiModel, runner: o.aiRunner }, deps); diff --git a/src/generate/python.ts b/src/generate/python.ts index 74eced2..2954fc9 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -210,14 +210,16 @@ def created_${name}(${name}): Settings come from .env (API_BASE_URL, API_TOKEN or API_LOGIN...) or the real environment; real variables win. Auth: with API_LOGIN (e.g. "POST /users/login") the tests log in and refresh the token before it expires; -otherwise the static API_TOKEN is used. +otherwise the static API_TOKEN is used. Test account: API_TEST_ACCOUNT=existing (default) | new | auto. """ import json import os import pathlib import re +import secrets import sys import time +import uuid import pytest import requests @@ -291,29 +293,68 @@ def base_url(): return url +_LOGIN_VARS = re.compile(r"\\$\\{(\\w+)\\}") + + +def _fill(template, values, name): + def sub(match): + value = values.get(match.group(1)) + if not value: + raise RuntimeError(f"{name} uses {match.group(0)}, which is not set (.env or environment)") + return json.dumps(value)[1:-1] + + return json.loads(_LOGIN_VARS.sub(sub, template)) + + +def _login_vars(): + return list(dict.fromkeys(_LOGIN_VARS.findall(os.environ.get("API_LOGIN_BODY") or ""))) + + class _TokenSource: - """Logs in with API_LOGIN / API_LOGIN_BODY and refreshes the token shortly before it expires.""" + """Logs in with API_LOGIN / API_LOGIN_BODY and refreshes the token shortly before it expires. + + API_TEST_ACCOUNT=existing (default): the account from .env (the \${VAR}s of API_LOGIN_BODY). + API_TEST_ACCOUNT=new: one NEW account per test session through API_REGISTER / API_REGISTER_BODY. + API_TEST_ACCOUNT=auto: the .env account; only when it is missing or its login is refused (401 / 403 / 422, + e.g. the test environment was reset) is ONE new account registered for the session. + Generated emails / passwords live in this process's memory only; .env is never changed. + """ def __init__(self, base_url): self.base_url = base_url.rstrip("/") + "/" self.token = None self.expires_at = 0.0 + self.mode = (os.environ.get("API_TEST_ACCOUNT") or "existing").strip().lower() + if self.mode not in ("existing", "new", "auto"): + raise RuntimeError(f'API_TEST_ACCOUNT must be "existing", "new" or "auto", got "{self.mode}"') + self.credentials = {v: os.environ[v] for v in _login_vars() if os.environ.get(v)} + self.registered = False + + def _register(self, why): + method, path = (os.environ.get("API_REGISTER") or "").split(None, 1) if os.environ.get("API_REGISTER") else ("", "") + template = os.environ.get("API_REGISTER_BODY") + if not method or not template: + raise RuntimeError(f"Test account: {why}; registering a new one needs API_REGISTER and API_REGISTER_BODY") + unique = f"{int(time.time() * 1000):x}{uuid.uuid4().hex[:6]}" + password = f"Qa-{secrets.token_urlsafe(12)}-7x!" + creds = {v: password if "pass" in v.lower() else f"api-test-{unique}@example.com" for v in _login_vars()} + body = _fill(template, {**os.environ, **creds, "UNIQUE": unique}, "API_REGISTER_BODY") + # Never print the request or the response: they contain the password. + res = requests.request(method.upper(), self.base_url + path.strip().lstrip("/"), json=body, timeout=30) + if not res.ok: + raise RuntimeError(f"Registering a test account failed: {method} {path} answered {res.status_code} (check API_REGISTER_BODY)") + label = next((value for key, value in creds.items() if "pass" not in key.lower()), "") + print(f"[test-account] {why}: registered new account {label} (stays on the server)") + self.credentials = creds + self.registered = True - def get(self): - if self.token and time.time() < self.expires_at - 30: - return self.token + def _login(self): method, path = os.environ["API_LOGIN"].split(None, 1) - - def fill(match): - value = os.environ.get(match.group(1)) - if not value: - raise RuntimeError(f"API_LOGIN_BODY uses {match.group(0)}, which is not set (.env or environment)") - return json.dumps(value)[1:-1] - - body = json.loads(re.sub(r"\\$\\{(\\w+)\\}", fill, os.environ.get("API_LOGIN_BODY") or "{}")) - res = requests.request(method, self.base_url + path.strip().lstrip("/"), json=body, timeout=30) + body = _fill(os.environ.get("API_LOGIN_BODY") or "{}", {**os.environ, **self.credentials}, "API_LOGIN_BODY") + res = requests.request(method.upper(), self.base_url + path.strip().lstrip("/"), json=body, timeout=30) if not res.ok: - raise RuntimeError(f"Login failed: {method} {path} answered {res.status_code} (check credentials in .env)") + source = "freshly registered account" if self.registered else "check the test account in .env" + raise _LoginRefused(res.status_code, f"Login failed: {method} {path} answered {res.status_code} ({source})") data = res.json() pointer = os.environ.get("API_TOKEN_POINTER") or "/access_token" token = read_pointer(data, pointer) @@ -324,6 +365,30 @@ class _TokenSource: self.expires_at = time.time() + (float(ttl) if isinstance(ttl, (int, float)) and ttl > 0 else 600) return token + def get(self): + if self.token and time.time() < self.expires_at - 30: + return self.token + if self.mode == "new" and not self.registered: + self._register("API_TEST_ACCOUNT=new") + elif self.mode == "auto" and not self.registered: + missing = [v for v in _login_vars() if v not in self.credentials] + if missing: + self._register(f"{', '.join(missing)} not set") + else: + try: + return self._login() + except _LoginRefused as e: + if e.status not in (401, 403, 422): + raise + self._register(f"the account from .env is refused ({e.status})") + return self._login() + + +class _LoginRefused(RuntimeError): + def __init__(self, status, message): + super().__init__(message) + self.status = status + @pytest.fixture(scope="session") def token_source(base_url): diff --git a/tests/unit/account.test.ts b/tests/unit/account.test.ts index 0f57f1e..782536c 100644 --- a/tests/unit/account.test.ts +++ b/tests/unit/account.test.ts @@ -67,3 +67,14 @@ describe('test account', () => { expect(env).not.toHaveProperty('SHOP_EMAIL'); // nothing half-applied }); }); + +describe('Python suites: test account modes', () => { + it('the generated conftest supports existing, new and auto, registering at most once per session', async () => { + const { renderConftest } = await import('../../src/generate/python.js'); + const text = renderConftest([], { spec: 'x', hash: 'h', version: 'test' }); + expect(text).toContain('if self.mode not in ("existing", "new", "auto")'); + expect(text).toContain('if e.status not in (401, 403, 422):'); + expect(text).toContain('self.registered = True'); + expect(text).toContain(String.raw`_LOGIN_VARS = re.compile(r"\$\{(\w+)\}")`); + }); +});