From c9c5998895d527aa8aae8a8cdbd2ecf872372b1c Mon Sep 17 00:00:00 2001 From: testomut Date: Tue, 10 Nov 2026 09:18:22 +0100 Subject: [PATCH] feat(params, collections): practical query-parameter testing and stronger GET collection checks Query parameters: - confirmed: an integer parameter gets a decimal inside its bounds (only the type is broken); every query case checks the value really went over HTTP; accepted values check the response contract; values over the limits are CASE_LIMIT_REACHED gaps; Python sends query booleans as true / false. - exploratory probes (empty, text, decimal, zero, negative, large, special, boolean / enum spelling, missing): GET / HEAD only, deduplicated against confirmed cases and the documented range, never failing on the API's behavior, recorded in the run report (exploratory.jsonl). GET collections (on the PR #14 engine): - "match": "search" (case-insensitive substring), "total" consistency, sort-reverse (descending = ascending reversed), several mappings per resource ("collections": [...]). Case ID vocabulary v5: sort-reverse, total, probe, decimal type case. CI gate: a Python test that reassigns its own fixture fails (a generated test shadowed the "items" fixture; its cleanup would not have run). Demo API: GET /items/search and 8 more faults; fault injection 17/17 in TypeScript and Python (base generator: 14/17 on the same spec). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 10 +- CHANGELOG.md | 7 + README.md | 3 +- ci/coverage-baseline.demo.json | 36 ++++ ci/coverage-baseline.kitchen-sink.json | 10 ++ demo-api/deps.json | 129 ++++++++------ demo-api/expected-gaps.json | 2 +- demo-api/openapi.yaml | 49 ++++++ demo-api/server.ts | 39 ++++- docs/OPENAPI_CHANGE_TRIGGER.md | 4 + docs/SUPPORT_MATRIX.md | 30 +++- scripts/mutation-check.ts | 20 ++- src/cases/assign.ts | 10 +- src/cases/ids.ts | 15 +- src/cases/validate.ts | 10 +- src/cli.ts | 7 +- src/contract/contract.py | 27 +++ src/generate/collection-render.ts | 225 +++++++++++++++++++++++-- src/generate/collection-tests.ts | 47 ++++-- src/generate/collection.ts | 14 +- src/generate/generate.ts | 63 +++++-- src/generate/graph.ts | 12 +- src/generate/negative.ts | 4 +- src/generate/param-cases.ts | 25 ++- src/generate/probes.ts | 122 ++++++++++++++ src/generate/python.ts | 48 +++++- src/generate/templates.ts | 87 ++++++++-- src/report/quality-gates.ts | 11 +- src/report/report.ts | 13 ++ tests/unit/collection.test.ts | 6 +- tests/unit/core.test.ts | 4 +- tests/unit/coverage-depth.test.ts | 27 +++ tests/unit/coverage.test.ts | 2 +- tests/unit/query-collections.test.ts | 141 ++++++++++++++++ 34 files changed, 1096 insertions(+), 163 deletions(-) create mode 100644 src/generate/probes.ts create mode 100644 tests/unit/query-collections.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 539c5b5..c34e974 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,12 +129,12 @@ jobs: npx tsx src/cli.ts manifest validate --tests-dir tests/api-python - name: Fault injection - the generated 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, a required optional field, an accepted expired token, an ignored suspension) on its own - # port: clean without a fault, at least one failure with each. + # The demo API runs once per DEMO_FAULT (17 defects: collection, body variants, auth, parameter validation, + # total, persistence, search, decimal truncation) on its own port: clean without a fault, at least one failure + # with each. Exploratory probes record and never fail, so they cannot hide a clean run. run: | - npx tsx scripts/mutation-check.ts --lang typescript --port 3200 tests/api/items tests/api/me - npx tsx scripts/mutation-check.ts --lang python --port 3300 tests/api-python/items tests/api-python/me + npx tsx scripts/mutation-check.ts --lang typescript --port 3200 --show tests/api/items tests/api/items-search tests/api/me + npx tsx scripts/mutation-check.ts --lang python --port 3300 --show tests/api-python/items tests/api-python/items_search tests/api-python/me 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); } ' diff --git a/CHANGELOG.md b/CHANGELOG.md index 2eb5976..8cc604a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- **Query parameters and GET collections** (docs/SUPPORT_MATRIX.md): + - confirmed: a decimal case for integer parameters (inside the documented bounds, so only the type is broken); every query case checks that the value really went over HTTP; accepted values also check the response contract; values over the limits are `CASE_LIMIT_REACHED` gaps instead of being dropped silently; Python sends query booleans as `true` / `false`; + - exploratory probes for scalar query parameters of GET / HEAD operations (empty, text, decimal, zero, negative, large, special characters, another spelling of a boolean or enum value, a missing required parameter): deduplicated against confirmed cases and the documented range, never failing on the API's behavior, recorded in the report (`exploratory.jsonl`, "Exploratory query probes"); + - collections: `"match": "search"` (case-insensitive substring), `total` (the same on every page and equal to the number listed), `sort-reverse` (descending is ascending reversed), several mappings per resource (`"collections": [...]`); + - case ID vocabulary v5: `sort-reverse`, `total`, `probe`, the decimal `type` case; + - CI gate: a Python test that reassigns its own fixture fails (found here: a generated test shadowed the `items` resource fixture, so its cleanup would not have run); + - demo API: `GET /items/search` (required `q`), and the faults `ignore-max`, `loose-types`, `ignore-enum`, `ignore-required`, `truncate-decimal`, `wrong-total`, `drop-update`, `broken-search`; fault injection 17/17 in TypeScript and Python (the previous generator: 14/17 on the same spec). - **Coverage depth** (docs/SUPPORT_MATRIX.md): - positive request-body variants for create / update of a confirmed chain: only the required fields, and every other `oneOf` / `anyOf` branch with a valid sample; each checked with ajv before a test is written, cleanup in `finally`; closes `UNCOVERED_VARIANT` where a branch can be sent; - reviewed auth cases from a deps `auth` section (environment variable names only): 403 for the operations named (`auth.forbidden`), 401 with an expired credential (`auth.expired`); skipped with the reason when the variable is unset; mismatches with the spec are `INVALID_REVIEWED_CONFIG`; diff --git a/README.md b/README.md index b2f4efe..1f4cf7c 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,8 @@ Coverage is reported, never implied. The full keyword-by-keyword table is in [do **Derived from the spec alone (deterministic):** - request bodies, recursively (`request.body#/items/*/sku`): required, type, null, enum, const, lengths, pattern, format, bounds, multipleOf, array and object size, uniqueItems, additionalProperties; one broken rule per case; -- query, header, cookie and path parameters, arrays in their documented style; +- query, header, cookie and path parameters, arrays in their documented style; each case checks that the value really went over HTTP; integers also get a decimal; +- exploratory query probes (empty, non-numeric, decimal, zero, negative, huge, special characters): what the API answers is recorded in the report, never treated as a confirmed defect; - documented successes, documented enum values and valid limits of query parameters (one test and one case ID each); - 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. diff --git a/ci/coverage-baseline.demo.json b/ci/coverage-baseline.demo.json index 0b61433..88f1f0d 100644 --- a/ci/coverage-baseline.demo.json +++ b/ci/coverage-baseline.demo.json @@ -1,12 +1,20 @@ { "schemaVersion": 1, "activeCaseIds": [ + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit/decimal:type", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit/empty:probe", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:maximum", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:minimum", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:type", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/offset/decimal:type", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/offset/empty:probe", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/offset/large:probe", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/offset:minimum", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/offset:type", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/sort/case:probe", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/sort/empty:probe", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/sort:enum", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/tag/special:probe", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/tag:maxLength", "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/tag:minLength", "ata:op_4PIO72ZI3SIY:contract:positive:response.body#:schema", @@ -23,12 +31,15 @@ "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/-price:sort", "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/name:accepted-value", "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/name:sort", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/name:sort-reverse", "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/price:accepted-value", "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/price:sort", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/price:sort-reverse", "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/tag/x:accepted-value", "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/tag/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:accepted-value", "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/tag:filter", "ata:op_4PIO72ZI3SIY:functional:positive:response.body#/items/*/id:unique", + "ata:op_4PIO72ZI3SIY:functional:positive:response.body#/total:total", "ata:op_7P2UH7UKQRHC:contract:positive:response.body#:schema", "ata:op_7P2UH7UKQRHC:contract:positive:response.status#/404:documented", "ata:op_7P2UH7UKQRHC:functional:negative:request.path#/itemId:not-found", @@ -41,6 +52,30 @@ "ata:op_FXHMYSJVVHAU:functional:negative:request.path#/reportId:not-found", "ata:op_OT5MMXZVBZK4:contract:positive:response.body#:schema", "ata:op_OT5MMXZVBZK4:functional:positive:operation:documented-success", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/limit/decimal:type", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/limit/empty:probe", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/limit:maximum", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/limit:minimum", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/limit:type", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/offset/decimal:type", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/offset/empty:probe", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/offset/large:probe", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/offset:minimum", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/offset:type", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/q/special:probe", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/q:maxLength", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/q:minLength", + "ata:op_RCUGPMGR7MCO:contract:negative:request.query#/q:required", + "ata:op_RCUGPMGR7MCO:contract:positive:response.body#:schema", + "ata:op_RCUGPMGR7MCO:functional:positive:operation:collection-contains", + "ata:op_RCUGPMGR7MCO:functional:positive:operation:documented-success", + "ata:op_RCUGPMGR7MCO:functional:positive:request.query#/limit/1:accepted-value", + "ata:op_RCUGPMGR7MCO:functional:positive:request.query#/limit/50:accepted-value", + "ata:op_RCUGPMGR7MCO:functional:positive:request.query#/offset/0:accepted-value", + "ata:op_RCUGPMGR7MCO:functional:positive:request.query#/offset:pagination", + "ata:op_RCUGPMGR7MCO:functional:positive:request.query#/q:filter", + "ata:op_RCUGPMGR7MCO:functional:positive:response.body#/items/*/id:unique", + "ata:op_RCUGPMGR7MCO:functional:positive:response.body#/total:total", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:maxLength", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:minLength", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable", @@ -94,6 +129,7 @@ ], "gaps": [ "CANNOT_ISOLATE_RULE GET /items request.query#/sort type", + "CANNOT_ISOLATE_RULE GET /items/search lifecycle", "MISSING_CLEANUP POST /admin/reset response.status#/204", "MISSING_CLEANUP POST /admin/reset response.status#/401", "MISSING_CLEANUP POST /admin/reset suite#/contract", diff --git a/ci/coverage-baseline.kitchen-sink.json b/ci/coverage-baseline.kitchen-sink.json index ca2fa98..0201ff3 100644 --- a/ci/coverage-baseline.kitchen-sink.json +++ b/ci/coverage-baseline.kitchen-sink.json @@ -22,12 +22,22 @@ "ata:op_MDAZRDJNDE6Z:contract:negative:request.cookie#/session:minLength", "ata:op_MDAZRDJNDE6Z:contract:negative:request.header#/x-request-id:format", "ata:op_MDAZRDJNDE6Z:contract:negative:request.header#/x-request-id:required", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/code/empty:probe", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/code/large:probe", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/code/special:probe", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/code:pattern", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/ids:uniqueItems", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit/decimal:type", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit/empty:probe", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit:maximum", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit:minimum", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit:type", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/since/empty:probe", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/since/large:probe", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/since/special:probe", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/since:format", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/status/case:probe", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/status/empty:probe", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/status:enum", "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/tags:maxItems", "ata:op_MDAZRDJNDE6Z:contract:positive:response.body#:schema", diff --git a/demo-api/deps.json b/demo-api/deps.json index b25ee43..7db3771 100644 --- a/demo-api/deps.json +++ b/demo-api/deps.json @@ -18,60 +18,89 @@ "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" + "collections": [ + { + "operationId": "listItems", + "items": "/items", + "id": "/id", + "fields": { + "/name": "exact", + "/price": "tolerance:0.001", + "/tags": "exact", + "/createdAt": "ignore" }, - { - "param": "sort", - "value": "-name", - "field": "/name", - "order": "desc" + "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 }, - { - "param": "sort", - "value": "price", - "field": "/price", - "order": "asc" + "deletedDisappears": true, + "total": "/total" + }, + { + "operationId": "searchItems", + "items": "/items", + "id": "/id", + "fields": { + "/name": "exact", + "/price": "tolerance:0.001" }, - { - "param": "sort", - "value": "-price", - "field": "/price", - "order": "desc" + "total": "/total", + "unique": [ + "/id" + ], + "filters": [ + { + "param": "q", + "field": "/name", + "match": "search" + } + ], + "page": { + "style": "offset", + "offsetParam": "offset", + "limitParam": "limit", + "maxPages": 20 } - ], - "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 6d8230f..098d32d 100644 --- a/demo-api/expected-gaps.json +++ b/demo-api/expected-gaps.json @@ -1,5 +1,5 @@ { - "CANNOT_ISOLATE_RULE": 1, + "CANNOT_ISOLATE_RULE": 2, "MISSING_CLEANUP": 2, "MISSING_RESOURCE_SOURCE": 1, "MISSING_RESPONSE_SCHEMA": 1 diff --git a/demo-api/openapi.yaml b/demo-api/openapi.yaml index e89b9ad..358faf8 100644 --- a/demo-api/openapi.yaml +++ b/demo-api/openapi.yaml @@ -122,6 +122,55 @@ paths: itemId: '$response.body#/id' '400': $ref: '#/components/responses/BadRequest' + /items/search: + get: + operationId: searchItems + summary: Search items by name + description: Items whose name contains q, ignoring case. + tags: [items] + parameters: + - name: q + in: query + required: true + description: Text the name must contain (case-insensitive). + schema: + type: string + minLength: 1 + maxLength: 30 + example: keyboard + - name: limit + in: query + required: false + schema: + type: integer + minimum: 1 + maximum: 50 + default: 20 + - name: offset + in: query + required: false + schema: + type: integer + minimum: 0 + default: 0 + responses: + '200': + description: Matching items + content: + application/json: + schema: + type: object + required: [items, total] + properties: + items: + type: array + items: + $ref: '#/components/schemas/Item' + total: + type: integer + minimum: 0 + '400': + $ref: '#/components/responses/BadRequest' /items/{itemId}: parameters: - name: itemId diff --git a/demo-api/server.ts b/demo-api/server.ts index 41b15a5..5d7d92d 100644 --- a/demo-api/server.ts +++ b/demo-api/server.ts @@ -83,18 +83,24 @@ route('/health', { GET: (_q, res) => send(res, 200, { status: 'ok' }) }); route('/items', { GET: (_q, res, _p, url) => { + // DEMO_FAULT simulates one defect at a time (mutation tests: the generated suite must catch each). + const fault = process.env.DEMO_FAULT; const raw = url.searchParams.get('limit'); - const limit = raw === null ? 20 : Number(raw); + let limit = raw === null ? 20 : Number(raw); + if (fault === 'loose-types' && !Number.isFinite(limit)) limit = 20; // a non-numeric limit silently becomes the default + if (fault === 'ignore-max' && limit > 100) limit = 100; // the maximum is clamped instead of rejected + if (fault === 'truncate-decimal' && Number.isFinite(limit)) limit = Math.trunc(limit); // 20.5 silently becomes 20 if (!Number.isInteger(limit) || limit < 1 || limit > 100) return error(res, 400, 'limit must be an integer 1-100'); 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'); + let sort = url.searchParams.get('sort'); + if (sort !== null && !['name', '-name', 'price', '-price'].includes(sort)) { + if (fault !== 'ignore-enum') return error(res, 400, 'sort must be name, -name, price or -price'); + sort = null; // an undocumented value is silently ignored + } 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); @@ -107,7 +113,7 @@ route('/items', { 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 }); + send(res, 200, { items: page, total: all.length + (fault === 'wrong-total' ? 1 : 0) }); }, POST: async (req, res) => { const body = await readJson(req); @@ -129,6 +135,25 @@ const findItem = (res: ServerResponse, id: string) => { return item; }; +route('/items/search', { + GET: (_q, res, _p, url) => { + const fault = process.env.DEMO_FAULT; + const q = url.searchParams.get('q'); + if (q === null && fault !== 'ignore-required') return error(res, 400, 'q is required'); + if (q !== null && (q.length < 1 || q.length > 30)) return error(res, 400, 'q must be 1-30 characters'); + const raw = url.searchParams.get('limit'); + const limit = raw === null ? 20 : Number(raw); + if (!Number.isInteger(limit) || limit < 1 || limit > 50) return error(res, 400, 'limit must be an integer 1-50'); + 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 needle = (q ?? '').toLowerCase(); + // Case-insensitive substring of the name; DEMO_FAULT=broken-search ignores the query. + const all = [...items.values()].filter((i) => fault === 'broken-search' || i.name.toLowerCase().includes(needle)); + send(res, 200, { items: all.slice(offset, offset + limit), total: all.length }); + }, +}); + route('/items/{itemId}', { GET: (_q, res, p) => { const item = findItem(res, p.itemId); @@ -141,6 +166,8 @@ route('/items/{itemId}', { if (!body.ok) return error(res, 400, 'Invalid JSON'); const v = validateItem(body.value, true); if (typeof v === 'string') return error(res, 400, v); + // DEMO_FAULT=drop-update: the response shows the change, but it is never stored. + if (process.env.DEMO_FAULT === 'drop-update') return send(res, 200, { ...item, ...v }); Object.assign(item, v); send(res, 200, item); }, diff --git a/docs/OPENAPI_CHANGE_TRIGGER.md b/docs/OPENAPI_CHANGE_TRIGGER.md index 61dbb46..676a874 100644 --- a/docs/OPENAPI_CHANGE_TRIGGER.md +++ b/docs/OPENAPI_CHANGE_TRIGGER.md @@ -294,6 +294,10 @@ v3 functional/positive: collection-contains, fixture operation v4 functional/positive: optional-omitted request.body# variant request.body#/@ functional/negative: expired-credentials request.security +v5 functional/positive: sort-reverse request.query#// + total response.body# + contract/negative: probe request.#// (exploratory: never asserted) + type request.#//decimal (a second type case of an integer) ``` 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. diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index a096e3e..5eb5916 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -50,7 +50,7 @@ Every case is a valid request (each required query / header / cookie parameter w | Target | State | Limits / gap | Stage | |---|---|---|---| | required (missing) | ✅ | query, header, cookie; needs the documented value of every required parameter, else `MISSING_VALID_SAMPLE` and no cases | 4 ✔ | -| `type` | ✅ | number, integer, boolean (a string parameter cannot have a wrong type on the wire) | 4 ✔ | +| `type` | ✅ | number, integer, boolean (a string parameter cannot have a wrong type on the wire); an integer also gets a decimal inside its bounds (`request.#//decimal`), which a lenient parser would round; with `multipleOf` > 1 or an `enum` → `CANNOT_ISOLATE_RULE` | 4 ✔, Q ✔ | | `enum`, `const` | ✅ | | 4 ✔ | | `pattern`, `format` | ✅ | as for bodies | 4 ✔ | | `minimum` / `maximum` / exclusive / `multipleOf` | ✅ | | 4 ✔ | @@ -62,7 +62,26 @@ Every case is a valid request (each required query / header / cookie parameter w | cookie parameters | ✅ | sent in the `Cookie` header | 4 ✔ | | path parameters | ✅ | type, format, pattern, enum, length; on write operations numeric bounds → `UNSAFE_LIVE_CHECK` (an out-of-range id could address a real record); other path parameters need documented values (`MISSING_RESOURCE_SOURCE`); not on operations whose body is required | 4 ✔ | | required header / cookie in every generated call | ✅ | positive, 404, 401, body and parameter cases; a required one without a documented value blocks the operation with its reason | 4 ✔ | -| boundary-valid values | ❌ | | 7 | +| boundary-valid values | ✅ | documented enum values, else the valid limits (min / max inside exclusive bounds and `multipleOf`, shortest / longest string), one `accepted-value` test each, status and response contract checked; more than 5 per parameter / 15 per operation → `CASE_LIMIT_REACHED` | 7 ✔, Q ✔ | +| the value is really sent | ✅ | every query case checks the request URL: the value under test as text, or absent for a missing one (a local schema violation proves nothing about the API); Python sends booleans as `true` / `false` like TypeScript | Q ✔ | + +### Exploratory probes (`src/generate/probes.ts`) + +Inputs a real client sends by mistake, for scalar query parameters of GET / HEAD operations. What the API must answer is not specified (or no rejection is documented), so a probe **never fails on the API's behavior**: it checks that the value went over HTTP and records the answer (status, documented or not, server error, contract match) as a test annotation and, during `--run`, in the report section "Exploratory query probes". A 5xx is flagged for a human, not reported as a defect. Rule `probe`, location `request.query#//`. + +| Probe | For | Not generated when | +|---|---|---| +| `missing` | required parameters | the confirmed `required` case sends it | +| `empty` (`name=`) | all | a confirmed `minLength` ≥ 1 case covers it | +| `text` (`abc`, `maybe`) | integer / number / boolean | the confirmed `type` case covers it | +| `decimal` (`1.5`) | integer | the confirmed decimal case covers it | +| `zero`, `negative` | integer / number | a documented range makes it valid, or a confirmed minimum case covers it | +| `large` | integer / number (20 digits), string without `maxLength` (1000 characters) | a confirmed maximum / maxLength case covers it | +| `special` (`'"<>%;&`) | free-text strings | | +| `numeric` (`1`) | boolean | | +| `case` (another letter case of an enum value) | string enums | | + +Write operations are never probed (`UNSAFE_LIVE_CHECK`); an operation with an unknown path value is not probed (`MISSING_RESOURCE_SOURCE`); more than 24 probes per operation → `CASE_LIMIT_REACHED`. ## Functional (`functional.spec.ts`) @@ -171,6 +190,10 @@ Strategy per list operation (recorded in `coverage-gaps.json` → `collection.st |---|---|---| | 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 | +| search (`"match": "search"`: the string field contains the value, ignoring case) | ✅ | controlled: the query in upper case, the data in lower case; read-only: prefixes of existing values; no subset check when the search parameter is required (there is no unfiltered list) | +| descending is the ascending order reversed (`sort-reverse`) | ✅ | for every asc / desc pair on one field; controlled: the test's records; read-only: the values (ties keep their place), read once more on a mismatch | +| total and metadata (`total`: a JSON pointer in the response) | ✅ | the same total on every page and equal to the number of resources listed; read-only skipped when there are more than `maxPages` pages; without `total` → `UNCONFIRMED_BUSINESS_RULE` | +| several list operations of one resource (`"collections": [...]`) | ✅ | each with its own mapping; an operation mapped twice → `INVALID_REVIEWED_CONFIG`; a lifecycle that cannot find the updated resource (required parameter, update changes the isolating field) → `CANNOT_ISOLATE_RULE` | | 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 | @@ -183,7 +206,7 @@ Strategy per list operation (recorded in `coverage-gaps.json` → `collection.st 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). Beyond the list defects below, the suite must also catch `require-optional` (an optional field is required), `accept-expired` (an expired token is accepted) and `ignore-suspension` (a refused account gets 200): 9/9 in CI; the generator of the previous release caught 7/9 on the same spec (both auth defects missed, `require-optional` only by chance, through a reviewed business scenario). +Defect detection on the demo API (`scripts/mutation-check.ts --show` lists which tests caught each defect; TypeScript and Python identical). 17 faults in CI: the list defects below, `require-optional`, `accept-expired`, `ignore-suspension`, and the parameter / collection faults `ignore-max`, `loose-types`, `ignore-enum`, `ignore-required`, `truncate-decimal` (limit=20.5 becomes 20), `wrong-total`, `drop-update` (the update is not stored), `broken-search`. The previous release caught 14/17 on the same spec (missed `wrong-total`, `broken-search`, `truncate-decimal`). Beyond the list defects below, the suite must also catch `require-optional` (an optional field is required), `accept-expired` (an expired token is accepted) and `ignore-suspension` (a refused account gets 200): 9/9 in CI; the generator of the previous release caught 7/9 on the same spec (both auth defects missed, `require-optional` only by chance, through a reviewed business scenario). @@ -236,6 +259,7 @@ Defect detection on the demo API (`scripts/mutation-check.ts`, TypeScript and Py | 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: coverage baseline | ✅ | `ci/coverage-baseline.{demo,kitchen-sink}.json`: every active case ID and every gap (code + operation + location); a lost case or a gap the baseline does not list fails until the PR updates the baseline (`scripts/coverage-summary.ts --write-baseline`) | D ✔ | +| CI: Python fixtures are never reassigned | ✅ | a test that assigns to its own fixture (e.g. `items, totals = ...` with the `items` resource fixture) fails the gate: its cleanup would hit the wrong object | Q ✔ | | CI: cleanup of write tests | ✅ | every generated test that creates data removes it in `finally`, a fixture teardown, or `removeIfCreated` right after the request and before any assertion (`src/report/quality-gates.ts`), TypeScript and Python | D ✔ | | CI: coverage summary | ✅ | per operation: suites, active case IDs, documented statuses checked, gaps with code and location; Markdown + JSON artifact `coverage-summary`, also in the job summary | D ✔ | | unchecked-status codes | ✅ | the actual reason: a status of an operation no request is sent to has the success call's reason (e.g. `MISSING_CLEANUP`), an unchecked success status the reason the success call is blocked (e.g. `MISSING_RESOURCE_SOURCE`) | D ✔ | diff --git a/scripts/mutation-check.ts b/scripts/mutation-check.ts index 7a3dac4..a928221 100644 --- a/scripts/mutation-check.ts +++ b/scripts/mutation-check.ts @@ -13,7 +13,7 @@ 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', 'require-optional', 'accept-expired', 'ignore-suspension'] as const; +export const FAULTS = ['ignore-filter', 'wrong-sort', 'hide-created', 'duplicate', 'wrong-field', 'bad-pagination', 'require-optional', 'accept-expired', 'ignore-suspension', 'ignore-max', 'loose-types', 'ignore-enum', 'wrong-total', 'drop-update', 'ignore-required', 'broken-search', 'truncate-decimal'] as const; const args = process.argv.slice(2); const lang = args.includes('--lang') ? args[args.indexOf('--lang') + 1] : 'typescript'; @@ -38,13 +38,14 @@ async function waitHealthy(url: string): Promise { throw new Error(`demo API at ${url} did not start`); } -function runTests(baseUrl: string): { passed: number; failed: number; skipped: number; output: string } { +function runTests(baseUrl: string): { passed: number; failed: number; skipped: number; output: string; failedTests: 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 failedTests = [...out.matchAll(/^(?:FAILED|ERROR) (\S+)/gm)].map((m) => m[1].split('::').slice(-1)[0]); + return { passed: n('passed'), failed: n('failed') + n('error'), skipped: n('skipped'), output: out, failedTests }; } 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`); @@ -52,7 +53,13 @@ function runTests(baseUrl: string): { passed: number; failed: number; skipped: n 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 }; + const failedTests: string[] = []; + const walk = (suite: any) => { + for (const sp of suite.specs ?? []) for (const t of sp.tests ?? []) if (t.status === 'unexpected' || t.status === 'flaky') failedTests.push(`${(suite.file ?? '').split('\\').join('/').split('/').slice(-3, -1).join('/')}: ${sp.title}`); + for (const c of suite.suites ?? []) walk(c); + }; + for (const suite of report.suites ?? []) walk(suite); + return { passed: s.expected ?? 0, failed: (s.unexpected ?? 0) + (s.flaky ?? 0), skipped: s.skipped ?? 0, output: r.stderr, failedTests }; } finally { rmSync(config, { force: true }); } @@ -71,18 +78,19 @@ async function withServer(fault: string, port: number, fn: (url: string) => T } } -const rows: { fault: string; passed: number; failed: number; skipped: number; ok: boolean }[] = []; +const rows: { fault: string; passed: number; failed: number; skipped: number; ok: boolean; caughtBy: string[] }[] = []; const faults = only ? FAULTS.filter((f) => only.includes(f)) : FAULTS; if (only && faults.length !== only.length) throw new Error(`unknown fault in --faults ${only.join(',')}: known ${FAULTS.join(', ')}`); 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 }); + rows.push({ fault: fault || '(none)', passed: r.passed, failed: r.failed, skipped: r.skipped, ok, caughtBy: r.failedTests }); 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'}`); +if (args.includes('--show')) for (const r of rows.filter((x) => x.fault !== '(none)')) console.log(` ${r.fault}: ${r.caughtBy.slice(0, 4).join(' | ') || '-'}`); const detected = rows.filter((r) => r.fault !== '(none)' && r.ok).length; console.log(`detected ${detected}/${faults.length} injected defects`); const label = args.includes('--label') ? args[args.indexOf('--label') + 1] : lang; diff --git a/src/cases/assign.ts b/src/cases/assign.ts index 86222a7..c325980 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -29,7 +29,7 @@ export interface ScenarioDefinition { export interface SuiteCaseIds { /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ functional: { collection?: string[]; fixture?: string; bodyVariants?: string[]; envCredentials?: 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 }; + contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[]; unsupportedMediaType?: string; probes?: 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[]>; @@ -58,6 +58,8 @@ export interface AssignInput { collectionChain?: CrudChain; /** An approved fixture is compared (strategy B). */ fixture?: boolean; + /** Exploratory query probes (one case each, in order). */ + probes?: { location: string }[]; /** Positive request-body variants (one case each, in order). */ bodyVariants?: { location: string; kind: string }[]; } @@ -107,7 +109,8 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): } for (const c of s.paramCases) { const t = c.target; - const at = t && t.in !== 'body' && t.field ? { query: location.query, header: location.header, cookie: location.cookie, path: location.path }[t.in](t.field) : undefined; + const named = t && t.in !== 'body' && t.field ? { query: location.query, header: location.header, cookie: location.cookie, path: location.path }[t.in](t.field) : undefined; + const at = named && t && t.in !== 'body' && t.variant ? `${named}/${t.variant}` : named; ids.contract.params.push(at ? add('contract', { subjectUid: uid, polarity: 'negative', location: at, rule: t!.rule }) : ''); } @@ -162,6 +165,8 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): 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 === 'sort-reverse' ? { location: location.paramValue('query', t.sort!.param, t.sort!.value), rule: 'sort-reverse' } + : t.kind === 'total' ? { location: location.responseBody(bodyPointer(segs(cp.c.total!))), rule: 'total' } : 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 }); @@ -178,6 +183,7 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): 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.probes?.length) ids.contract.probes = s.probes.map((p) => add('contract', { subjectUid: uid, polarity: 'negative', location: p.location, rule: 'probe' })); if (s.bodyVariants?.length) ids.functional.bodyVariants = s.bodyVariants.map((v) => add('functional', { subjectUid: uid, polarity: 'positive', location: v.location, rule: v.kind }, rel)); 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). diff --git a/src/cases/ids.ts b/src/cases/ids.ts index 99c46b8..361e333 100644 --- a/src/cases/ids.ts +++ b/src/cases/ids.ts @@ -18,9 +18,13 @@ export type Polarity = 'positive' | 'negative'; * v4 adds functional/positive request-body variants: `optional-omitted` (on "request.body#": only the required * fields are sent) and `variant` (request.body#/@: branch n of the oneOf / anyOf at that pointer), and * functional/negative `expired-credentials` (request.security; `forbidden` exists since v1). + * v5 adds functional/positive collection rules `sort-reverse` (request.query#//: the + * descending value gives the reverse order) and `total` (response.body#), and contract/negative + * `probe` (request.#//: an exploratory request whose outcome is recorded, never asserted) and a + * second `type` case of an integer parameter (request.#//decimal). * Registries of older versions stay readable. */ -export const CASE_RULE_VOCABULARY_VERSION = 4; +export const CASE_RULE_VOCABULARY_VERSION = 5; const CONSTRAINT_RULES = [ 'required', 'nullable', 'type', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', @@ -29,10 +33,10 @@ const CONSTRAINT_RULES = [ /** Built-in vocabulary v1, by suiteType/polarity. */ export const VOCABULARY_V1: Record = { - 'functional/positive': ['documented-success', 'accepted-value', 'collection-contains', 'filter', 'sort', 'pagination', 'unique', 'fixture', 'optional-omitted', 'variant'], + 'functional/positive': ['documented-success', 'accepted-value', 'collection-contains', 'filter', 'sort', 'pagination', 'unique', 'fixture', 'optional-omitted', 'variant', 'sort-reverse', 'total'], 'functional/negative': ['not-found', 'unauthorized', 'forbidden', 'invalid-credentials', 'expired-credentials', 'method-not-allowed', 'precondition-failed'], 'contract/positive': ['documented', 'schema'], - 'contract/negative': [...CONSTRAINT_RULES, 'content-type'], + 'contract/negative': [...CONSTRAINT_RULES, 'content-type', 'probe'], 'scenario/positive': ['crud', 'business-rule'], 'scenario/negative': ['business-rule'], }; @@ -130,7 +134,8 @@ export function checkCombination(p: CaseParts): CaseIdError | undefined { 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 === 'sort' || p.rule === 'sort-reverse') return /^request\.query#\/[^/]*\/[^/]*$/.test(loc) ? undefined : bad(`${p.rule} names a query parameter and its value`); + if (p.rule === 'total') return loc.startsWith('response.body#/') ? undefined : bad('total names the total-count field of the response body'); 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': @@ -143,6 +148,8 @@ export function checkCombination(p: CaseParts): CaseIdError | undefined { return loc.startsWith('response.status#/') || loc.startsWith('response.content-type#/') ? undefined : bad('documented is checked on a response status or content type'); case 'contract/negative': if (p.rule === 'content-type') return loc === 'request.content-type' ? undefined : bad('content-type is checked on "request.content-type"'); + if (p.rule === 'probe') return /^request\.(query|header|cookie)#\/[^/]*\/[a-z-]+$/.test(loc) ? undefined : bad('probe names a parameter and a probe kind: request.#//'); + if (p.rule === 'type' && /^request\.(query|header|cookie)#\/[^/]*\/decimal$/.test(loc)) return undefined; return /^request\.body#/.test(loc) || /^request\.(query|path|header|cookie)#\/[^/]*$/.test(loc) ? undefined : bad('a constraint rule is checked on a request field or one parameter'); default: // scenario if (loc === 'lifecycle') return p.subjectUid.startsWith('scn_') ? undefined : subject('a lifecycle scenario needs a scn_ subject'); diff --git a/src/cases/validate.ts b/src/cases/validate.ts index c8a9c2f..85d1b3e 100644 --- a/src/cases/validate.ts +++ b/src/cases/validate.ts @@ -199,7 +199,13 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine // 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; + if ((rule === 'sort' || rule === 'sort-reverse') && !Array.isArray(p.schema?.enum) && p.schema?.const === undefined) return undefined; + // probe kinds and the decimal type case name a technique, not a documented value. + if (rule === 'probe') return undefined; + if (rule === 'type' && rawValue === 'decimal') { + const t = Array.isArray(p.schema?.type) ? p.schema.type : [p.schema?.type]; + return t.includes('integer') ? undefined : bad(`the decimal case needs an integer ${m[1]} "${name}"`); + } 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}"`); } @@ -246,7 +252,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', 'unique', 'optional-omitted'].includes(rule) && !ruleFits(r.node, rule)) { + if (!['schema', 'type', 'required', 'nullable', 'enum', 'const', 'unique', 'optional-omitted', 'total'].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 17a0fa0..f2aa55e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -295,6 +295,10 @@ common(program.command('generate').description('audit, then generate Playwright for (const d of ids.duplicates.slice(0, 10)) log(` DUPLICATE ${d}`); for (const u of ids.unregistered.slice(0, 10)) log(` UNREGISTERED ${u}`); } + if (gen.exploratory?.length) { + const notable = gen.exploratory.filter((p) => p.serverError || !p.documented); + log(`Exploratory probes: ${gen.exploratory.length} recorded (never failing), ${notable.length} with a server error or an undocumented status (see the report)`); + } if (gen.cleanupFailures.length) { log(`WARNING: cleanup could not remove ${gen.cleanupFailures.length} record(s); they stay on ${o.baseUrl}:`); for (const line of cleanupSummary(gen.cleanupFailures)) log(` LEFT ${line}`); @@ -312,6 +316,7 @@ common(program.command('generate').description('audit, then generate Playwright files: gen.files.map((f) => resolve(f).replace(process.cwd() + (process.platform === 'win32' ? '\\' : '/'), '').replace(/\\/g, '/')), scenarios: gen.scenarios.map(({ name, status, reason, operations }) => ({ name, status, reason, operations })), cleanupFailures: gen.cleanupFailures, + ...(gen.exploratory?.length ? { exploratory: gen.exploratory } : {}), ...(gen.caseIdCheck ? { caseIdCheck: gen.caseIdCheck } : {}), }, }); @@ -650,7 +655,7 @@ async function capture(specArg: string | undefined, o: CaptureCli) { 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), + collections: (deps?.scenarios ?? []).flatMap((s: any) => [s.collection, ...(Array.isArray(s.collections) ? s.collections : [])]).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.`); diff --git a/src/contract/contract.py b/src/contract/contract.py index 2fb4e7f..04ec63e 100644 --- a/src/contract/contract.py +++ b/src/contract/contract.py @@ -114,6 +114,8 @@ def expect_fields(item: Any, expected: Any, policies: dict) -> None: 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 == "search": # the text contains the value, ignoring case + return str(value).lower() in ("" if v is None else str(v)).lower() if match == "contains": return isinstance(v, list) and str(value) in [str(x) for x in v] return str(v) == str(value) @@ -203,6 +205,17 @@ def poll(fn, done, timeout_ms: int, interval_ms: int): return v +def expect_sent_query(res: Any, name: str, value: Any) -> None: + """The query parameter went over HTTP as intended: its text, or absent (value None).""" + from urllib.parse import parse_qs, urlsplit + + sent = parse_qs(urlsplit(res.request.url).query, keep_blank_values=True).get(name, []) + if value is None: + assert sent == [], f"{name} is not sent, got {sent}" + else: + assert sent == [value], f"{name} is sent as {value!r}, got {sent}" + + def without_fields(payload: Any, ptrs: list) -> Any: """A copy of a payload without the fields at these JSON pointers (array elements by index).""" out = copy.deepcopy(payload) @@ -433,6 +446,20 @@ def expect(self, res: Any, method: str, path: str) -> Any: assert ok, f"CONTRACT_MISMATCH {method.upper()} {path} ({kind}): {'; '.join(errors)}" return None if body is _UNPARSEABLE else body + def record_probe(self, res: Any, info: dict, method: str, path: str) -> dict: + """Exploratory probe (never fails on the API's behavior): records the outcome; a 5xx is flagged, not asserted.""" + content_type, body, raw = _body(res) + self.notes = [] + ok, kind, errors = self.validate(method, path, res.status_code, content_type, body, raw, dict(res.headers)) + observation = {**info, "status": res.status_code, "documented": kind != "undocumented-status", "contract": "matches" if ok else "; ".join(errors), "serverError": res.status_code >= 500} + out = os.environ.get("API_AGENT_EXPLORATORY_LOG") + if out: + with open(out, "a", encoding="utf-8") as f: + f.write(json.dumps(observation) + "\n") + elif observation["serverError"]: + warnings.warn(f"exploratory probe {info} answered {res.status_code} (an observation, not a confirmed defect)", stacklevel=2) + return observation + def expect_rejected(self, res: Any, documented: list[str], method: str, path: str) -> Any: """The request must be rejected with a documented status ("400", "422", "4XX"...), then match the contract.""" s = str(res.status_code) diff --git a/src/generate/collection-render.ts b/src/generate/collection-render.ts index ae22126..65f545b 100644 --- a/src/generate/collection-render.ts +++ b/src/generate/collection-render.ts @@ -34,6 +34,25 @@ function pageEntries(plan: CollectionPlan, i: string, size: string, q: (s: strin return undefined; } +/** A query parameter of the list operation that is required (no unfiltered list without it). */ +const requiredParam = (s: SuiteInput, name: string) => s.op.params.some((p) => p.in === 'query' && p.name === name && p.required); + +/** Read-only filter: candidate values from existing resources (search: a prefix of the text, in upper case). */ +function searchLength(s: SuiteInput, f: { param: string }): number { + const schema: any = s.op.params.find((p) => p.name === f.param)?.schema ?? {}; + return Math.max(typeof schema.minLength === 'number' ? schema.minLength : 1, Math.min(typeof schema.maxLength === 'number' ? schema.maxLength : 8, 8)); +} +function tsCandidates(f: { param: string; match: string }, s: SuiteInput): string { + if (f.match === 'contains') return 'Array.isArray(v) ? v : []'; + if (f.match === 'search') return `typeof v === 'string' && v.length >= ${searchLength(s, f)} ? [v.slice(0, ${searchLength(s, f)}).toUpperCase()] : []`; + return 'v === undefined || v === null ? [] : [v]'; +} +function pyCandidates(f: { param: string; match: string }, s: SuiteInput): string { + if (f.match === 'contains') return 'v if isinstance(v, list) else []'; + if (f.match === 'search') return `[v[:${searchLength(s, f)}].upper()] if isinstance(v, str) and len(v) >= ${searchLength(s, f)} else []`; + return '[] if v is None else [v]'; +} + 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!; @@ -83,12 +102,14 @@ export function tsCollectionPrelude(s: SuiteInput, ci: CollectionInput): string[ } L.push( '', - `async function listPage(api: Apis, params: Record): Promise {`, + `async function listBody(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);`, + ` return res.json();`, `}`, '', + `const listPage = async (api: Apis, params: Record): Promise => itemsOf(await listBody(api, params), 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 @@ -109,6 +130,35 @@ export function tsCollectionPrelude(s: SuiteInput, ci: CollectionInput): string[ `const listUntil = (api: Apis, params: Record, done: (items: unknown[]) => boolean) => poll(() => listAll(api, params), done, POLL.timeoutMs, POLL.intervalMs);`, '', ); + if (c.total) { + L.push( + `const TOTAL = ${js(c.total)};`, + `/** Every page with the total it reports (at most MAX_PAGES); complete: the last page was reached. */`, + `async function listWithTotals(api: Apis, params: Record): Promise<{ items: unknown[]; totals: unknown[]; complete: boolean }> {`, + ` const items: unknown[] = [];`, + ` const totals: unknown[] = [];`, + ...(page + ? [ + ` for (let i = 0; i < MAX_PAGES; i++) {`, + ` const size = WALK;`, + ` const body = await listBody(api, { ...params, ${page} });`, + ` const one = itemsOf(body, ITEMS);`, + ` items.push(...one);`, + ` totals.push(readPointer(body, TOTAL));`, + ` if (one.length < size) return { items, totals, complete: true };`, + ` }`, + ` return { items, totals, complete: false };`, + ] + : [` const body = await listBody(api, params);`, ` items.push(...itemsOf(body, ITEMS));`, ` totals.push(readPointer(body, TOTAL));`, ` return { items, totals, complete: true };`]), + `}`, + `/** One total on every page, and it is the number of resources listed. */`, + `function expectTotal(r: { items: unknown[]; totals: unknown[] }): void {`, + ` expect(new Set(r.totals.map(String)).size, 'the same total on every page: ' + r.totals.join(', ')).toBe(1);`, + ` expect(Number(r.totals[0]), TOTAL + ' is the number of resources listed').toBe(r.items.length);`, + `}`, + '', + ); + } return L; } @@ -151,7 +201,9 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] 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')} }`; + // search: the query in upper case, the data in lower case: matching must ignore case. + const query = f.match === 'search' ? `(${filterValue(t, 'a', 'ts')}).toUpperCase()` : filterValue(t, 'a', 'ts'); + const params = t.filterValues!.kind === 'enum' ? `{ ...ISO(marker), ${js(f.param)}: ${query} }` : `{ ${js(f.param)}: ${query} }`; 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}');`, @@ -164,15 +216,19 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] ` 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);`, + ` const values = [...new Map(all.flatMap((i) => { const v = readPointer(i, ${js(f.field)}); return ${tsCandidates(f, s)}; }).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));`, + ...(requiredParam(s, f.param) + ? [` // ${f.param} is required: there is no unfiltered list to compare with.`] + : [ + ` // 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));`, + ]), ` }`, ` });`, '', @@ -194,6 +250,45 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] ` });`, '', ); + } else if (t.kind === 'sort-reverse' && t.mode === 'controlled') { + const [a, d] = [t.sort!, t.sortDesc!]; + L.push(...tsSeeded(t.title, opts, t.sortValues!.map((v) => `withValue(isolate(await fresh(api), marker), ${js(a.field)}, ${sortValue(v, 'ts')})`), [ + `const order = (xs: unknown[]) => xs.map((i) => String(readPointer(i, ID))).filter((id) => ids.includes(id));`, + `const asc = order(await listUntil(api, { ...ISO(marker), ${js(a.param)}: ${js(a.value)} }, has(...ids)));`, + `const desc = order(await listUntil(api, { ...ISO(marker), ${js(d.param)}: ${js(d.value)} }, has(...ids)));`, + `expect(desc, ${js(`${d.param}=${d.value} is ${a.param}=${a.value} reversed`)}).toEqual([...asc].reverse());`, + ])); + } else if (t.kind === 'sort-reverse') { + const [a, d] = [t.sort!, t.sortDesc!]; + L.push( + ` test(${js(t.title)}, ${opts}, async ({ ${roFixture(s.op)} }) => {`, + ` const values = (xs: unknown[]) => xs.map((i) => readPointer(i, ${js(a.field)}));`, + ` const read = async () => [values(await listAll(api, { ${js(a.param)}: ${js(a.value)} })), values(await listAll(api, { ${js(d.param)}: ${js(d.value)} }))];`, + ` let [asc, desc] = await read();`, + ` test.skip(asc.length < 2, 'fewer than 2 resources: the orders cannot be compared (read-only check)');`, + ` // Ties keep equal values in place, so the values (not the ids) must mirror; shared data moves: read once more.`, + ` if (JSON.stringify(desc) !== JSON.stringify([...asc].reverse())) [asc, desc] = await read();`, + ` expect(desc, ${js(`${d.param}=${d.value} is ${a.param}=${a.value} reversed`)}).toEqual([...asc].reverse());`, + ` });`, + '', + ); + } else if (t.kind === 'total' && t.mode === 'controlled') { + L.push(...tsSeeded(t.title, opts, [iso('await fresh(api)'), iso('await fresh(api)')], [ + `const r = await poll(() => listWithTotals(api, ISO(marker)), (x) => has(...ids)(x.items), POLL.timeoutMs, POLL.intervalMs);`, + `expectTotal(r);`, + `expect(r.items.length, 'only the resources the test created').toBe(ids.length);`, + ])); + } else if (t.kind === 'total') { + L.push( + ` test(${js(t.title)}, ${opts}, async ({ ${roFixture(s.op)} }) => {`, + ` let r = await listWithTotals(api, {});`, + ` test.skip(!r.complete, 'more than MAX_PAGES pages: the total cannot be compared with every resource (read-only check)');`, + ` // Shared data moves between pages: read once more before failing.`, + ` if (new Set(r.totals.map(String)).size !== 1 || Number(r.totals[0]) !== r.items.length) r = await listWithTotals(api, {});`, + ` expectTotal(r);`, + ` });`, + '', + ); } 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)')), [ @@ -220,7 +315,7 @@ export function tsCollectionTests(s: SuiteInput, ci: CollectionInput): string[] `const items = await listUntil(api, ISO(marker), has(...ids));`, `expectUniqueBy(items, ${js(t.unique)});`, ])); - } else { + } else if (t.kind === 'unique') { L.push(` test(${js(t.title)}, ${opts}, async ({ ${roFixture(s.op)} }) => {`, ` expectUniqueBy(await listAll(api, {}), ${js(t.unique)});`, ` });`, ''); } }); @@ -322,10 +417,14 @@ export function pyCollectionPrelude(s: SuiteInput, ci: CollectionInput): string[ ); } L.push( - 'def _list_page(api, params):', + 'def _list_body(api, params):', ` res = api.${op.method}(${pathExpr(op)}, params={**${py(req)}, **params}${pyRequired(op, ['params'])})`, ` ${assertSuccess(op)}`, - ' return items_of(res.json(), ITEMS)', + ' return res.json()', + '', + '', + 'def _list_page(api, params):', + ' return items_of(_list_body(api, params), ITEMS)', '', '', 'def _list_pages(api, params, size=WALK):', @@ -355,6 +454,40 @@ export function pyCollectionPrelude(s: SuiteInput, ci: CollectionInput): string[ '', '', ); + if (c.total) { + L.push( + `TOTAL = ${py(c.total)}`, + '', + '', + 'def _list_with_totals(api, params):', + ' # Every page with the total it reports (at most MAX_PAGES); complete: the last page was reached.', + ' items, totals = [], []', + ...(page + ? [ + ' size = WALK', + ' for i in range(MAX_PAGES):', + ` body = _list_body(api, {**params, ${page}})`, + ' one = items_of(body, ITEMS)', + ' items.extend(one)', + ' totals.append(read_pointer(body, TOTAL))', + ' if len(one) < size:', + ' return items, totals, True', + ' return items, totals, False', + ] + : [' body = _list_body(api, params)', ' items.extend(items_of(body, ITEMS))', ' totals.append(read_pointer(body, TOTAL))', ' return items, totals, True']), + '', + '', + 'def _total_ok(items, totals):', + ' return len({str(t) for t in totals}) == 1 and totals[0] == len(items)', + '', + '', + 'def _expect_total(items, totals):', + ' assert len({str(t) for t in totals}) == 1, f"the same total on every page: {totals}"', + ' assert totals[0] == len(items), f"{TOTAL} is the number of resources listed: {totals[0]} != {len(items)}"', + '', + '', + ); + } return L; } @@ -407,7 +540,8 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] 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')}}`; + const query = f.match === 'search' ? `(${filterValue(t, 'a', 'py')}).upper()` : filterValue(t, 'a', 'py'); + const params = t.filterValues!.kind === 'enum' ? `{**_iso(marker), ${py(f.param)}: ${query}}` : `{${py(f.param)}: ${query}}`; 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}`)})`, @@ -416,7 +550,7 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] ])); } 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]'; + const values = pyCandidates(f, s); L.push( mark, `def ${nameOf(`test_filter_${f.param}_returns_only_matching`)}(${pyRoFixture(s.op)}):`, @@ -433,11 +567,15 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] ` 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))`, + ...(requiredParam(s, f.param) + ? [` # ${f.param} is required: there is no unfiltered list to compare with.`] + : [ + ' # 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))`, + ]), '', '', ); @@ -462,6 +600,57 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] '', '', ); + } else if (t.kind === 'sort-reverse' && t.mode === 'controlled') { + const [a, d] = [t.sort!, t.sortDesc!]; + L.push(...pySeeded(nameOf(`test_sort_${a.param}_${d.value.replace(/^-/, 'desc_')}_reverses_${a.value}`), mark, fx, t.sortValues!.map((v) => `with_value(_isolate(${fresh}, marker), ${py(a.field)}, ${sortValue(v, 'py')})`), [ + 'def order(xs):', + ' return [str(read_pointer(i, ID)) for i in xs if str(read_pointer(i, ID)) in ids]', + '', + `asc = order(_list_until(api, {**_iso(marker), ${py(a.param)}: ${py(a.value)}}, _has(*ids)))`, + `desc = order(_list_until(api, {**_iso(marker), ${py(d.param)}: ${py(d.value)}}, _has(*ids)))`, + `assert desc == list(reversed(asc)), ${py(`${d.param}=${d.value} is ${a.param}=${a.value} reversed`)}`, + ])); + } else if (t.kind === 'sort-reverse') { + const [a, d] = [t.sort!, t.sortDesc!]; + L.push( + mark, + `def ${nameOf(`test_sort_${a.param}_${d.value.replace(/^-/, 'desc_')}_reverses_${a.value}`)}(${pyRoFixture(s.op)}):`, + ...pyRoAlias(s.op), + ' def read():', + ` asc = [read_pointer(i, ${py(a.field)}) for i in _list_all(api, {${py(a.param)}: ${py(a.value)}})]`, + ` desc = [read_pointer(i, ${py(a.field)}) for i in _list_all(api, {${py(d.param)}: ${py(d.value)}})]`, + ' return asc, desc', + '', + ' asc, desc = read()', + ' if len(asc) < 2:', + ' pytest.skip("fewer than 2 resources: the orders cannot be compared (read-only check)")', + ' # Ties keep equal values in place, so the values (not the ids) must mirror; shared data moves: read once more.', + ' if desc != list(reversed(asc)):', + ' asc, desc = read()', + ` assert desc == list(reversed(asc)), ${py(`${d.param}=${d.value} is ${a.param}=${a.value} reversed`)}`, + '', + '', + ); + } else if (t.kind === 'total' && t.mode === 'controlled') { + L.push(...pySeeded(nameOf('test_total_equals_the_number_of_resources'), mark, fx, [iso(fresh), iso(fresh)], [ + 'listed, totals, _ = poll(lambda: _list_with_totals(api, _iso(marker)), lambda r: _has(*ids)(r[0]), POLL_TIMEOUT_MS, POLL_INTERVAL_MS)', + '_expect_total(listed, totals)', + 'assert len(listed) == len(ids), f"only the resources the test created: {len(listed)} != {len(ids)}"', + ])); + } else if (t.kind === 'total') { + L.push( + mark, + `def ${nameOf('test_total_equals_the_number_of_resources')}(${pyRoFixture(s.op)}):`, + ...pyRoAlias(s.op), + ' listed, totals, complete = _list_with_totals(api, {})', + ' if not complete:', + ' pytest.skip("more than MAX_PAGES pages: the total cannot be compared with every resource (read-only check)")', + ' if not _total_ok(listed, totals): # shared data moves between pages: read once more', + ' listed, totals, _ = _list_with_totals(api, {})', + ' _expect_total(listed, totals)', + '', + '', + ); } 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)), [ @@ -494,7 +683,7 @@ export function pyCollectionTests(s: SuiteInput, ci: CollectionInput): string[] `found = _list_until(api, _iso(marker), _has(*ids))`, `expect_unique_by(found, ${py(t.unique)})`, ])); - } else { + } else if (t.kind === '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)})`, '', ''); } }); diff --git a/src/generate/collection-tests.ts b/src/generate/collection-tests.ts index 65d9a39..2ff440c 100644 --- a/src/generate/collection-tests.ts +++ b/src/generate/collection-tests.ts @@ -12,8 +12,8 @@ import { schemaAt, type ResolvedCollection } from './collection.js'; * 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 type CollectionTestKind = 'listed' | 'filter' | 'sort' | 'sort-reverse' | 'pagination' | 'unique' | 'total'; +type Filter = { param: string; field: string; match: 'equals' | 'contains' | 'search' }; export interface CollectionTest { kind: CollectionTestKind; @@ -23,6 +23,8 @@ export interface CollectionTest { /** 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' }; + /** sort-reverse: the descending counterpart of `sort` (same parameter and field). */ + sortDesc?: { 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; @@ -60,6 +62,15 @@ export function planCollectionTests(doc: OpenApiDoc, c: ResolvedCollection, x: { if (!s) return false; return f.match === 'contains' ? typesOf(s).includes('array') && markerString(schemaAt(doc, s, '/*')) && (s.maxItems ?? 1) >= 1 : markerString(s); }; + const sortValuesOf = (field: string) => { + const s = iso ? createField(field) : undefined; + if (!s || s.enum) return undefined; + if (typesOf(s).some((t) => t === 'integer' || t === 'number')) { + const lo = typeof s.minimum === 'number' ? s.minimum + (s.exclusiveMinimum === true ? 1 : 0) : 1; + return typeof s.maximum !== 'number' || s.maximum >= lo + 2 ? [lo + 2, lo, lo + 1] : undefined; + } + return markerString(s) ? ['sort-c-', 'sort-a-', 'sort-b-'] : undefined; + }; const filters = (c.filters ?? []).filter((f, i, all) => all.findIndex((g) => g.param === f.param) === i); const iso = filters.find(markerFilter); @@ -82,36 +93,42 @@ export function planCollectionTests(doc: OpenApiDoc, c: ResolvedCollection, x: { 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`, + title: (filterValues ? `filter ${f.param} returns the matching resource and leaves out the other` : `filter ${f.param} returns only matching resources`) + (f.match === 'search' ? ' (search, ignoring case)' : ''), 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-']; - } + const sorts = (c.sorts ?? []).filter((v, i, all) => all.findIndex((w) => w.param === v.param && w.value === v.value) === i); + for (const s of sorts) { + const sortValues = sortValuesOf(s.field); 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 } : {}) }); } + // Ascending and descending on the same field: the descending order is the ascending one reversed. + for (const asc of sorts.filter((s) => s.order === 'asc')) { + const desc = sorts.find((s) => s.order === 'desc' && s.param === asc.param && s.field === asc.field); + if (!desc) continue; + const sortValues = sortValuesOf(asc.field); + tests.push({ kind: 'sort-reverse', title: `sort ${asc.param}=${desc.value} is the reverse of ${asc.param}=${asc.value}`, mode: sortValues ? 'controlled' : 'read-only', sort: asc, sortDesc: desc, ...(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 (c.total) tests.push({ kind: 'total', title: `${c.total} equals the number of resources and is the same on every page`, mode: iso ? 'controlled' : 'read-only' }); + else gaps.push({ code: 'UNCONFIRMED_BUSINESS_RULE', location: 'operation', reason: `${c.op.key}: no reviewed "total" pointer: the total count is not checked` }); 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)); + // Without the isolating filter after the update, a list with a required query parameter cannot be read in full. + const requiredQuery = c.op.params.some((p) => p.in === 'query' && p.required); + const lifecycle = x.canCreate && x.canUpdate && x.canDelete && Object.keys(c.fields ?? {}).length > 0 && (lifecycleIso || !requiredQuery); + if (!lifecycle && x.canCreate && x.canUpdate && x.canDelete && requiredQuery && !lifecycleIso) gaps.push({ code: 'CANNOT_ISOLATE_RULE', location: 'lifecycle', reason: `${c.op.key}: the update changes the isolating field and the list needs a required query parameter, so the updated resource cannot be found reliably` }); + else 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` }); return { c, tests, ...(iso ? { iso } : {}), lifecycle, lifecycleIso, gaps, walkSize, pageSize }; } diff --git a/src/generate/collection.ts b/src/generate/collection.ts index 4692d15..18f0c79 100644 --- a/src/generate/collection.ts +++ b/src/generate/collection.ts @@ -12,7 +12,9 @@ import type { CoverageGap } from './body-cases.js'; * "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" }], + * "total": "/total", JSON pointer to the total count in the response (consistent across pages) + * "filters": [{ "param": "tag", "field": "/tags", "match": "contains" }], equals | contains (array) | search + * (search: the string field contains the value, ignoring case) * "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, @@ -34,7 +36,8 @@ export interface CollectionConfig { id: string; fields?: Record; unique?: string[]; - filters?: { param: string; field: string; match: 'equals' | 'contains' }[]; + filters?: { param: string; field: string; match: 'equals' | 'contains' | 'search' }[]; + total?: string; 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; size?: number; firstPage?: number; maxPages?: number }; consistency?: { pollTimeoutMs: number; pollIntervalMs: number }; @@ -103,7 +106,8 @@ export function resolveCollection(doc: OpenApiDoc, ops: Operation[], cfg: Collec 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`); + if (!['equals', 'contains', 'search'].includes(f.match)) errors.push(`collection: filter match "${f.match}" is equals, contains or search`); + if (f.match === 'search' && itemSchema && !typesOf(schemaAt(doc, itemSchema, f.field)).includes('string')) errors.push(`collection: search filter field "${f.field}" is not a string`); } for (const s of cfg.sorts ?? []) { query(s.param, 'sort parameter'); @@ -125,6 +129,10 @@ export function resolveCollection(doc: OpenApiDoc, ops: Operation[], cfg: Collec } 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"'); + if (cfg.total !== undefined) { + const t = typeof cfg.total === 'string' && cfg.total.startsWith('/') ? schemaAt(doc, response, cfg.total) : undefined; + if (!t || !typesOf(t).includes('integer')) errors.push(`collection: "total" ${cfg.total} is not an integer field of the ${op.key} response`); + } 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/generate.ts b/src/generate/generate.ts index 025e576..1e8e526 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -17,13 +17,15 @@ import { paramCasesDetailed, sendable } from './param-cases.js'; import { checkAuthConfig, errorPlan } from './error-cases.js'; import { collectionGaps, resolveCollection } from './collection.js'; import { bodyVariants as variantsOf, type BodyVariant } from './variants.js'; +import { paramProbes } from './probes.js'; +import { encodeSegment, location } from '../cases/ids.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'; -import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; +import { CONTRACT_ASSERT, MAX_VALUES_PER_OPERATION, MAX_VALUES_PER_PARAM, queryVariantsDetailed, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; import { API_BASE, buildApiIndex, renderApiBaseClass, renderApiChildClass, renderApis } from './api-objects.js'; import { PY_FILES, pyName, renderConftest, renderPyContract, renderPyFunctional, renderPyResource, renderPyScenarios, resourceModule } from './python.js'; @@ -69,10 +71,24 @@ export interface GenerateResult { coverage: Coverage[]; /** Test data the generated cleanup could not remove during --run (it stays on the target). */ cleanupFailures: CleanupFailure[]; + /** Exploratory probe outcomes of a --run: observations, never confirmed defects. */ + exploratory?: ExploratoryObservation[]; /** After --run: every physical test has its own registered case ID. */ caseIdCheck?: CaseIdCheck; } +export interface ExploratoryObservation { + caseId?: string; + operation: string; + parameter: string; + probe: string; + value: string | null; + status: number; + documented: boolean; + contract: string; + serverError: boolean; +} + export interface CleanupFailure { operation: string; id: string; @@ -251,12 +267,12 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp // 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 ?? ''; + for (const chain of chains) for (const cfg of chain.collections ?? []) { + const r = resolveCollection(spec.doc, ops, cfg); + const key = ops.find((x) => x.operationId === cfg.operationId)?.key ?? ''; const p = plans.find((x) => x.chain === chain); - if (r.collection && p) collectionOf.set(r.collection.op, { plan: p, c: r.collection }); + if (r.collection && p && collectionOf.has(r.collection.op)) collectionErrors.set(key, [...(collectionErrors.get(key) ?? []), { code: 'INVALID_REVIEWED_CONFIG', location: 'operation', reason: `collection: ${key} is mapped twice in the deps file` }]); + else 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` }); @@ -399,9 +415,15 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp if (variantResult.variants.length) input.bodyVariants = variantResult.variants; } } + // Exploratory query probes: recorded, never asserted (src/generate/probes.ts). + const probed = op.deprecated ? { probes: [], gaps: [] } : paramProbes(op, qCases); + if (input.positive && !plan && op.method === 'get') { + for (const d of queryVariantsDetailed(op).dropped) probed.gaps.push({ code: 'CASE_LIMIT_REACHED', location: `${location.query(d.name)}/${encodeSegment(String(d.value))}`, rule: 'accepted-value', reason: `more than ${MAX_VALUES_PER_PARAM} values of a parameter or ${MAX_VALUES_PER_OPERATION} of an operation: ${d.name}=${String(d.value)} is not sent` }); + } + if (probed.probes.length) input.probes = probed.probes; 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, collection: collPlan, collectionChain: coll?.plan.chain, fixture: !!fixture, bodyVariants: input.bodyVariants }, 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, bodyVariants: input.bodyVariants, probes: input.probes }, 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). @@ -429,7 +451,7 @@ 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, ...collGaps], + gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps, ...collGaps, ...probed.gaps], ...(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: { @@ -627,26 +649,31 @@ export async function runGenerated(result: GenerateResult, env: { baseUrl: strin if (!specs.length) return; // The generated cleanup appends one JSON line per record it could not remove. const cleanupLog = resolve(outDir, 'cleanup-failures.jsonl'); + const exploratoryLog = resolve(outDir, 'exploratory.jsonl'); await mkdir(dirname(cleanupLog), { recursive: true }); await rm(cleanupLog, { force: true }); + await rm(exploratoryLog, { force: true }); const casesOut = resolve(outDir, 'collected-cases.jsonl'); await rm(casesOut, { force: true }); - const runEnv = { ...process.env, API_BASE_URL: env.baseUrl, API_AGENT_CLEANUP_LOG: cleanupLog, API_AGENT_CASES_OUT: casesOut }; + const runEnv = { ...process.env, API_BASE_URL: env.baseUrl, API_AGENT_CLEANUP_LOG: cleanupLog, API_AGENT_EXPLORATORY_LOG: exploratoryLog, API_AGENT_CASES_OUT: casesOut }; await (lang === 'python' ? runPytest(specs, runEnv, outDir) : runPlaywright(specs, runEnv, outDir)); // Every physical test that ran (or was collected) must carry its own case ID from the registry. const collected = lang === 'python' ? await readCollected(casesOut) : await playwrightCaseIds(resolve(outDir, 'playwright-results.json')); const registryFile = result.files.find((f) => /[\\/]_support[\\/]cases\.json$/.test(f)); const registered = registryFile && existsSync(registryFile) ? new Set(Object.keys(JSON.parse(await readFile(registryFile, 'utf8')).cases ?? {})) : new Set(); result.caseIdCheck = checkCaseIds(collected, registered); - result.cleanupFailures = existsSync(cleanupLog) - ? (await readFile(cleanupLog, 'utf8')).split('\n').filter((l) => l.trim()).flatMap((l) => { - try { - return [JSON.parse(l) as CleanupFailure]; - } catch { - return []; - } - }) - : []; + const lines = async (file: string): Promise => + existsSync(file) + ? (await readFile(file, 'utf8')).split('\n').filter((l) => l.trim()).flatMap((l) => { + try { + return [JSON.parse(l) as T]; + } catch { + return []; + } + }) + : []; + result.cleanupFailures = await lines(cleanupLog); + result.exploratory = await lines(exploratoryLog); } export interface CaseIdCheck { diff --git a/src/generate/graph.ts b/src/generate/graph.ts index 3040cad..b6fb821 100644 --- a/src/generate/graph.ts +++ b/src/generate/graph.ts @@ -24,8 +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; + /** The reviewed list operations that show this resource (deps file "collection" / "collections"), checked in resolveCollection. */ + collections?: CollectionConfig[]; } export interface FillRule { @@ -61,9 +61,15 @@ export interface DepsFile { echoes?: string[]; /** The list operation of this resource and its confirmed semantics (src/generate/collection.ts). */ collection?: CollectionConfig; + /** Several list operations of this resource (e.g. a list and a search), each with its own mapping. */ + collections?: CollectionConfig[]; }[]; } +/** "collection" (one) and "collections" (several) of a deps entry, in that order. */ +const collectionsOf = (s: { collection?: CollectionConfig; collections?: CollectionConfig[] }): CollectionConfig[] => + [...(s.collection && typeof s.collection === 'object' ? [s.collection] : []), ...(Array.isArray(s.collections) ? s.collections.filter((c) => c && typeof c === 'object') : [])]; + const RUNTIME_EXPR = /^\$response\.body#(\/.*)$/; export function findChains(doc: OpenApiDoc, ops: Operation[], deps?: DepsFile): { chains: CrudChain[]; candidates: Candidate[] } { @@ -86,7 +92,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 } : {}), + ...(collectionsOf(s).length ? { collections: collectionsOf(s) } : {}), }); } diff --git a/src/generate/negative.ts b/src/generate/negative.ts index 45a11ae..f5fa70f 100644 --- a/src/generate/negative.ts +++ b/src/generate/negative.ts @@ -16,9 +16,11 @@ export interface NegCase { data?: unknown; query?: Record; /** What the case breaks, for its case ID: a body field (path from the root; [] = the body) or a parameter, and the rule. */ - target?: { in: 'body'; path: (string | typeof ARRAY)[]; rule: string } | { in: 'query' | 'header' | 'cookie' | 'path'; field: string | null; rule: string }; + target?: { in: 'body'; path: (string | typeof ARRAY)[]; rule: string } | { in: 'query' | 'header' | 'cookie' | 'path'; field: string | null; rule: string; variant?: 'decimal' }; /** Parameter cases: the whole request (valid parameters plus the one under test). */ request?: ParamRequest; + /** Query cases: the value of the parameter under test on the wire (null = not sent), checked against the request URL. */ + sent?: { name: string; value: string | null }; } diff --git a/src/generate/param-cases.ts b/src/generate/param-cases.ts index 94d9522..0348380 100644 --- a/src/generate/param-cases.ts +++ b/src/generate/param-cases.ts @@ -173,7 +173,30 @@ export function paramCasesDetailed(doc: OpenApiDoc, op: Operation, opts: { allow } if (Object.keys(headers).length) request.headers = headers; const title = c.title.replace(/^"([^"]*)"/, `${where} "$1"`).replace(/^missing required field "([^"]*)"/, `missing required ${where} "$1"`); - cases.push({ title, source: `${where}.${p.name}.${rule}`, request, target: { in: where, field: p.name, rule } }); + cases.push({ title, source: `${where}.${p.name}.${rule}`, request, target: { in: where, field: p.name, rule }, ...(where === 'query' && !Array.isArray(v) ? { sent: { name: p.name, value: missing ? null : String(v) } } : {}) }); + } + // An integer parameter given a decimal: numeric text, so a lenient parser may round it, but not an integer. + // The value stays inside the documented bounds, so only the type is broken; not with multipleOf > 1. + if (t === 'integer' && where !== 'path') { + const at = typeof value === 'number' ? value : typeof s.minimum === 'number' ? s.minimum : 1; + const inRange = (x: number) => (typeof s.minimum !== 'number' || x >= s.minimum) && (typeof s.maximum !== 'number' || x <= s.maximum) && (typeof s.exclusiveMinimum !== 'number' || x > s.exclusiveMinimum) && (typeof s.exclusiveMaximum !== 'number' || x < s.exclusiveMaximum); + const decimal = [at + 0.5, at - 0.5].find(inRange); + if (typeof s.multipleOf === 'number' && s.multipleOf !== 1) gaps.push({ code: 'CANNOT_ISOLATE_RULE', location: loc, rule: 'type', reason: `a decimal would also break multipleOf ${s.multipleOf}` }); + else if (Array.isArray(s.enum)) gaps.push({ code: 'CANNOT_ISOLATE_RULE', location: loc, rule: 'type', reason: 'a decimal would also break enum; the enum case covers it' }); + else if (decimal === undefined) gaps.push({ code: 'CANNOT_ISOLATE_RULE', location: loc, rule: 'type', reason: 'no decimal fits inside the documented bounds' }); + else { + const params = { ...base.params }; + const headers = { ...base.headers }; + const request: ParamRequest = {}; + if (where === 'query') request.params = { ...params, [p.name]: String(decimal) }; + else { + if (Object.keys(params).length) request.params = params; + if (where === 'header') headers[p.name] = String(decimal); + else headers.Cookie = [...(headers.Cookie ?? '').split('; ').filter((x) => x && !x.startsWith(`${p.name}=`)), `${p.name}=${decimal}`].join('; '); + } + if (Object.keys(headers).length) request.headers = headers; + cases.push({ title: `${where} "${p.name}" is a decimal (${decimal}), not an integer`, source: `${where}.${p.name}.type.decimal`, request, target: { in: where, field: p.name, rule: 'type', variant: 'decimal' }, ...(where === 'query' ? { sent: { name: p.name, value: String(decimal) } } : {}) }); + } } } return { cases, gaps }; diff --git a/src/generate/probes.ts b/src/generate/probes.ts new file mode 100644 index 0000000..86ba3b8 --- /dev/null +++ b/src/generate/probes.ts @@ -0,0 +1,122 @@ +import type { Operation } from '../types.js'; +import { location } from '../cases/ids.js'; +import type { CoverageGap } from './body-cases.js'; +import type { NegCase } from './negative.js'; +import { requiredRequest, sendable } from './param-cases.js'; + +/** + * Exploratory query-parameter probes (docs/SUPPORT_MATRIX.md, "Parameters: exploratory probes"). + * + * Inputs a real client sends by mistake: an empty value, text where a number is expected, a decimal for an integer, + * zero, a negative number, a very large number, special characters, another spelling of a boolean or an enum value, + * and a missing required parameter. What the API must answer is NOT specified for them (or no rejection is + * documented), so a probe never asserts the API's behavior: it records what came back (status, documented or not, + * server error, contract mismatch) as an observation. Confirmed checks stay in the constraint cases; a value that a + * confirmed case already sends is not probed again. Only safe operations (GET / HEAD) are probed. + */ + +export type ProbeKind = 'empty' | 'text' | 'decimal' | 'zero' | 'negative' | 'large' | 'special' | 'numeric' | 'case' | 'missing'; + +export interface Probe { + param: string; + kind: ProbeKind; + /** Location for the case ID: request.query#//. */ + location: string; + title: string; + /** The whole query (required parameters with their documented values plus the probe). */ + params: Record; + /** The probe's value on the wire; null = the parameter is not sent. */ + value: string | null; +} + +export const MAX_PROBES_PER_OPERATION = 24; + +const typeOf = (s: any): string | undefined => (Array.isArray(s?.type) ? s.type.find((t: string) => t !== 'null') : s?.type); + +/** The probe values of one scalar parameter, by kind, before deduplication. */ +function candidates(schema: any, required: boolean): { kind: ProbeKind; value: string | null; why: string }[] { + const t = typeOf(schema); + const out: { kind: ProbeKind; value: string | null; why: string }[] = []; + if (required) out.push({ kind: 'missing', value: null, why: 'the required parameter is not sent' }); + out.push({ kind: 'empty', value: '', why: 'an empty value' }); + if (t === 'integer' || t === 'number') { + out.push({ kind: 'text', value: 'abc', why: 'text where a number is expected' }); + if (t === 'integer') out.push({ kind: 'decimal', value: '1.5', why: 'a decimal for an integer' }); + out.push({ kind: 'zero', value: '0', why: 'zero' }); + out.push({ kind: 'negative', value: '-1', why: 'a negative number' }); + out.push({ kind: 'large', value: '99999999999999999999', why: 'a number beyond 64-bit integers' }); + } else if (t === 'boolean') { + out.push({ kind: 'text', value: 'maybe', why: 'text that is not a boolean' }); + out.push({ kind: 'numeric', value: '1', why: '1 instead of true' }); + } else if (t === 'string') { + if (Array.isArray(schema.enum) && typeof schema.enum[0] === 'string') { + const other = schema.enum[0].toUpperCase() === schema.enum[0] ? schema.enum[0].toLowerCase() : schema.enum[0].toUpperCase(); + if (other !== schema.enum[0] && !schema.enum.includes(other)) out.push({ kind: 'case', value: other, why: 'a documented value in another letter case' }); + } else { + out.push({ kind: 'special', value: `'"<>%;&`, why: 'special characters' }); + if (typeof schema.maxLength !== 'number') out.push({ kind: 'large', value: 'x'.repeat(1000), why: '1000 characters, no documented maximum' }); + } + } + return out; +} + +/** Probe kinds a confirmed constraint case of the parameter already exercises (logically equivalent inputs). */ +function coveredKinds(schema: any, cases: NegCase[]): Set { + const rules = new Set(cases.map((c) => (c.target && c.target.in !== 'body' && c.target.variant ? `${c.target.rule}/${c.target.variant}` : c.target?.rule))); + const out = new Set(); + if (rules.has('required')) out.add('missing'); + if (rules.has('type')) out.add('text'); // non-numeric / non-boolean text + if (rules.has('type/decimal')) out.add('decimal'); + const lowRule = rules.has('minimum') || rules.has('exclusiveMinimum'); + const low = typeof schema.minimum === 'number' ? schema.minimum : typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined; + if (lowRule && low !== undefined && low >= 0) out.add('negative'); // below a non-negative minimum + if (lowRule && low !== undefined && (low > 0 || (low === 0 && (schema.exclusiveMinimum === true || schema.exclusiveMinimum === 0)))) out.add('zero'); + // Inside the documented range a value is valid by the spec, not an open question. + const inRange = (v: number) => (typeof schema.minimum !== 'number' || v >= schema.minimum) && (typeof schema.maximum !== 'number' || v <= schema.maximum) && (typeof schema.exclusiveMinimum !== 'number' || v > schema.exclusiveMinimum) && (typeof schema.exclusiveMaximum !== 'number' || v < schema.exclusiveMaximum); + const bounded = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum'].some((k) => typeof schema[k] === 'number'); + if (bounded && inRange(0)) out.add('zero'); + if (bounded && inRange(-1)) out.add('negative'); + if (rules.has('maximum') || rules.has('exclusiveMaximum')) out.add('large'); + if (rules.has('maxLength')) out.add('large'); + if (rules.has('minLength') && (schema.minLength ?? 0) >= 1) out.add('empty'); + return out; +} + +/** + * Probes of an operation. `confirmed` are its constraint cases: a value they already send for a parameter (and, + * for a required parameter, its absence) is not probed again. + */ +export function paramProbes(op: Operation, confirmed: NegCase[]): { probes: Probe[]; gaps: CoverageGap[] } { + const probes: Probe[] = []; + const gaps: CoverageGap[] = []; + const query = op.params.filter((p) => p.in === 'query' && sendable(p) && ['integer', 'number', 'boolean', 'string'].includes(typeOf(p.schema) ?? '')); + if (!query.length) return { probes, gaps }; + if (!['get', 'head'].includes(op.method)) { + gaps.push({ code: 'UNSAFE_LIVE_CHECK', location: 'operation', rule: 'probe', reason: `exploratory query probes are sent to GET / HEAD only: ${op.key} could change data` }); + return { probes, gaps }; + } + const base = requiredRequest(op); + if (base.missing.length) return { probes, gaps }; // no valid request to start from: paramCases reports it + const unknownPath = op.params.filter((p) => p.in === 'path' && p.knownValue === undefined); + if (unknownPath.length) { + gaps.push({ code: 'MISSING_RESOURCE_SOURCE', location: 'operation', rule: 'probe', reason: `no value for ${unknownPath.map((p) => `path "${p.name}"`).join(', ')}: a missing resource would answer before the parameter is read` }); + return { probes, gaps }; + } + for (const p of query) { + const sent = new Set(confirmed.filter((c) => c.sent?.name === p.name).map((c) => (c.sent!.value === null ? '\u0000missing' : c.sent!.value))); + const covered = coveredKinds(p.schema ?? {}, confirmed.filter((c) => c.target && c.target.in === 'query' && c.target.field === p.name)); + for (const c of candidates(p.schema ?? {}, !!p.required)) { + // A confirmed case already sends this value, or one equivalent to it (same documented rule): no probe. + if (sent.has(c.value === null ? '\u0000missing' : c.value) || covered.has(c.kind)) continue; + const params = { ...base.params }; + delete params[p.name]; + if (c.value !== null) params[p.name] = c.value; + probes.push({ param: p.name, kind: c.kind, location: `${location.query(p.name)}/${c.kind}`, title: `query "${p.name}": ${c.why}${c.value !== null && c.value.length <= 24 ? ` (${JSON.stringify(c.value)})` : ''}`, params, value: c.value }); + } + } + if (probes.length > MAX_PROBES_PER_OPERATION) { + for (const p of probes.slice(MAX_PROBES_PER_OPERATION)) gaps.push({ code: 'CASE_LIMIT_REACHED', location: p.location, rule: 'probe', reason: `more than ${MAX_PROBES_PER_OPERATION} probes for ${op.key}` }); + probes.length = MAX_PROBES_PER_OPERATION; + } + return { probes, gaps }; +} diff --git a/src/generate/python.ts b/src/generate/python.ts index cea5202..ed23390 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -255,6 +255,7 @@ def pytest_configure(config): "scenario": "multi-request flows", "positive": "the request is expected to succeed / the response to conform", "negative": "the request is expected to be rejected", + "exploratory": "a probe that records the API's answer and never fails on it", }.items(): config.addinivalue_line("markers", f"{name}: {text}") config.addinivalue_line("markers", "api_case_id(id): stable case ID from _support/cases.json") @@ -283,6 +284,9 @@ class ApiClient(requests.Session): def request(self, method, url, *args, **kwargs): kwargs.setdefault("timeout", 30) + # Query booleans as JSON text (true / false), like the TypeScript suite; requests would send True / False. + if isinstance(kwargs.get("params"), dict): + kwargs["params"] = {k: ("true" if v is True else "false" if v is False else v) for k, v in kwargs["params"].items()} return super().request(method, self.base_url + url.lstrip("/"), *args, **kwargs) @@ -509,8 +513,8 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { const base = requiredRequest(op).params; L.push('QUERY_VALUES = ['); variants.forEach((v, n) => L.push(` pytest.param(${pyLit({ ...base, [v.name]: v.value }, 4)}, id=${str(`${v.name}=${String(v.value)}`)}${paramMarks(s.ids?.functional.variants[n])}),`)); - L.push(']', '', '', POS, '@pytest.mark.parametrize("params", QUERY_VALUES)', 'def test_accepts_documented_query_value(api, params):'); - L.push(` res = api.${op.method}(${pathExpr(op)}, params=params${pyRequired(op, ['params'])})`, ` ${assertSuccess(op)}`, '', ''); + L.push(']', '', '', POS, '@pytest.mark.parametrize("params", QUERY_VALUES)', 'def test_accepts_documented_query_value(api, contract, params):'); + L.push(` res = api.${op.method}(${pathExpr(op)}, params=params${pyRequired(op, ['params'])})`, ` ${assertSuccess(op)}`, ` contract.expect(res, ${str(op.method)}, ${str(op.path)}) # an accepted value must still give a documented response`, '', ''); } 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'))); @@ -679,12 +683,46 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { L.push('INVALID_PARAMETERS = ['); s.paramCases.forEach((c, n) => { const r = c.request ?? (c.query ? { params: c.query as Record } : {}); - const parts = Object.fromEntries(Object.entries({ params: r.params, headers: r.headers, path: r.path }).filter(([, v]) => v !== undefined)); + const parts = Object.fromEntries(Object.entries({ params: r.params, headers: r.headers, path: r.path, sent: c.sent }).filter(([, v]) => v !== undefined)); L.push(` pytest.param(${pyLit(parts, 4)}, id=${str(c.title)}${paramMarks(s.ids?.contract.params[n])}), # ${c.source}`); }); - L.push(']', '', '', NEG, '@pytest.mark.parametrize("parts", INVALID_PARAMETERS)', 'def test_rejects_invalid_parameter(api, contract, parts):'); + L.push(']', '', '', 'from contract import expect_sent_query # noqa: E402', '', '', NEG, '@pytest.mark.parametrize("parts", INVALID_PARAMETERS)', 'def test_rejects_invalid_parameter(api, contract, parts):'); L.push(' path = parts.get("path", {})'); - L.push(` res = api.${op.method}(${pathFromParts(op)}, params=parts.get("params"), headers=parts.get("headers"))`, ` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, '', ''); + L.push( + ` res = api.${op.method}(${pathFromParts(op)}, params=parts.get("params"), headers=parts.get("headers"))`, + ' # The request carried the value under test (a local schema violation proves nothing about the API).', + ' if parts.get("sent"):', + ' expect_sent_query(res, parts["sent"]["name"], parts["sent"]["value"])', + ` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, + '', + '', + ); + } + if (s.probes?.length) { + // Exploratory: what the API must answer is not specified, so these never fail on its behavior; they record it. + const fx = 'api'; + L.push('PROBES = ['); + s.probes.forEach((p, n) => { + const id = s.ids?.contract.probes?.[n]; + L.push(` pytest.param(${pyLit({ param: p.param, kind: p.kind, params: p.params, value: p.value }, 4)}, id=${str(p.title)}${id ? `, marks=pytest.mark.api_case_id(${str(id)})` : ''}),`); + }); + L.push( + ']', + '', + '', + 'from contract import expect_sent_query # noqa: E402,F811', + '', + '', + NEG, + '@pytest.mark.exploratory', + '@pytest.mark.parametrize("probe", PROBES)', + `def test_exploratory_probe_records_never_fails(${fx}, contract, probe):`, + ` res = ${fx}.${op.method}(${pathExpr(op)}, params=probe["params"])`, + ' expect_sent_query(res, probe["param"], probe["value"])', + ` contract.record_probe(res, {"operation": ${str(op.key)}, "parameter": probe["param"], "probe": probe["kind"], "value": probe["value"]}, ${str(op.method)}, ${str(op.path)})`, + '', + '', + ); } if (s.errors?.unsupportedMediaType && chain) { // 415: the documented body, but declared as text/plain. Anything the API wrongly creates is removed. diff --git a/src/generate/templates.ts b/src/generate/templates.ts index c2347b6..46e8eb0 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -10,6 +10,7 @@ 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'; import type { BodyVariant } from './variants.js'; +import type { Probe } from './probes.js'; import { tsVariantImports, tsVariantTests } from './variant-render.js'; /** Payloads and assumptions for one confirmed resource chain. */ @@ -81,8 +82,17 @@ export function optionsWith(op: Operation, inner?: string): string | undefined { /** Safe query variations: only values explicitly allowed by the schema (enum values, else the valid limits). */ export function queryVariants(op: Operation): Array<{ name: string; value: string | number | boolean }> { - if (op.method !== 'get') return []; - return op.params.filter((p) => p.in === 'query' && !p.required).flatMap((p) => { + return queryVariantsDetailed(op).kept; +} + +export const MAX_VALUES_PER_PARAM = 5; +export const MAX_VALUES_PER_OPERATION = 15; + +/** Accepted values and those left out by the limits (reported as CASE_LIMIT_REACHED, never dropped silently). */ +export function queryVariantsDetailed(op: Operation): { kept: Array<{ name: string; value: string | number | boolean }>; dropped: Array<{ name: string; value: string | number | boolean }> } { + if (op.method !== 'get') return { kept: [], dropped: [] }; + const dropped: Array<{ name: string; value: string | number | boolean }> = []; + const all = op.params.filter((p) => p.in === 'query' && !p.required).flatMap((p) => { const schema: any = p.schema ?? {}; const values: unknown[] = Array.isArray(schema.enum) ? [...schema.enum] : []; // Boundary-valid values: the documented limits themselves must be accepted. @@ -90,8 +100,11 @@ export function queryVariants(op: Operation): Array<{ name: string; value: strin const kept = values.filter((v): v is string | number | boolean => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'); // One physical test per value, each with its own case ID: values equal as strings would share an ID. const unique = kept.filter((v, i) => kept.findIndex((x) => String(x) === String(v)) === i); - return unique.slice(0, 5).map((value) => ({ name: p.name, value })); - }).slice(0, 15); + dropped.push(...unique.slice(MAX_VALUES_PER_PARAM).map((value) => ({ name: p.name, value }))); + return unique.slice(0, MAX_VALUES_PER_PARAM).map((value) => ({ name: p.name, value })); + }); + dropped.push(...all.slice(MAX_VALUES_PER_OPERATION)); + return { kept: all.slice(0, MAX_VALUES_PER_OPERATION), dropped }; } function header(kind: string, op: Operation, meta: Meta, extra: string[]): string[] { @@ -238,6 +251,8 @@ export interface SuiteInput { fixture?: LoadedFixture; /** Positive request-body variants of a create / update (only required fields, other oneOf / anyOf branches). */ bodyVariants?: BodyVariant[]; + /** Exploratory query probes (record the API's answer, never fail on it). */ + probes?: Probe[]; } export type Role = 'create' | 'read' | 'update' | 'delete'; @@ -268,7 +283,7 @@ export function suiteCounts(s: SuiteInput): Record { const e = s.errors; const base = { functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0) + (e?.invalidCredentials ? 1 : 0) + (e?.envCredentials?.length ?? 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), + contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length + (e?.unsupportedMediaType && s.plan ? 1 : 0) + (s.probes?.length ?? 0), }; return { contract: base.contract, @@ -373,7 +388,7 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan) || !!s.collection?.plan.tests.length || !!s.bodyVariants?.length; const errorStatus = !!(s.errors?.invalidCredentials || s.errors?.envCredentials?.length || s.errors?.methodNotAllowed || s.errors?.preconditionFailed); 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'] : []), ...tsVariantImports(s)])]; + 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'] : []), ...tsVariantImports(s), ...(s.positive && !plan && op.method === 'get' && queryVariants(op).length ? ['expectContract'] : [])])]; 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' }, () => {`); @@ -408,6 +423,7 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { ` test(${q(`accepts documented ${variant.name}=${String(variant.value)}`)}, ${testOptions('positive', s.ids?.functional.variants[n])}, async ({ ${fx} }) => {`, ` const res = await ${apiCall(ref, fx, pathArgs(op, ref), optionsWith(op, `{ params: ${JSON.stringify(params)} }`))};`, ` ${expectSuccess(op)}`, + ` await expectContract(res, '${op.method}', ${q(op.path)}); // an accepted value must still give a documented response`, ` });`, '', ); @@ -564,7 +580,7 @@ export function renderContract(s: SuiteInput, meta: Meta): string { const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || (s.bodyCases.length > 0 && !!chain && (isCreate || needsExisting)) || wrongMedia; // Validation cases go through the same fixture as the positive test (anonymous for public operations). const fx = chain ? 'api' : apiFixture(op); - const names = [...(s.positive || s.notFound || s.unauthorized ? ['expectContract'] : []), ...(invalid ? ['expectRejected'] : [])]; + const names = [...(s.positive || s.notFound || s.unauthorized ? ['expectContract'] : []), ...(invalid ? ['expectRejected'] : []), ...(s.paramCases.some((c) => c.sent) || s.probes?.length ? ['expectSentQuery'] : []), ...(s.probes?.length ? ['recordProbe'] : [])]; const L = suiteHeader('contract', s, meta, ['Checks conformance to the OpenAPI document: the status actually returned is documented and the body matches its schema.', 'Invalid requests break one documented constraint each and must get a documented rejection.']); L.push(...imports(s, names, usesHelpers)); if (s.bodyCases.length + s.paramCases.length > 0) L.push('', `const rejection = ${JSON.stringify(s.validation)}; // documented in the spec`); @@ -592,10 +608,10 @@ export function renderContract(s: SuiteInput, meta: Meta): string { } if (s.paramCases.length) { // Each row is a whole request: the valid required parameters plus the one parameter under test. - L.push(` const invalidParameters: { title: string; source: string; caseId?: string; params?: Record | string; headers?: Record; path?: Record }[] = [`); + L.push(` const invalidParameters: { title: string; source: string; caseId?: string; params?: Record | string; headers?: Record; path?: Record; sent?: { name: string; value: string | null } }[] = [`); s.paramCases.forEach((c, n) => { const r: ParamRequest = c.request ?? (c.query ? { params: c.query as ParamRequest['params'] } : {}); - const fields = [r.params !== undefined ? `params: ${JSON.stringify(r.params)}` : '', r.headers ? `headers: ${JSON.stringify(r.headers)}` : '', r.path ? `path: ${JSON.stringify(r.path)}` : ''].filter(Boolean).join(', '); + const fields = [r.params !== undefined ? `params: ${JSON.stringify(r.params)}` : '', r.headers ? `headers: ${JSON.stringify(r.headers)}` : '', r.path ? `path: ${JSON.stringify(r.path)}` : '', c.sent ? `sent: ${JSON.stringify(c.sent)}` : ''].filter(Boolean).join(', '); L.push(` { title: ${q(c.title)}, source: ${q(c.source)}, ${caseField(s.ids?.contract.params[n])}${fields} },`); }); const args = ref.pathParams.map((name) => { @@ -603,7 +619,34 @@ export function renderContract(s: SuiteInput, meta: Meta): string { return `c.path?.[${q(name)}] ?? ${known === undefined ? "'unused'" : q(String(known))}`; }); L.push(` ];`, '', ` for (const c of invalidParameters) {`, ` test(\`rejects invalid parameter: \${c.title}\`, ${loopOptions(s.ids?.contract.params)}, async ({ ${fx} }) => {`); - L.push(` const res = await ${apiCall(ref, fx, args, '{ params: c.params, headers: c.headers }')};`, ` await expectRejected(res, rejection, '${op.method}', ${q(op.path)});`, ` });`, ` }`, ''); + L.push( + ` const res = await ${apiCall(ref, fx, args, '{ params: c.params, headers: c.headers }')};`, + ...(s.paramCases.some((c) => c.sent) + ? [` // The request carried the value under test (a local schema violation proves nothing about the API).`, ` if (c.sent) expectSentQuery(res, c.sent.name, c.sent.value);`] + : []), + ` await expectRejected(res, rejection, '${op.method}', ${q(op.path)});`, + ` });`, + ` }`, + '', + ); + } + if (s.probes?.length) { + // Exploratory: what the API must answer is not specified, so these never fail on its behavior; they record it. + const pfx = isPublic(op) && !chain ? 'publicApi' : 'api'; + L.push(` const probes: { title: string; caseId: string; param: string; kind: string; params: Record; value: string | null }[] = [`); + s.probes.forEach((p, n) => L.push(` { title: ${q(p.title)}, caseId: ${q(s.ids?.contract.probes?.[n] ?? '')}, param: ${q(p.param)}, kind: ${q(p.kind)}, params: ${JSON.stringify(p.params)}, value: ${JSON.stringify(p.value)} },`)); + L.push( + ` ];`, + '', + ` for (const p of probes) {`, + ` test(\`exploratory probe (records, never fails): \${p.title}\`, { tag: ['@negative', '@exploratory'], annotation: { type: 'caseId', description: p.caseId } }, async ({ ${pfx} }) => {`, + ` const res = await ${apiCall(ref, pfx, pathArgs(op, ref), '{ params: p.params }')};`, + ` expectSentQuery(res, p.param, p.value);`, + ` await recordProbe(res, { caseId: p.caseId, operation: ${q(op.key)}, parameter: p.param, probe: p.kind, value: p.value }, '${op.method}', ${q(op.path)});`, + ` });`, + ` }`, + '', + ); } if (wrongMedia) { // 415: the documented body, but declared as text/plain. Anything the API wrongly creates is removed. @@ -835,9 +878,10 @@ export function expectFields(item: unknown, expected: unknown, policies: Record< } /** 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 { +export function expectAllMatch(items: unknown[], ptr: string, match: 'equals' | 'contains' | 'search', value: unknown): void { const bad = items.filter((i) => { const v = readPointer(i, ptr); + if (match === 'search') return !String(v ?? '').toLowerCase().includes(String(value).toLowerCase()); 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); @@ -918,6 +962,27 @@ export async function poll(fn: () => Promise, done: (v: T) => boolean, tim return v; } +/** + * Exploratory probe (never fails on the API's behavior): records what came back, as a test annotation and, when the + * agent runs the suite, a line in API_AGENT_EXPLORATORY_LOG. A 5xx is flagged for a human, not reported as a defect. + */ +export async function recordProbe(res: APIResponse, info: Record, method: string, path: string): Promise { + const { contentType, body, rawText } = await readBody(res); + const r = validator.validateResponse({ method, path, status: res.status(), contentType, body, rawText, headers: res.headers() }); + const observation = { ...info, status: res.status(), documented: r.kind !== 'undocumented-status', contract: r.ok ? 'matches' : r.errors.join('; '), serverError: res.status() >= 500 }; + test.info().annotations.push({ type: 'exploratory', description: JSON.stringify(observation) }); + const file = process.env.API_AGENT_EXPLORATORY_LOG; + if (file) appendFileSync(file, JSON.stringify(observation) + '\\n'); + else if (observation.serverError) console.warn('exploratory probe ' + JSON.stringify(info) + ' answered ' + res.status() + ' (an observation, not a confirmed defect)'); +} + +/** The query parameter went over HTTP as intended: its text, or absent (value null). */ +export function expectSentQuery(res: APIResponse, name: string, value: string | null): void { + const sent = new URL(res.url()).searchParams.getAll(name); + if (value === null) expect(sent, name + ' is not sent').toEqual([]); + else expect(sent, name + ' is sent as ' + JSON.stringify(value)).toEqual([value]); +} + /** A copy of a payload without the fields at these JSON pointers (array elements by index). */ export function withoutFields(payload: T, ptrs: string[]): T { const out = structuredClone(payload) as any; diff --git a/src/report/quality-gates.ts b/src/report/quality-gates.ts index cf3a788..0f2dd32 100644 --- a/src/report/quality-gates.ts +++ b/src/report/quality-gates.ts @@ -15,7 +15,8 @@ export interface CleanupProblem { */ export function cleanupProblems(text: string, lang: 'typescript' | 'python'): CleanupProblem[] { const out: CleanupProblem[] = []; - const blocks = lang === 'typescript' ? text.split(/\n test\(/).slice(1) : text.split(/\n(?=@pytest\.mark\.(?:positive|negative))/).slice(1); + // The leading newline keeps a test at the very start of the text (the first part is the file header). + const blocks = lang === 'typescript' ? ('\n' + text).split(/\n test\(/).slice(1) : ('\n' + text).split(/\n(?=@pytest\.mark\.(?:positive|negative))/).slice(1); for (const b of blocks) { const title = b.split('\n')[lang === 'typescript' ? 0 : 1 + (b.includes('api_case_id') ? 1 : 0)]?.slice(0, 100) ?? ''; const creates = lang === 'typescript' ? /resource\.create\(|\.create\(api, |removeIfCreated/.test(b) : /\w+\.create\(|remove_if_created|\.new_create_payload\(\)/.test(b); @@ -25,6 +26,14 @@ export function cleanupProblems(text: string, lang: 'typescript' | 'python'): Cl ? /finally\s*\{[\s\S]*(resource\.remove|removeIfCreated|reportCleanupFailure)/.test(b) || /=\s*await [^\n]+;\n\s*await resource\.removeIfCreated\(api, res\);/.test(b) : /finally:[\s\S]*(\.remove\(|report_cleanup_failure|remove_if_created)/.test(b) || /def \w+\([^)]*created_\w+[^)]*\)/.test(b) || /res = api\.\w+\((?:(?!assert|contract\.)[\s\S])*?\)\n\s+\w+\.remove_if_created\(res\)/.test(b); if (!cleaned) out.push({ test: title.trim(), problem: 'creates data without guaranteed cleanup' }); + if (lang === 'python') { + // A fixture the test assigns to is no longer the fixture: its cleanup (e.g. items.remove) hits the wrong object. + const sig = /def \w+\(([^)]*)\)/.exec(b)?.[1] ?? ''; + const fixtures = sig.split(',').map((x) => x.trim()).filter(Boolean); + for (const f of fixtures) { + if (new RegExp(`^\\s+(?:[\\w\\s,]*,\\s*)?${f}\\s*(?:,[\\w\\s,]*)?=(?!=)`, 'm').test(b)) out.push({ test: title.trim(), problem: `the fixture "${f}" is reassigned in the test, so its cleanup no longer applies` }); + } + } } return out; } diff --git a/src/report/report.ts b/src/report/report.ts index c0a1a96..7d1583e 100644 --- a/src/report/report.ts +++ b/src/report/report.ts @@ -34,6 +34,8 @@ export interface AuditReport { scenarios: { name: string; status: Status; reason: string; operations: string[] }[]; /** Test data cleanup could not remove during the run: it stays on the target. */ cleanupFailures?: { operation: string; id: string; status: number | string }[]; + /** Exploratory probe outcomes: observations for a human, never confirmed defects. */ + exploratory?: { operation: string; parameter: string; probe: string; value: string | null; status: number; documented: boolean; contract: string; serverError: boolean }[]; /** After a run: every physical test has its own case ID registered in cases.json. */ caseIdCheck?: { tests: number; missing: string[]; duplicates: string[]; unregistered: string[] }; }; @@ -130,6 +132,17 @@ export function toMarkdown(r: AuditReport): string { L.push('## ⚠️ Test data left on the target', '', `Cleanup could not remove ${left.length} record(s) created by the run. Remove them by hand, or fix the cleanup (e.g. an account allowed to delete) before running again.`, ''); L.push('| Cleanup operation | Status | Id |', '|---|---|---|', ...left.map((f) => `| \`${f.operation}\` | ${f.status} | \`${f.id}\` |`), ''); } + const probes = r.generated?.exploratory ?? []; + if (probes.length) { + const notable = probes.filter((p) => p.serverError || !p.documented || p.contract !== 'matches'); + L.push( + '## Exploratory query probes (observations, not confirmed defects)', + '', + `${probes.length} probe(s) sent inputs the spec does not specify an answer for; ${notable.length} answered with a server error, an undocumented status or a response that does not match the contract. Review them: a 5xx on malformed input usually deserves a bug report, but the spec does not make it one.`, + '', + ); + if (notable.length) L.push('| Operation | Parameter | Probe | Value | Status | Note |', '|---|---|---|---|---|---|', ...notable.map((p) => `| \`${p.operation}\` | \`${p.parameter}\` | ${p.probe} | ${p.value === null ? '(not sent)' : `\`${String(p.value).slice(0, 24)}\``} | ${p.status} | ${p.serverError ? 'server error' : !p.documented ? 'undocumented status' : p.contract.slice(0, 80)} |`), ''); + } if (r.generated) { L.push('## Generated functional scenarios', ''); for (const s of r.generated.scenarios) L.push(`- **${s.name}** · ${ICON[s.status]}: ${s.reason}`); diff --git a/tests/unit/collection.test.ts b/tests/unit/collection.test.ts index def488e..fb960cc 100644 --- a/tests/unit/collection.test.ts +++ b/tests/unit/collection.test.ts @@ -17,7 +17,7 @@ import { normalizeSpec } from '../../src/change/normalize.js'; 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 cfg: CollectionConfig = deps.scenarios[0].collections[0]; const approved: Fixture = JSON.parse(await readFile('demo-api/fixtures/approved/listItems.json', 'utf8')); const createSchema = { $ref: '#/components/schemas/ItemInput' }; @@ -67,7 +67,7 @@ describe('strategy selection', () => { 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.map((t) => `${t.kind}:${t.mode}`)).toEqual(['listed:controlled', 'filter:controlled', 'sort:controlled', 'sort:controlled', 'sort:controlled', 'sort:controlled', 'sort-reverse:controlled', 'sort-reverse:controlled', 'pagination:controlled', 'unique:controlled', 'total: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); @@ -165,7 +165,7 @@ describe('shared environments (found on Toolshop)', () => { }); 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 ro = { scenarios: [{ ...deps.scenarios[0], collections: [{ ...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'); diff --git a/tests/unit/core.test.ts b/tests/unit/core.test.ts index 4d2cc02..228f964 100644 --- a/tests/unit/core.test.ts +++ b/tests/unit/core.test.ts @@ -13,7 +13,7 @@ const op = (key: string) => ops.find((o) => o.key === key)!; describe('catalog', () => { it('lists every operation with path-level params merged in', () => { - expect(ops).toHaveLength(11); + expect(ops).toHaveLength(12); expect(op('GET /items/{itemId}').params.map((p) => p.name)).toEqual(['itemId']); }); @@ -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 }, { offset: 'not-a-number' }, { offset: -1 }, { tag: '' }, { tag: 'x'.repeat(31) }, { sort: '__not_in_enum__' }]); + expect(r.cases.map((c) => c.request?.params)).toEqual([{ limit: 'not-a-number' }, { limit: 0 }, { limit: 101 }, { limit: '20.5' }, { offset: 'not-a-number' }, { offset: -1 }, { offset: '0.5' }, { 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-depth.test.ts b/tests/unit/coverage-depth.test.ts index 6122495..edda911 100644 --- a/tests/unit/coverage-depth.test.ts +++ b/tests/unit/coverage-depth.test.ts @@ -173,3 +173,30 @@ describe('CI quality gates', () => { expect(d).toEqual({ lostCases: ['a'], newCases: ['c'], newGaps: ['G2'], closedGaps: ['G1'] }); }); }); + +describe('CI quality gates: Python fixtures', () => { + it('a test that reassigns its resource fixture fails the gate (its cleanup would hit the wrong object)', () => { + const py = [ + '@pytest.mark.positive', + 'def test_shadow(api, items):', + ' ids = []', + ' try:', + ' ids.append(items.create({})[0])', + ' items, totals, _ = (1, 2, 3)', + ' finally:', + ' for rid in ids:', + ' items.remove(rid)', + '@pytest.mark.positive', + 'def test_fine(api, items):', + ' ids = []', + ' try:', + ' ids.append(items.create({})[0])', + ' listed, totals, _ = (1, 2, 3)', + ' assert listed == 1', + ' finally:', + ' for rid in ids:', + ' items.remove(rid)', + ].join('\n'); + expect(cleanupProblems(py, 'python').map((p) => p.problem)).toEqual(['the fixture "items" is reassigned in the test, so its cleanup no longer applies']); + }); +}); diff --git a/tests/unit/coverage.test.ts b/tests/unit/coverage.test.ts index eae46ab..1e6c538 100644 --- a/tests/unit/coverage.test.ts +++ b/tests/unit/coverage.test.ts @@ -59,7 +59,7 @@ describe('stage 2: one case ID per physical test', () => { const tsIds = idsIn(await ts.read('items/get/functional.spec.ts')).sort(); const pyIds = idsIn(await py.read('items/get/test_functional.py')).sort(); expect(pyIds).toEqual(tsIds); - expect(await py.read('items/get/test_functional.py')).toContain('def test_accepts_documented_query_value(api, params):'); + expect(await py.read('items/get/test_functional.py')).toContain('def test_accepts_documented_query_value(api, contract, params):'); const compiled = spawnSync(findPython(), ['-m', 'py_compile', join(py.dir, 'items/get/test_functional.py')], { encoding: 'utf8' }); if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); }); diff --git a/tests/unit/query-collections.test.ts b/tests/unit/query-collections.test.ts new file mode 100644 index 0000000..0a8f1c2 --- /dev/null +++ b/tests/unit/query-collections.test.ts @@ -0,0 +1,141 @@ +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 { paramCasesDetailed } from '../../src/generate/param-cases.js'; +import { paramProbes } from '../../src/generate/probes.js'; +import { queryVariantsDetailed } from '../../src/generate/templates.js'; +import { resolveCollection } from '../../src/generate/collection.js'; +import { planCollectionTests } from '../../src/generate/collection-tests.js'; +import { parseCaseId } from '../../src/cases/ids.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { normalizeSpec } from '../../src/change/normalize.js'; +import { cleanupProblems } from '../../src/report/quality-gates.js'; + +/** Query parameters (confirmed cases and exploratory probes) and the GET collection additions (search, total, sort-reverse). */ + +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 op = (k: string) => ops.find((o) => o.key === k)!; +const kinds = (probes: { param: string; kind: string }[], param: string) => probes.filter((p) => p.param === param).map((p) => p.kind); + +async function gen(lang: 'typescript' | 'python') { + const dir = await mkdtemp(join(tmpdir(), 'ata-qc-')); + const r = await generate(demo, ops, { outDir: dir, version: 'test', lang, deps }); + return { dir, r, read: (f: string) => readFile(join(dir, f), 'utf8') }; +} + +describe('confirmed query-parameter cases', () => { + const list = paramCasesDetailed(demo.doc, op('GET /items'), { allowPath: true, allowOthers: true }); + + it('an integer parameter also gets a decimal inside its bounds (only the type is broken)', () => { + const d = list.cases.find((c) => c.source === 'query.limit.type.decimal')!; + expect(d.request?.params).toEqual({ limit: '20.5' }); + expect(d.target).toEqual({ in: 'query', field: 'limit', rule: 'type', variant: 'decimal' }); + expect(parseCaseId(`ata:op_AAAAAAAAAAAA:contract:negative:request.query#/limit/decimal:type`).ok).toBe(true); + }); + + it('every query case records the value that must go over HTTP (null: not sent)', () => { + const q = list.cases.filter((c) => c.target?.in === 'query'); + expect(q.every((c) => c.sent !== undefined)).toBe(true); + expect(list.cases.find((c) => c.source === 'query.limit.maximum')!.sent).toEqual({ name: 'limit', value: '101' }); + const missing = paramCasesDetailed(demo.doc, op('GET /items/search'), { allowPath: true, allowOthers: true }).cases.find((c) => c.source === 'query.q.required')!; + expect(missing.sent).toEqual({ name: 'q', value: null }); + }); + + it('a decimal that would also break multipleOf is a gap, not a case', () => { + const o = structuredClone(op('GET /items')); + (o.params.find((p) => p.name === 'limit')!.schema as any).multipleOf = 5; + const r = paramCasesDetailed(demo.doc, o, { allowPath: true, allowOthers: true }); + expect(r.cases.some((c) => c.source === 'query.limit.type.decimal')).toBe(false); + expect(r.gaps).toContainEqual(expect.objectContaining({ code: 'CANNOT_ISOLATE_RULE', rule: 'type', location: 'request.query#/limit' })); + }); + + it('accepted values over the limits are reported, never dropped silently', () => { + const o = structuredClone(op('GET /items')); + (o.params.find((p) => p.name === 'sort')!.schema as any).enum = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; + const v = queryVariantsDetailed(o); + expect(v.dropped.filter((x) => x.name === 'sort').map((x) => x.value)).toEqual(['f', 'g']); + }); +}); + +describe('exploratory probes (recorded, never asserted)', () => { + const confirmed = paramCasesDetailed(demo.doc, op('GET /items'), { allowPath: true, allowOthers: true }).cases; + const r = paramProbes(op('GET /items'), confirmed); + + it('no probe repeats a confirmed rule or a value the spec makes valid', () => { + expect(kinds(r.probes, 'limit')).toEqual(['empty']); // text / decimal / zero / negative / large: confirmed cases + expect(kinds(r.probes, 'offset')).toEqual(['empty', 'large']); // zero is valid (minimum 0), negative is the minimum case + expect(kinds(r.probes, 'tag')).toEqual(['special']); // empty: the minLength case; long: the maxLength case + expect(kinds(r.probes, 'sort')).toEqual(['empty', 'case']); + }); + + it('without documented rejections everything is a probe, never a confirmed failure', () => { + const p = paramProbes(op('GET /items'), []); + // zero and -1 break minimum 1, but no rejection is documented: the answer is unspecified, so they are probes. + expect(kinds(p.probes, 'limit')).toEqual(['empty', 'text', 'decimal', 'zero', 'negative', 'large']); + for (const x of p.probes) expect(parseCaseId(`ata:op_AAAAAAAAAAAA:contract:negative:${x.location}:probe`).ok, x.location).toBe(true); + }); + + it('a write operation is never probed: a gap says why', () => { + const o = structuredClone(op('GET /items')); + o.method = 'post'; + const p = paramProbes(o, []); + expect(p.probes).toEqual([]); + expect(p.gaps).toEqual([expect.objectContaining({ code: 'UNSAFE_LIVE_CHECK', rule: 'probe' })]); + }); + + it('generated probes never assert the API: they check what was sent and record the answer', async () => { + const ts = await (await gen('typescript')).read('items/get/contract.spec.ts'); + const block = ts.slice(ts.indexOf('for (const p of probes)')); + expect(block).toContain('expectSentQuery(res, p.param, p.value);'); + expect(block).toContain('await recordProbe(res,'); + expect(block.slice(0, block.indexOf(' }\n'))).not.toMatch(/expectRejected|expectStatus|expectContract/); + }); +}); + +describe('GET collections: search, total, sort-reverse, several mappings', () => { + const createSchema = { $ref: '#/components/schemas/ItemInput' }; + const [items, search] = deps.scenarios[0].collections; + + it('validates the new mapping parts against the spec', () => { + expect(resolveCollection(demo.doc, ops, search).errors).toEqual([]); + const bad = { ...search, total: '/items', filters: [{ param: 'q', field: '/price', match: 'search' }] }; + const errors = resolveCollection(demo.doc, ops, bad).errors.join('\n'); + expect(errors).toContain('"total" /items is not an integer field'); + expect(errors).toContain('search filter field "/price" is not a string'); + }); + + it('plans the total and the reverse-order checks on controlled data', () => { + const c = resolveCollection(demo.doc, ops, items).collection!; + const p = planCollectionTests(demo.doc, c, { canCreate: true, createSchema, canUpdate: true, updatePayload: { name: 'x' }, canDelete: true }); + expect(p.tests.filter((t) => t.kind === 'sort-reverse').map((t) => `${t.sort!.value}/${t.sortDesc!.value}:${t.mode}`)).toEqual(['name/-name:controlled', 'price/-price:controlled']); + expect(p.tests.find((t) => t.kind === 'total')?.mode).toBe('controlled'); + }); + + it('a search list with a required parameter: isolated by the search itself; no lifecycle once the update changes the name', () => { + const c = resolveCollection(demo.doc, ops, search).collection!; + const p = planCollectionTests(demo.doc, c, { canCreate: true, createSchema, canUpdate: true, updatePayload: { name: 'renamed' }, canDelete: true }); + expect(p.iso).toEqual({ param: 'q', field: '/name', match: 'search' }); + expect(p.lifecycle).toBe(false); + expect(p.gaps).toContainEqual(expect.objectContaining({ code: 'CANNOT_ISOLATE_RULE', location: 'lifecycle' })); + }); + + it('TypeScript and Python generate the same cases; the registry is valid; no Python test shadows its fixture', async () => { + const ts = await gen('typescript'); + const py = await gen('python'); + const active = async (g: typeof ts) => Object.entries(JSON.parse(await g.read('_support/cases.json')).cases).filter(([, c]) => c.status !== 'retired').map(([id]) => id).sort(); + const [a, b] = [await active(ts), await active(py)]; + expect(b).toEqual(a); + for (const rule of [':probe', '/decimal:type', ':sort-reverse', ':total', 'request.query#/q:filter']) expect(a.some((id) => id.includes(rule)), rule).toBe(true); + const reg = validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('demo-api/openapi.yaml', 'utf8'), 'demo')); + expect(reg.errors).toEqual([]); + const search = await ts.read('items-search/get/functional.spec.ts'); + expect(search).toContain('.toUpperCase()'); // the query in upper case, the data in lower case + for (const f of ['items/get/test_functional.py', 'items_search/get/test_functional.py']) expect(cleanupProblems((await py.read(f)).replace(/\r\n/g, '\n'), 'python'), f).toEqual([]); + }); +});