diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 697d5d0..d68133a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,24 @@ jobs: - run: npm run build - run: npm test + - name: Generated code for the synthetic fixture compiles (TypeScript and Python) + # tests/fixtures/coverage/kitchen-sink.yaml exercises every template: nested bodies, all parameter + # kinds, error responses, scenarios. Generated, never run (no server), but it must compile. + run: | + npx tsx src/cli.ts generate tests/fixtures/coverage/kitchen-sink.yaml --deps tests/fixtures/coverage/kitchen-sink.deps.json --tests-dir tests/api-ks --max-cases 500 -o reports/ks --fail-on never + npx tsc --noEmit + npx tsx src/cli.ts generate tests/fixtures/coverage/kitchen-sink.yaml --deps tests/fixtures/coverage/kitchen-sink.deps.json --tests-dir tests/api-ks-python --lang python --max-cases 500 -o reports/ks-python --fail-on never + python -m py_compile $(find tests/api-ks-python -name '*.py') + npx tsx src/cli.ts registry validate tests/api-ks/_support/cases.json --spec tests/fixtures/coverage/kitchen-sink.yaml --require-spec > /dev/null + # TypeScript / Python parity on every template: the same active cases. + node -e ' + const active = (f) => Object.entries(require(f).cases).filter(([, c]) => c.status !== "retired").map(([id]) => id).sort(); + const ts = active("./tests/api-ks/_support/cases.json"), py = active("./tests/api-ks-python/_support/cases.json"); + console.log("kitchen sink cases:", ts.length, "TypeScript /", py.length, "Python"); + if (JSON.stringify(ts) !== JSON.stringify(py)) process.exit(1); + ' + rm -rf tests/api-ks tests/api-ks-python + - name: Start demo API run: | nohup npm run demo > demo-api.log 2>&1 & @@ -53,7 +71,7 @@ jobs: ' - name: Generate tests (resource/method/functional|contract|scenarios) and run them once - run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --allow-write --run -o reports/generate --fail-on never + run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run -o reports/generate --fail-on never - name: Self-check - generated suite fails only on the known defect run: | @@ -65,17 +83,44 @@ jobs: if (JSON.stringify(bad) !== JSON.stringify(["stats/get/contract"]) || passed < 10) process.exit(1); ' + - name: Self-check - every physical test has its own registered case ID; registry and manifest are valid + run: | + node -e ' + const c = require("./reports/generate/report.json").generated.caseIdCheck; + console.log(JSON.stringify(c)); + if (!c || c.tests < 10 || c.missing.length || c.duplicates.length || c.unregistered.length) process.exit(1); + ' + npx tsx src/cli.ts registry validate tests/api/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null + npx tsx src/cli.ts manifest validate --tests-dir tests/api + # Coverage gaps are exactly the expected ones: a new gap or a silently vanished one fails. + node -e ' + const got = require("./reports/generate/coverage-gaps.json").summary.gapsByCode; + const want = require("./demo-api/expected-gaps.json"); + console.log("coverage gaps:", JSON.stringify(got)); + if (JSON.stringify(got) !== JSON.stringify(want)) { console.log("expected:", JSON.stringify(want)); process.exit(1); } + ' + - name: Generate Python tests (pytest + requests) and run them once run: | pip install pytest requests jsonschema - npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never + npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never node -e ' const r = require("./reports/generate-python/report.json"); const bad = r.generated.scenarios.filter(s => s.status === "CONTRACT_MISMATCH" || s.status === "TEST_FAILURE").map(s => s.name); const passed = r.generated.scenarios.filter(s => s.status === "PASS").length; console.log("failing:", bad, "passed:", passed); if (JSON.stringify(bad) !== JSON.stringify(["stats/get/contract"]) || passed < 10) process.exit(1); + const c = r.generated.caseIdCheck; + console.log(JSON.stringify(c)); + if (!c || c.tests < 10 || c.missing.length || c.duplicates.length || c.unregistered.length) process.exit(1); + // TypeScript and Python generate the same active cases (retired ones are history). + const active = (f) => Object.entries(require(f).cases).filter(([, c]) => c.status !== "retired").map(([id]) => id).sort(); + const ts = active("./tests/api/_support/cases.json"); + const py = active("./tests/api-python/_support/cases.json"); + if (JSON.stringify(ts) !== JSON.stringify(py)) { console.log("TS/Python case sets differ"); process.exit(1); } ' + npx tsx src/cli.ts registry validate tests/api-python/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null + npx tsx src/cli.ts manifest validate --tests-dir tests/api-python - name: Analyse the legacy example project (init + run) working-directory: examples/legacy-project diff --git a/CHANGELOG.md b/CHANGELOG.md index 657bc4c..eff1d90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- **Coverage completeness** (see docs/SUPPORT_MATRIX.md): + - one physical test → one stable case ID (vocabulary v2: `accepted-value`, `invalid-credentials`, `method-not-allowed`, `precondition-failed`), checked on the real run (Playwright report, pytest collection); cases no longer generated become tombstones; + - recursive request-body negative cases at any depth, exactly one broken rule each (verified with ajv), configurable limit `--max-cases` with dropped cases reported; + - query / header / cookie / path parameter cases, array serialization by style / explode, required header / cookie parameters sent in every call; + - stricter response contract in TypeScript and Python alike: headers, no body for 204 / 205 / 304 / HEAD / no content, empty body, text schemas, writeOnly; what is not checked is said; + - documented errors with safe triggers: 401 invalid credentials, 405, 409 (deps `conflictOn`), 412, 415; 403 / 429 / others as gaps; + - boundary-valid query values, deps `echoes`, sampler fixes (multipleOf, exclusive bounds, uniqueItems), uncovered oneOf / anyOf branches reported; + - reviewed business scenarios (`--scenarios`, `scenarios validate`, schemas/scenarios.schema.json) and repeated delete; + - `coverage-gaps.json`: summary by machine code, per-suite status, unchecked statuses / request media types / security alternatives; + - CI: case-ID checks, registry and manifest validation, TypeScript / Python parity, the synthetic fixture must compile, expected coverage gaps. - **Stable case IDs** (step 3 of docs/OPENAPI_CHANGE_TRIGGER.md, core): every generated test carries `ata:::::` (Playwright annotation `caseId`, pytest marker `api_case_id`). `generate` writes `_support/cases.json` (operations, cases, CRUD scenario definitions; existing UIDs kept, removed operations retired, never rebuilt), `_support/generation-manifest.json` (file ownership and canonical hashes, written last) and `_support/openapi.snapshot.meta.json`, which makes the snapshot a `diff` baseline. New `registry validate [path] [--spec] [--require-spec]` and `manifest validate`. Case ID encoding / parsing and the rule vocabulary v1 with its allowed combinations follow the design. - **`diff`: semantic diff of two OpenAPI specs** (step 1 of docs/OPENAPI_CHANGE_TRIGGER.md). Writes `changes.json` (schema in `schemas/changes.schema.json`) and, with `--format markdown`, `changes.md`: operations added / removed / moved (rename detection with the documented thresholds; uncertain links marked `review`), `operationId` and path parameter renames, parameter, request and response changes, schema constraint changes per facet and direction, example / default changes, servers. Deterministic `operationUid` per operation. Formatting, descriptions, `$ref` layout, equivalent `allOf` and 3.0 ↔ 3.1 nullable give no changes. Compatibility verdicts come from oasdiff `1.34.1` (`OASDIFF_BIN` or `PATH`, not bundled; version pinned). Baseline: `--base`, else the Git merge base; otherwise `BLOCKED: BASE_SPEC_MISSING`. URLs need `--allow-network`; private and metadata hosts are denied unless allowed. Exit codes 0 / 1 (`--fail-on breaking | blocked | unknown`, repeatable, default `blocked`) / 2 (configuration). - **A failed create check no longer leaves data:** the resource helper's `create()` removes the record before failing when a check after the request fails (e.g. the API answers an undocumented `201` where the spec says `200`). Before, the test failed before cleanup was registered, and the record stayed (found on Toolshop favorites). diff --git a/README.md b/README.md index 09ff602..0e24812 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,21 @@ Generated files are overwritten when the spec changes; put hand-written cases in `generate --draft-pr` commits the tests and the report on a new branch and opens a GitHub Draft PR. It never pushes to the default branch or merges. +## What is covered, and what is not + +Coverage is reported, never implied. The full keyword-by-keyword table is in [docs/SUPPORT_MATRIX.md](docs/SUPPORT_MATRIX.md); every check that could not be generated is in `coverage-gaps.json` with a machine code and its exact location. + +**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; +- 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. + +**Needs your confirmation (deps or scenarios file):** CRUD chains and cleanup, 409 conflicts (`conflictOn`), fields a create returns as sent (`echoes`), values taken from existing data (`fill`), and every business flow (`--scenarios`): state transitions, parent → child, login / refresh, list / search / pagination. + +**Never generated (reported as gaps):** 403 without a reviewed role setup, 429, a 405 that would need an unsafe method, oneOf / anyOf branches other than the one sent, rules that cannot be broken without breaking another, media types other than JSON / text, and anything the spec does not state. + ## Options | Option | Default | | diff --git a/demo-api/expected-gaps.json b/demo-api/expected-gaps.json new file mode 100644 index 0000000..84bbd0d --- /dev/null +++ b/demo-api/expected-gaps.json @@ -0,0 +1,5 @@ +{ + "MISSING_CLEANUP": 2, + "MISSING_RESOURCE_SOURCE": 1, + "MISSING_RESPONSE_SCHEMA": 1 +} diff --git a/demo-api/scenarios.json b/demo-api/scenarios.json new file mode 100644 index 0000000..e5c1af5 --- /dev/null +++ b/demo-api/scenarios.json @@ -0,0 +1,27 @@ +{ + "scenarios": [ + { + "id": "items.read-created", + "title": "an item that was just created can be read by its id", + "polarity": "positive", + "primary": "read", + "steps": [ + { "name": "create", "operationId": "createItem", "phase": "setup", "body": { "name": "Scenario item", "price": 5, "tags": ["scenario"] }, "expect": "201", "save": { "itemId": "/id" } }, + { "name": "read", "operationId": "getItem", "phase": "action", "params": { "itemId": "{itemId}" }, "expect": "200" }, + { "operationId": "deleteItem", "phase": "cleanup", "params": { "itemId": "{itemId}" } } + ] + }, + { + "id": "items.gone-after-delete", + "title": "an item that was deleted cannot be read any more", + "polarity": "negative", + "primary": "read", + "steps": [ + { "name": "create", "operationId": "createItem", "phase": "setup", "body": { "name": "Scenario item", "price": 5 }, "expect": "201", "save": { "itemId": "/id" } }, + { "name": "delete", "operationId": "deleteItem", "phase": "setup", "params": { "itemId": "{itemId}" }, "expect": "204" }, + { "name": "read", "operationId": "getItem", "phase": "action", "params": { "itemId": "{itemId}" }, "expect": "404" }, + { "operationId": "deleteItem", "phase": "cleanup", "params": { "itemId": "{itemId}" } } + ] + } + ] +} diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md new file mode 100644 index 0000000..f6826d0 --- /dev/null +++ b/docs/SUPPORT_MATRIX.md @@ -0,0 +1,160 @@ +# OpenAPI support matrix + +What the generator derives from an OpenAPI document today, per keyword and per suite. Updated with every change that adds or closes a gap. + +Legend: ✅ supported · 🟡 partial (limits listed) · ❌ missing · ⛔ not generated on purpose (unsafe or needs a business requirement; reported as a gap) + +Baseline: `main` at 4c34a85 (audit of 2026-11-09). Each row names the stage of the coverage plan that changes it. + +## Request body: negative contract cases (`contract.spec.ts`, `src/generate/body-cases.ts`) + +Recursive from a valid payload; every case breaks exactly one rule (verified with ajv in `tests/unit/body-cases.test.ts`: one error, the expected keyword, the expected instance path). Locations are JSON pointers at any depth, `*` for array elements (the first element stands for all). A rule that cannot be broken alone is a gap with a code, never a guess. + +| Keyword | State | Limits / gap | Stage | +|---|---|---|---| +| `required` | ✅ | any depth; a required field without a valid sample → `MISSING_VALID_SAMPLE` | 3 ✔ | +| `type` | ✅ | any depth; skipped for `enum` / `const` fields (`CANNOT_ISOLATE_RULE`: the enum case covers it) | 3 ✔ | +| `nullable` / `type: [.., null]` | ✅ | `null` where null is not allowed (rule `nullable`) | 3 ✔ | +| `enum` | ✅ | string, number, integer, boolean; an enum covering all values → gap | 3 ✔ | +| `const` | ✅ | scalars | 3 ✔ | +| `minLength` / `maxLength` | ✅ | gap when `pattern` / `format` / `enum` / `const` would break too | 3 ✔ | +| `pattern` | ✅ | a simple non-matching string within the length limits; otherwise gap | 3 ✔ | +| `format` | ✅ | email, uuid, date-time, date, time, uri, url, hostname, ipv4, ipv6; others → `UNSUPPORTED_SCHEMA_KEYWORD` | 3 ✔ | +| `minimum` / `maximum` | ✅ | step = `multipleOf` when present; gap when the value would break another bound | 3 ✔ | +| `exclusiveMinimum` / `exclusiveMaximum` | ✅ | 3.1 numeric and 3.0 boolean form | 3 ✔ | +| `multipleOf` | ✅ | a neighbour of the sample value inside the bounds | 3 ✔ | +| `minItems` / `maxItems` | ✅ | `maxItems` with `uniqueItems` → gap (repeating breaks uniqueness) | 3 ✔ | +| `uniqueItems` | ✅ | duplicate first element; gap when it would exceed `maxItems` | 3 ✔ | +| `items` constraints | ✅ | recursive through the first element; an empty sample array → gap | 3 ✔ | +| `minProperties` / `maxProperties` | ✅ | drops optional properties only / adds extra ones; gap when required or `additionalProperties: false` would break | 3 ✔ | +| `additionalProperties: false` | ✅ | any depth | 3 ✔ | +| nested objects / arrays | ✅ | `request.body#/customer/address/city`, `request.body#/items/*/price`, depth ≤ 12 | 3 ✔ | +| `allOf` | ✅ | object parts merged | 3 ✔ | +| `oneOf` / `anyOf` / `not` / `discriminator` | ⛔ | `UNSUPPORTED_SCHEMA_KEYWORD` at that location: a broken value may still match another branch | 3 ✔ (gap) | +| `readOnly` | ✅ | not sent, no case | 3 ✔ | +| case limit | ✅ | `--max-cases` (default 60 per operation); potential / generated / dropped in `coverage-gaps.json`, each dropped case as `CASE_LIMIT_REACHED` | 3 ✔ | + +## Parameters (`src/generate/param-cases.ts`) + +Every case is a valid request (each required query / header / cookie parameter with its documented value) in which exactly one parameter breaks exactly one rule (verified in `tests/unit/param-cases.test.ts` against the parameter schemas). The rules come from the same engine as request bodies. Expected result: a documented 400 / 422 / 4XX. + +| 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 ✔ | +| `enum`, `const` | ✅ | | 4 ✔ | +| `pattern`, `format` | ✅ | as for bodies | 4 ✔ | +| `minimum` / `maximum` / exclusive / `multipleOf` | ✅ | | 4 ✔ | +| `minLength` / `maxLength` | ✅ | | 4 ✔ | +| arrays: `minItems` / `maxItems` / `uniqueItems` | ✅ | query `form` (explode true → repeated keys, false → comma), `spaceDelimited`, `pipeDelimited`; header `simple` | 4 ✔ | +| array item / object member constraints in parameters | ⛔ | `UNSUPPORTED_SCHEMA_KEYWORD` | 4 ✔ (gap) | +| `deepObject`, object parameters, array cookies | ⛔ | `UNSUPPORTED_SCHEMA_KEYWORD` | 4 ✔ (gap) | +| header parameters | ✅ | `Authorization`, `Content-Type`, `Accept` are not parameters (OpenAPI) | 4 ✔ | +| 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 | + +## Functional (`functional.spec.ts`) + +| Check | State | Limits | Stage | +|---|---|---|---| +| documented success status | ✅ | | | +| create returns an id | ✅ | confirmed chain | | +| read returns the created resource (same id) | ✅ | | | +| create response returns sent fields | ✅ | only the fields a reviewed deps file names (`echoes`): the spec does not state it | 7 ✔ | +| update → read returns the new values | ✅ | scenario, marked ASSUMPTION | | +| delete → read 404 | ✅ | scenario | | +| GET with each documented query `enum` value | ✅ | one test and one `accepted-value` case ID per value | 2 ✔ | +| boundary-valid query values accepted | ✅ | minimum / maximum (inside exclusive bounds, on `multipleOf`), shortest / longest string (no pattern / format, ≤ 64 chars); one test and case ID each | 7 ✔ | +| list contains the created resource, filter / search / pagination / sort | ⛔ | need a confirmed mapping of list fields and parameters (not in the spec) | 8 (gap) | +| optional-field variants of a create payload | ❌ | | | +| response examples as requirements | ⛔ | examples are illustrations, never asserted | | + +## Response contract (`src/contract/validator.ts`, `src/contract/contract.py`) + +The TypeScript and Python validators apply the same rules; `tests/unit/validator.test.ts` runs one table of cases through both and requires identical results. + +| Check | State | Limits | Stage | +|---|---|---|---| +| status, `NXX` ranges, `default` | ✅ | | | +| Content-Type of the matched response, media type parameters ignored, `type/*` and `*/*` | ✅ | an undocumented type is reported before an empty body | 5 ✔ | +| JSON schema (3.0 nullable, 3.1 / 3.2 JSON Schema 2020-12, formats) | ✅ | | | +| local / bundled `$ref` | ✅ | the snapshot is bundled | | +| response headers | ✅ | required ones present; documented ones match their schema (integer / number / boolean coerced, arrays comma-separated, style simple); `Content-Type` ignored as OpenAPI says | 5 ✔ | +| no body for `204` / `205` / `304`, `HEAD`, responses without `content` | ✅ | a body that arrives anyway is `unexpected-body` | 5 ✔ | +| empty body where a schema is documented | ✅ | `empty-body` (JSON `null` is a body) | 5 ✔ | +| text media types with a schema | ✅ | the text is validated as a string | 5 ✔ | +| other media types (XML, binary, …) | ⛔ | not checked: a note in the test report (Playwright annotation `contract-note`, pytest warning) and `UNSUPPORTED_MEDIA_TYPE` in `coverage-gaps.json` | 5 ✔ (gap) | +| a response without a schema | ⛔ | not checked: note + `MISSING_RESPONSE_SCHEMA` | 5 ✔ (gap) | +| `writeOnly` | ✅ | must not appear in a response; never required in a response | 5 ✔ | +| `readOnly` | ✅ | not sent in request cases (stage 3) | 3 ✔ | +| `discriminator` | 🟡 | `oneOf` validated; the mapping is not used | | +| contract tests exercise | 🟡 | success, 404 and 401 responses; more in stage 6 | 6 | + +## Documented error responses (`src/generate/error-cases.ts`) + +A case is generated only when the request that triggers the error is safe and the error is documented for the operation; everything else is a gap in `coverage-gaps.json` at `response.status#/`. + +| Status | State | How / gap | Stage | +|---|---|---|---| +| 400 / 422 (invalid input) | ✅ | body and parameter cases | 3–4 ✔ | +| 401 (no credentials) | ✅ | `publicApi` / `anonymous_api` | | +| 401 (invalid credentials) | ✅ | a certainly invalid credential of the operation's scheme: HTTP bearer / OAuth2 / OpenID Connect (`Bearer api-agent-invalid-token`), HTTP basic, API key in header / query / cookie; an unknown scheme → `UNSUPPORTED_SCHEMA_KEYWORD` | 6 ✔ | +| 401 (expired token) | ⛔ | needs a configured expired token | 6 (gap) | +| 403 (scope / role) | ⛔ | `UNCONFIRMED_BUSINESS_RULE`: needs a reviewed account that must be refused | 6 ✔ (gap) | +| 404 (unknown id) | ✅ | single trailing path parameter | | +| 405 | ✅ | a GET to a path that defines no GET (one case per path); a path with GET → `UNSAFE_LIVE_CHECK` (any other undocumented method could change data) | 6 ✔ | +| 409 (conflict) | ✅ | create twice with the same payload, only when the deps file names `conflictOn` fields (a reviewed business rule); both records removed in `finally`; otherwise `UNCONFIRMED_BUSINESS_RULE` | 6 ✔ | +| 412 (precondition) | ✅ | a non-matching `If-Match` / `If-Unmodified-Since` header (when documented) on a resource the test creates and removes; no such header → `UNCONFIRMED_BUSINESS_RULE` | 6 ✔ | +| 415 (wrong Content-Type) | ✅ | the documented body as `text/plain`, create / update with confirmed cleanup; otherwise `MISSING_CLEANUP` | 6 ✔ | +| 429 (rate limit) | ⛔ | `UNSAFE_LIVE_CHECK`: never exercised (opt-in with a request budget is not implemented) | 6 ✔ (gap) | +| other documented 4xx | ⛔ | `UNREACHABLE_RESPONSE_STATUS` | 6 ✔ (gap) | + +## Scenarios (`scenarios.spec.ts`, `src/scenarios/dsl.ts`) + +CRUD flows come from confirmed dependencies (OpenAPI links or the deps file). Business flows are never guessed from paths: they come from a reviewed scenarios file (`--scenarios`, JSON Schema `schemas/scenarios.schema.json`, `scenarios validate --spec`): steps in order with phases, parameters and bodies with `{var}` values saved by earlier steps, the documented status each step must get, and cleanup steps run in `finally` (failures reported). The case ID comes from the scenario's external `id`, never from the title. + +| Flow | State | Source / limits | Stage | +|---|---|---|---| +| create → read | ✅ | confirmed chain | | +| create → update → read | ✅ | confirmed chain; marked ASSUMPTION | | +| create → delete → read 404 | ✅ | confirmed chain | | +| delete → repeated delete → 404 | ✅ | confirmed chain, delete documents 404 | 8 ✔ | +| create → duplicate create → 409 | ✅ | deps `conflictOn` | 6 ✔ | +| update / delete unknown resource → 404 | ✅ | functional `not-found` cases | | +| business flows (login → request, parent → child, state transitions, negative transitions, idempotency key, …) | ✅ | reviewed scenarios file; strict validation: operations exist, parameters exist, every non-cleanup step names a documented status, every `{var}` is saved earlier, a writing scenario has cleanup, the primary is an action, IDs unique | 8 ✔ | +| create → list / search / filter, pagination, sort | 🟡 | as a reviewed business scenario; no automatic derivation (list fields and filters are not in the spec) | 8 ✔ | +| eventual consistency with bounded polling | ❌ | the scenario DSL has no retry / polling step yet | | +| refresh token → request | 🟡 | as a reviewed scenario with explicit steps | 8 ✔ | + +## Valid data (`src/generate/sample.ts`) + +| Keyword | State | Limits | Stage | +|---|---|---|---| +| `example`, `default`, `enum`, `const` | 🟡 | first value only | | +| `examples` | 🟡 | first only | | +| `oneOf` / `anyOf` | 🟡 | one branch is sent (the example's, else the first); the others are `UNCOVERED_VARIANT` gaps at their location | 7 ✔ (gap) | +| `discriminator` | 🟡 | blocked with an explicit reason | | +| `pattern` | 🟡 | blocked without an example (explicit reason) | | +| `multipleOf` | ✅ | the smallest multiple inside the bounds | 7 ✔ | +| exclusive bounds | ✅ | 3.1 numeric and 3.0 boolean form, combined with `minimum` | 7 ✔ | +| formats | 🟡 | uuid, email, date-time, date, uri, url, hostname, ipv4 | | +| `minItems`, nested objects / arrays | ✅ | | | +| `uniqueItems` | ✅ | distinct elements (enum values, suffixed strings, stepped numbers); otherwise blocked with the reason | 7 ✔ | +| unique values on a documented 409 | ✅ | suffix that respects enum / const / format / pattern / maxLength | | + +## Reporting and CI + +| Item | State | Notes | Stage | +|---|---|---|---| +| `coverage-gaps.json` | ✅ | summary (operations, generated tests per suite, gaps by code); per operation: gaps with code and location, per-suite generated count and missing code, positive-blocked code, body cases potential / generated / dropped, unchecked statuses (with the reason code), unchecked request media types, unchecked security alternatives | 10 ✔ | +| machine codes | ✅ | `MISSING_VALID_SAMPLE`, `MISSING_RESOURCE_SOURCE`, `MISSING_CLEANUP`, `MISSING_RESPONSE_SCHEMA`, `UNSUPPORTED_SCHEMA_KEYWORD`, `UNSUPPORTED_MEDIA_TYPE`, `UNCONFIRMED_BUSINESS_RULE`, `UNCOVERED_VARIANT`, `CANNOT_ISOLATE_RULE`, `CASE_LIMIT_REACHED`, `UNREACHABLE_RESPONSE_STATUS`, `UNSAFE_LIVE_CHECK`, `DEPRECATED_OPERATION`, `NO_DOCUMENTED_REJECTION` (`src/generate/coverage.ts`) | 10 ✔ | +| unique case ID per physical test | ✅ | checked on the real run: Playwright JSON report annotations, pytest collection (`API_AGENT_CASES_OUT`) | 2 ✔ | +| cases no longer generated | ✅ | tombstones (`status: retired`), reactivated when generated again | 2 ✔ | +| CI: registry and manifest validation | ✅ | `registry validate --spec --require-spec`, `manifest validate`, TypeScript and Python | 2 ✔ | +| CI: no duplicate case IDs, every test registered | ✅ | | 2 ✔ | +| CI: TypeScript / Python parity | ✅ | the same active cases for the demo API and for the synthetic fixture | 9 ✔ | +| CI: the synthetic fixture compiles | ✅ | `tests/fixtures/coverage/kitchen-sink.yaml` generated in both languages: `tsc`, `py_compile`, valid registry | 6 ✔ | +| CI: expected coverage gaps | ✅ | demo API (`demo-api/expected-gaps.json`) in CI; the synthetic fixture in unit tests | 10 ✔ | +| README | ✅ | "What is covered, and what is not": spec-derived vs needs confirmation vs never generated | 10 ✔ | diff --git a/schemas/scenarios.schema.json b/schemas/scenarios.schema.json new file mode 100644 index 0000000..15967fb --- /dev/null +++ b/schemas/scenarios.schema.json @@ -0,0 +1,40 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://github.com/testomut/api-test-agent/schemas/scenarios.schema.json", + "title": "Reviewed business scenarios", + "description": "Input of `generate --scenarios` and `scenarios validate`. Business flows are never guessed from paths; a human writes and reviews this file. `scenarios validate --spec` also checks it against the spec (operations, parameters, documented statuses, saved values, cleanup).", + "type": "object", + "additionalProperties": false, + "required": ["scenarios"], + "properties": { + "scenarios": { "type": "array", "items": { "$ref": "#/definitions/scenario" } } + }, + "definitions": { + "scenario": { + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "polarity", "primary", "steps"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$", "description": "Stable external ID: the scenarioUid is derived from it, never from the title or the steps." }, + "title": { "type": "string", "minLength": 1 }, + "polarity": { "enum": ["positive", "negative"] }, + "primary": { "type": "string", "description": "Name or operationId of the action step under test." }, + "steps": { "type": "array", "minItems": 2, "items": { "$ref": "#/definitions/step" } } + } + }, + "step": { + "type": "object", + "additionalProperties": false, + "required": ["operationId", "phase"], + "properties": { + "name": { "type": "string" }, + "operationId": { "type": "string" }, + "phase": { "enum": ["setup", "action", "assertion", "cleanup"] }, + "params": { "type": "object", "description": "Path and query parameters by name; \"{var}\" uses a value saved by an earlier step." }, + "body": { "description": "JSON request body; \"{var}\" strings are replaced by saved values." }, + "expect": { "type": "string", "pattern": "^([1-5][0-9][0-9]|[1-5]XX)$", "description": "Documented status the step must get. Required for every phase but cleanup." }, + "save": { "type": "object", "additionalProperties": { "type": "string", "pattern": "^(/.*)?$" }, "description": "Variable → JSON pointer into the response body." } + } + } + } +} diff --git a/src/cases/assign.ts b/src/cases/assign.ts index 1797569..f02ef0d 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -2,6 +2,8 @@ import type { Operation } from '../types.js'; import type { CrudChain } from '../generate/graph.js'; import type { NegCase } from '../generate/negative.js'; import { bodyPointer, caseId, location, scenarioUid, type CaseParts, type Phase, type ScenarioStep } from './ids.js'; +import type { ErrorPlan } from '../generate/error-cases.js'; +import type { ResolvedScenario } from '../scenarios/dsl.js'; /** * Case IDs of the tests the generator writes for one operation (docs/OPENAPI_CHANGE_TRIGGER.md, "Stable IDs"). @@ -23,9 +25,10 @@ export interface ScenarioDefinition { } export interface SuiteCaseIds { - functional: { success?: string; notFound?: string; unauthorized?: string }; - contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; query: string[] }; - scenario: { createRead?: string; updateRead?: string; deleteGone?: string }; + /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ + functional: { success?: string; notFound?: string; unauthorized?: string; variants: string[]; invalidCredentials?: string; methodNotAllowed?: string; preconditionFailed?: string }; + contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[]; unsupportedMediaType?: string }; + scenario: { createRead?: string; updateRead?: string; deleteGone?: string; conflict?: string; deleteTwice?: string; business: string[] }; /** Every case of this operation, by suite, with metadata for cases.json. */ records: Record<'functional' | 'contract' | 'scenario', CaseRecord[]>; scenarios: Record; @@ -38,10 +41,16 @@ export interface AssignInput { chain?: CrudChain; positive: boolean; bodyCases: NegCase[]; - queryCases: NegCase[]; + paramCases: NegCase[]; notFound?: { param: string }; unauthorized: boolean; - scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean }; + scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict?: boolean; deleteTwice?: boolean }; + /** Reviewed business scenarios whose primary step is this operation. */ + business?: ResolvedScenario[]; + /** Documented error responses with a safe trigger (stage 6). */ + errors?: ErrorPlan; + /** Documented query values the suite sends one by one (functional positive), each its own physical test. */ + queryVariants?: { name: string; value: string | number | boolean }[]; } export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): SuiteCaseIds { @@ -58,7 +67,7 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): return id; }; const ok = successStatus(s.op); - const ids: SuiteCaseIds = { functional: {}, contract: { body: [], query: [] }, scenario: {}, records, scenarios }; + const ids: SuiteCaseIds = { functional: { variants: [] }, contract: { body: [], params: [] }, scenario: { business: [] }, records, scenarios }; const rel = related.length ? { relatedOperationUids: related } : {}; if (s.positive) { @@ -72,6 +81,9 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): ids.contract.success = add('contract', { subjectUid: uid, polarity: 'positive', location: location.status(ok?.status ?? '200'), rule: 'documented' }, rel); } } + for (const v of s.queryVariants ?? []) { + ids.functional.variants.push(add('functional', { subjectUid: uid, polarity: 'positive', location: location.paramValue('query', v.name, v.value), rule: 'accepted-value' })); + } if (s.notFound) { ids.functional.notFound = add('functional', { subjectUid: uid, polarity: 'negative', location: location.path(s.notFound.param), rule: 'not-found' }); ids.contract.notFound = add('contract', { subjectUid: uid, polarity: 'positive', location: location.status('404'), rule: 'documented' }); @@ -82,13 +94,21 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): } for (const c of s.bodyCases) { const t = c.target; - ids.contract.body.push(t ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.requestBody(t.field === null ? '' : bodyPointer([t.field])), rule: t.rule }) : ''); + ids.contract.body.push(t?.in === 'body' ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.requestBody(bodyPointer(t.path)), rule: t.rule }) : ''); } - for (const c of s.queryCases) { + for (const c of s.paramCases) { const t = c.target; - ids.contract.query.push(t?.field ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.query(t.field), rule: t.rule }) : ''); + 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; + ids.contract.params.push(at ? add('contract', { subjectUid: uid, polarity: 'negative', location: at, rule: t!.rule }) : ''); } + // Documented error responses (stage 6). + const e = s.errors; + if (e?.invalidCredentials) ids.functional.invalidCredentials = add('functional', { subjectUid: uid, polarity: 'negative', location: location.security(), rule: 'invalid-credentials' }); + if (e?.methodNotAllowed) ids.functional.methodNotAllowed = add('functional', { subjectUid: uid, polarity: 'negative', location: location.operation(), rule: 'method-not-allowed' }); + if (e?.preconditionFailed && chain) ids.functional.preconditionFailed = add('functional', { subjectUid: uid, polarity: 'negative', location: location.header(e.preconditionFailed.header), rule: 'precondition-failed' }, rel); + if (e?.unsupportedMediaType && chain) ids.contract.unsupportedMediaType = add('contract', { subjectUid: uid, polarity: 'negative', location: location.requestContentType(), rule: 'content-type' }, rel); + // CRUD scenarios: steps in order; the operation under test is the action. if (chain) { const step = (o: Operation | undefined, phase: Phase): ScenarioStep[] => (o ? [{ operationUid: uidOf(o), phase }] : []); @@ -104,9 +124,30 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): scenarios[sUid] = def; return add('scenario', { subjectUid: sUid, polarity: 'positive', location: location.lifecycle(), rule: 'crud' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uid))] }); }; + if (s.scenarios.conflict) { + // A business rule confirmed by the deps file: the same create twice conflicts. Business scenarios have no roles. + const steps = [...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.delete, 'cleanup')]; + const sUid = scenarioUid('business', steps); + scenarios[sUid] = { scenarioType: 'business', primaryOperationUid: uid, steps }; + ids.scenario.conflict = add('scenario', { subjectUid: sUid, polarity: 'negative', location: location.lifecycle(), rule: 'business-rule' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uid))] }); + } + if (s.scenarios.deleteTwice) { + // Deleting the same resource twice: the second delete gets the documented 404. + const steps = [...step(chain.create, 'setup'), ...step(s.op, 'action'), { operationUid: uid, phase: 'assertion' as Phase }]; + const sUid = scenarioUid('crud', steps); + scenarios[sUid] = { scenarioType: 'crud', primaryOperationUid: uid, steps, roles: { create: chain.create ? uidOf(chain.create) : null, read: null, update: null, delete: uid } }; + ids.scenario.deleteTwice = add('scenario', { subjectUid: sUid, polarity: 'negative', location: location.lifecycle(), rule: 'business-rule' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uid))] }); + } if (s.scenarios.createRead) ids.scenario.createRead = define([...step(chain.create, 'action'), ...step(chain.read, 'assertion'), ...step(chain.delete, 'cleanup')]); if (s.scenarios.updateRead) ids.scenario.updateRead = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion'), ...step(chain.delete, 'cleanup')]); if (s.scenarios.deleteGone) ids.scenario.deleteGone = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion')]); } + // Reviewed business scenarios: identity from the external ID (never from the title or the steps). + for (const sc of s.business ?? []) { + const steps = sc.steps.map((st) => ({ operationUid: uidOf(st.op), phase: st.phase })); + const sUid = scenarioUid('business', steps, sc.id); + scenarios[sUid] = { scenarioType: 'business', primaryOperationUid: uidOf(sc.primaryOp), steps, externalId: sc.id }; + ids.scenario.business.push(add('scenario', { subjectUid: sUid, polarity: sc.polarity, location: location.lifecycle(), rule: 'business-rule' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uidOf(sc.primaryOp)))] })); + } return ids; } diff --git a/src/cases/ids.ts b/src/cases/ids.ts index 07ad5b8..81c65d8 100644 --- a/src/cases/ids.ts +++ b/src/cases/ids.ts @@ -10,7 +10,11 @@ import { base32 } from '../change/normalize.js'; export type SuiteType = 'functional' | 'contract' | 'scenario'; export type Polarity = 'positive' | 'negative'; -export const CASE_RULE_VOCABULARY_VERSION = 1; +/** + * v2 adds functional/positive `accepted-value` (one case per documented parameter value) and functional/negative + * `invalid-credentials`, `method-not-allowed`, `precondition-failed`. Registries of v1 stay readable. + */ +export const CASE_RULE_VOCABULARY_VERSION = 2; const CONSTRAINT_RULES = [ 'required', 'nullable', 'type', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', @@ -19,8 +23,8 @@ const CONSTRAINT_RULES = [ /** Built-in vocabulary v1, by suiteType/polarity. */ export const VOCABULARY_V1: Record = { - 'functional/positive': ['documented-success'], - 'functional/negative': ['not-found', 'unauthorized', 'forbidden'], + 'functional/positive': ['documented-success', 'accepted-value'], + 'functional/negative': ['not-found', 'unauthorized', 'forbidden', 'invalid-credentials', 'method-not-allowed', 'precondition-failed'], 'contract/positive': ['documented', 'schema'], 'contract/negative': [...CONSTRAINT_RULES, 'content-type'], 'scenario/positive': ['crud', 'business-rule'], @@ -56,6 +60,9 @@ export const location = { requestContentType: () => 'request.content-type', query: (name: string) => `request.query#/${encodeSegment(name)}`, path: (name: string) => `request.path#/${encodeSegment(name)}`, + /** One documented value of a parameter: `request.query#//` (string, number or boolean as in the spec). */ + paramValue: (where: 'query' | 'path' | 'header' | 'cookie', name: string, value: string | number | boolean) => + `request.${where}#/${encodeSegment(where === 'header' ? name.toLowerCase() : name)}/${encodeSegment(String(value))}`, header: (name: string) => `request.header#/${encodeSegment(name.toLowerCase())}`, cookie: (name: string) => `request.cookie#/${encodeSegment(name)}`, /** `pointer` is already a case pointer ('' = body root). */ @@ -81,7 +88,7 @@ export interface CaseIdError { } const UID = /^(op|scn)_[A-Z2-7]{12,52}$/; -const LOCATION = /^(operation|lifecycle|request\.security|request\.content-type|request\.(query|path|header|cookie)#\/[^/]*|request\.body#(\/[^/]*)*|response\.body#(\/[^/]*)*|response\.status#\/[^/]+|response\.content-type#\/[^/]+)$/; +const LOCATION = /^(operation|lifecycle|request\.security|request\.content-type|request\.(query|path|header|cookie)#\/[^/]*(\/[^/]*)?|request\.body#(\/[^/]*)*|response\.body#(\/[^/]*)*|response\.status#\/[^/]+|response\.content-type#\/[^/]+)$/; /** Splits on the five structural colons and checks encoding, vocabulary and the allowed combination (no spec needed). */ export function parseCaseId(id: string): { ok: true; parts: CaseParts } | { ok: false; error: CaseIdError } { @@ -112,16 +119,19 @@ export function checkCombination(p: CaseParts): CaseIdError | undefined { const subject = (why: string): CaseIdError => ({ code: 'INVALID_CASE_SUBJECT', reason: why }); switch (`${p.suiteType}/${p.polarity}`) { case 'functional/positive': + if (p.rule === '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': - if (p.rule === 'not-found') return loc.startsWith('request.path#/') ? undefined : bad('not-found is checked on a path parameter'); + if (p.rule === 'not-found') return /^request\.path#\/[^/]*$/.test(loc) ? undefined : bad('not-found is checked on a path parameter'); + if (p.rule === 'method-not-allowed') return loc === 'operation' ? undefined : bad('method-not-allowed is checked on "operation"'); + if (p.rule === 'precondition-failed') return /^request\.header#\/[^/]*$/.test(loc) ? undefined : bad('precondition-failed is checked on a precondition header'); return loc === 'request.security' ? undefined : bad(`${p.rule} is checked on "request.security"`); case 'contract/positive': if (p.rule === 'schema') return loc.startsWith('response.body#') ? undefined : bad('schema is checked on a response body location'); 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"'); - return /^request\.(body|query|path|header|cookie)#/.test(loc) ? undefined : bad('a constraint rule is checked on a request field or parameter'); + 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'); if (loc === 'operation' && p.polarity === 'negative' && p.rule === 'business-rule') return p.subjectUid.startsWith('op_') ? undefined : subject('a single-operation scenario needs an op_ subject'); diff --git a/src/cases/registry.ts b/src/cases/registry.ts index 9d9bb4a..54111db 100644 --- a/src/cases/registry.ts +++ b/src/cases/registry.ts @@ -159,6 +159,10 @@ export function buildRegistry(i: BuildInput): Registry { if (active.has(uid) || e.status === 'retired') continue; reg.operations[uid] = { ...e, status: 'retired', retiredRevision: i.spec.revision, retiredSpecHash: i.spec.hash, lastValidatedGeneratorVersion: i.generatorVersion }; } + // Cases this run generates are active (a retired one the generator produces again is reactivated: it is the + // same rule on the same subject); every other case stays as a tombstone, never deleted, never reused. + const current = new Set(i.cases.map((c) => c.caseId)); + for (const [id, c] of Object.entries(reg.cases)) if (!current.has(id) && c.status !== 'retired') reg.cases[id] = { ...c, status: 'retired' }; for (const c of i.cases) { const { caseId: id, ...rest } = c; reg.cases[id] = { ...rest }; diff --git a/src/cases/validate.ts b/src/cases/validate.ts index b098b2b..ec1aedb 100644 --- a/src/cases/validate.ts +++ b/src/cases/validate.ts @@ -4,6 +4,7 @@ import { dirname, join } from 'node:path'; import { normalizePath, type NormOp, type NormSpec } from '../change/normalize.js'; import { CASE_RULE_VOCABULARY_VERSION, parseCaseId } from './ids.js'; import { canonicalJson, fileHash, type Registry } from './registry.js'; +import { boundaryValues } from '../generate/boundaries.js'; /** `registry validate` / `manifest validate` (docs/OPENAPI_CHANGE_TRIGGER.md, "Registry validation"). */ @@ -190,9 +191,16 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine const bad = (reason: string): Finding => ({ code: 'INVALID_CASE_LOCATION', pointer: '', reason: `${o.key}: ${reason}` }); const m = loc.match(/^request\.(query|path|header|cookie)#\/(.*)$/); if (m) { - const name = String(decodeSegment(m[2])); + const [rawName, rawValue] = m[2].split('/'); + const name = String(decodeSegment(rawName)); const p = o.params.find((x) => x.in === m[1] && (m[1] === 'header' ? x.name.toLowerCase() === name : x.name === name)); if (!p) return bad(`no ${m[1]} parameter "${name}"`); + if (rawValue !== undefined) { + // accepted-value: the value must be one the spec documents for this parameter. + const value = String(decodeSegment(rawValue)); + const allowed = Array.isArray(p.schema?.enum) ? p.schema.enum.map(String) : p.schema?.const !== undefined ? [String(p.schema.const)] : boundaryValues(p.schema).map(String); + return allowed.includes(value) ? undefined : bad(`"${value}" is not a documented value or valid limit of ${m[1]} "${name}"`); + } if (rule !== 'required' && rule !== 'not-found' && !ruleFits(p.schema, rule)) return { code: 'INVALID_CASE_RULE_FOR_SCHEMA', pointer: '', reason: `${o.key}: "${rule}" does not apply to ${m[1]} "${name}"` }; return undefined; } diff --git a/src/cli.ts b/src/cli.ts index 3ec84c2..0f670ee 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -11,6 +11,7 @@ import { runSchemathesis } from './audit/schemathesis.js'; import { resolveAuth } from './audit/auth.js'; import { buildReport, writeReport, type AuditReport } from './report/report.js'; import { cleanupSummary, generate, runGenerated, scenarioFindings } from './generate/generate.js'; +import { summarize } from './generate/coverage.js'; import { openDraftPr } from './pr.js'; import type { Finding, Operation } from './types.js'; import { classifyTarget, loadConfig } from './config.js'; @@ -23,6 +24,8 @@ import { SUPPORTED_OASDIFF_VERSION } from './change/oasdiff.js'; import { normalizeSpec } from './change/normalize.js'; import { readSource } from './change/network.js'; import { validateManifest, validateRegistry } from './cases/validate.js'; +import { validateScenarios, type ResolvedScenario } from './scenarios/dsl.js'; +import { isUrl } from './change/network.js'; import { accountNotice, ACCOUNT_MODES, checkRegisterConfig, missingLoginVars, parseAccountMode, registerAccount, type AccountMode } from './audit/account.js'; import { AiRunner, describeAiError, RUNNERS, type RunnerKind } from './ai/runner.js'; import { proposeDependencies } from './ai/dependencies.js'; @@ -214,6 +217,8 @@ common(program.command('audit').description('analyse a spec (and, if allowed, a common(program.command('generate').description('audit, then generate Playwright API tests for confirmed CRUD dependencies')) .option('--tests-dir ', 'where generated tests are written (default: API_TESTS_DIR or tests/api)') .option('--deps ', 'JSON file with human-confirmed dependencies') + .option('--scenarios ', 'reviewed business scenarios (schemas/scenarios.schema.json); validated against the spec') + .option('--max-cases ', 'request-body negative cases per operation; the rest is reported as CASE_LIMIT_REACHED', '60') .addOption(new Option('--lang ', 'language of generated tests (default: API_TESTS_LANG or typescript)').choices(['typescript', 'python'])) .option('--run', 'run the generated tests once against --base-url (needs --allow-write)', false) .option('--draft-pr', 'commit to a new branch and open a GitHub Draft PR for review', false) @@ -221,7 +226,7 @@ common(program.command('generate').description('audit, then generate Playwright .addOption(new Option('--ai-runner ', 'console tool: claude, codex, or command (API_AI_COMMAND). Default: API_AI or claude').choices(RUNNERS)) .option('--ai-max-calls ', 'AI call budget per run', '10') .option('--ai-model ', 'model name passed to the console tool (default: its own default)') - .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; aiModel?: string; aiRunner?: RunnerKind }) => { + .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; maxCases: string; scenarios?: string; aiModel?: string; aiRunner?: RunnerKind }) => { const location = await resolveInputs(specArg, o); o.testsDir ??= cfg.testsDir; o.lang ??= cfg.testsLang; @@ -235,13 +240,30 @@ common(program.command('generate').description('audit, then generate Playwright const deps = o.deps ? JSON.parse(await readFile(o.deps, 'utf8')) : undefined; if (o.ai) await aiProposals(r.spec.doc, r.ops, o.out, { maxCalls: Number(o.aiMaxCalls), model: o.aiModel, runner: o.aiRunner }, deps); log('Generating test suites (functional / contract / scenarios)…'); - const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang }); + const maxCases = Number(o.maxCases); + if (!Number.isInteger(maxCases) || maxCases < 1) throw new Error(`--max-cases must be a positive integer, got "${o.maxCases}".`); + let scenarios: ResolvedScenario[] | undefined; + if (o.scenarios) { + const checked = validateScenarios(JSON.parse(await readFile(o.scenarios, 'utf8')), r.ops); + if (checked.errors.length) throw new Error(`${o.scenarios} is invalid:\n${checked.errors.map((e) => ` ${e.pointer || '(root)'}: ${e.reason}`).join('\n')}`); + scenarios = checked.scenarios; + log(`Scenarios: ${scenarios.length} reviewed business scenario(s) from ${o.scenarios}`); + } + const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases, scenarios }); for (const s of gen.scenarios) log(` ${s.status.padEnd(9)} ${s.name}`); for (const f of gen.removed) log(` REMOVED ${relative(process.cwd(), f).replace(/\\/g, '/')} (generated earlier, no longer produced)`); if (o.run) { log('Running generated tests once (assertions are never changed to pass)…'); await runGenerated(gen, { baseUrl: o.baseUrl! }, o.out, o.lang); for (const s of gen.scenarios.filter((x) => x.file)) log(` ${s.status.padEnd(9)} ${s.name}`); + const ids = gen.caseIdCheck; + if (ids) { + const bad = ids.missing.length + ids.duplicates.length + ids.unregistered.length; + log(`Case IDs: ${ids.tests} test(s)${bad ? ` · WARNING: ${ids.missing.length} without an ID, ${ids.duplicates.length} duplicated, ${ids.unregistered.length} not in cases.json` : ', each with its own registered ID'}`); + for (const t of ids.missing.slice(0, 10)) log(` NO ID ${t}`); + 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.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}`); @@ -259,11 +281,15 @@ 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.caseIdCheck ? { caseIdCheck: gen.caseIdCheck } : {}), }, }); const files = await writeReport(report, o.out); const coverageFile = join(o.out, 'coverage-gaps.json'); - await writeFile(coverageFile, JSON.stringify({ spec: location, hash: r.spec.hash, operations: gen.coverage }, null, 2) + '\n'); + const byCode = summarize(gen.coverage); + const generated = Object.fromEntries((['functional', 'contract', 'scenario'] as const).map((k) => [k, gen.coverage.reduce((n, c) => n + c.counts[k], 0)])); + await writeFile(coverageFile, JSON.stringify({ spec: location, hash: r.spec.hash, summary: { operations: gen.coverage.length, generated, gapsByCode: byCode }, operations: gen.coverage }, null, 2) + '\n'); + if (Object.keys(byCode).length) log(`Coverage gaps: ${Object.entries(byCode).map(([k, n]) => `${k} ${n}`).join(', ')} (${coverageFile})`); log(`Report: ${files.md}`); log(`Coverage and gaps per operation: ${coverageFile}`); if (o.draftPr) { @@ -387,6 +413,22 @@ program process.exitCode = r.exitCode; }); +program + .command('scenarios') + .description('reviewed business scenarios') + .command('validate') + .description('check a scenarios file against the spec: operations, parameters, documented statuses, saved values, cleanup (exit 1 on an error)') + .argument('', 'scenarios JSON (schemas/scenarios.schema.json)') + .requiredOption('--spec ', 'the spec the scenarios run against') + .option('--allow-network', 'allow a URL --spec', false) + .action(async (file: string, o: { spec: string; allowNetwork: boolean }) => { + const spec = await loadSpec(isUrl(o.spec) ? (o.allowNetwork ? o.spec : (() => { throw new Error(`${o.spec} is a URL: pass --allow-network`); })()) : o.spec); + const r = validateScenarios(JSON.parse(await readFile(file, 'utf8')), buildCatalog(spec.doc)); + log(`${r.scenarios.length} valid scenario(s), ${r.errors.length} error(s)`); + for (const e of r.errors) log(` ${e.pointer || '(root)'}: ${e.reason}`); + if (r.errors.length) process.exitCode = 1; + }); + const registryCmd = program.command('registry').description('the case registry (_support/cases.json): stable operation, case and scenario IDs'); registryCmd .command('validate') diff --git a/src/contract/contract.py b/src/contract/contract.py index 638d985..0228215 100644 --- a/src/contract/contract.py +++ b/src/contract/contract.py @@ -9,10 +9,11 @@ import json import os import sys +import warnings from pathlib import Path from typing import Any -from jsonschema import Draft7Validator, Draft202012Validator, FormatChecker +from jsonschema import Draft7Validator, Draft202012Validator, FormatChecker, ValidationError, validators _UNPARSEABLE = object() @@ -70,6 +71,22 @@ def _nullable(node: Any) -> Any: return out +def fill_vars(value: Any, saved: dict) -> Any: + """Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text.""" + import re + + if isinstance(value, str): + whole = re.fullmatch(r"\{([A-Za-z_]\w*)\}", value) + if whole: + return saved.get(whole.group(1)) + return re.sub(r"\{([A-Za-z_]\w*)\}", lambda m: str(saved.get(m.group(1))), value) + if isinstance(value, list): + return [fill_vars(v, saved) for v in value] + if isinstance(value, dict): + return {k: fill_vars(v, saved) for k, v in value.items()} + return value + + def read_pointer(body: Any, pointer: str) -> Any: node = body for raw in pointer.split("/")[1:]: @@ -83,29 +100,101 @@ def read_pointer(body: Any, pointer: str) -> Any: return node -def _body(res: Any) -> tuple[str | None, Any]: +def _body(res: Any) -> tuple[str | None, Any, str]: content_type = res.headers.get("content-type") + raw = res.text if res.content else "" if content_type and "json" in content_type: if not res.content: - return content_type, None + return content_type, None, raw try: - return content_type, res.json() + return content_type, res.json(), raw except ValueError: - return content_type, _UNPARSEABLE - return content_type, res.text + return content_type, _UNPARSEABLE, raw + return content_type, raw, raw + + +# Statuses that never carry a body (RFC 9110). +_NO_BODY_STATUS = {204, 205, 304} + + +def _drop_write_only_from_required(node: Any, seen: set | None = None) -> None: + """Responses only: a writeOnly property is never sent back, so it is never required in a response.""" + seen = seen if seen is not None else set() + if id(node) in seen: + return + if isinstance(node, list): + seen.add(id(node)) + for n in node: + _drop_write_only_from_required(n, seen) + return + if not isinstance(node, dict): + return + seen.add(id(node)) + props = node.get("properties") + if isinstance(node.get("required"), list) and isinstance(props, dict): + node["required"] = [n for n in node["required"] if not (isinstance(props.get(n), dict) and props[n].get("writeOnly") is True)] + for v in node.values(): + _drop_write_only_from_required(v, seen) + + +def _write_only(validator: Any, write_only: Any, instance: Any, schema: Any): + """writeOnly properties must not appear in a response.""" + if write_only is True: + yield ValidationError("is writeOnly and must not appear in a response") + + +def _header_value(schema: Any, value: str) -> Any: + """A header value as its schema expects it: numbers, booleans and comma-separated arrays (style: simple).""" + types = schema.get("type", []) if isinstance(schema, dict) else [] + types = types if isinstance(types, list) else [types] + + def scalar(v: str, t: list) -> Any: + if ("integer" in t or "number" in t) and v.strip(): + try: + n = float(v) + return int(n) if n.is_integer() and "integer" in t else n + except ValueError: + return v + if "boolean" in t and v in ("true", "false"): + return v == "true" + return v + + if "array" in types: + items = schema.get("items") or {} + it = items.get("type", []) if isinstance(items, dict) else [] + it = it if isinstance(it, list) else [it] + return [scalar(x.strip(), it) for x in value.split(",")] + return scalar(value, types) class ContractValidator: def __init__(self, doc: dict) -> None: self.is31 = str(doc.get("openapi", "")).startswith(("3.1", "3.2")) # both use JSON Schema 2020-12 self.doc = copy.deepcopy(doc) if self.is31 else _nullable(doc) + _drop_write_only_from_required(self.doc) + base = Draft202012Validator if self.is31 else Draft7Validator + self._cls = validators.extend(base, {"writeOnly": _write_only}) self._cache: dict[str, Any] = {} + self.notes: list[str] = [] + + def _validator(self, pointer: str) -> Any: + v = self._cache.get(pointer) + if v is None: + # The whole document is the root, so "#/components/..." refs resolve; "$ref" selects the schema. + v = self._cache[pointer] = self._cls({**self.doc, "$ref": "#" + pointer}, format_checker=FormatChecker()) + return v + + @staticmethod + def _messages(validator: Any, instance: Any, prefix: str = "") -> list[str]: + errors = sorted(validator.iter_errors(instance), key=lambda e: list(e.absolute_path)) + return [f"{prefix}/{'/'.join(str(p) for p in e.absolute_path) or '(root)'} {e.message}" for e in errors] @classmethod def from_file(cls, path: str | Path) -> "ContractValidator": return cls(json.loads(Path(path).read_text(encoding="utf-8"))) - def validate(self, method: str, path: str, status: int, content_type: str | None, body: Any) -> tuple[bool, str | None, list[str]]: + def validate(self, method: str, path: str, status: int, content_type: str | None, body: Any, raw_text: str | None = None, headers: Any = None) -> tuple[bool, str | None, list[str]]: + """Same rules as validator.ts. Notes on what was not checked go to self.notes.""" op_ptr = f"/paths/{_esc(path)}/{method.lower()}" responses, _ = _resolve(self.doc, f"{op_ptr}/responses") responses = responses or {} @@ -114,8 +203,37 @@ def validate(self, method: str, path: str, status: int, content_type: str | None if matched is None: return False, "undocumented-status", [f"Status {code} is not documented (documented: {', '.join(responses) or 'none'})"] resp, resp_ptr = _resolve(self.doc, f"{op_ptr}/responses/{_esc(matched)}") - content = (resp or {}).get("content") or {} - if not content: + resp = resp or {} + + # Response headers: required ones present, every documented one matching its schema. + got = {k.lower(): v for k, v in (headers or {}).items()} + header_errors: list[str] = [] + for name, raw_def in (resp.get("headers") or {}).items(): + if name.lower() == "content-type": + continue # OpenAPI: ignored, the media type decides + hdef, hptr = _resolve(self.doc, f"{resp_ptr}/headers/{_esc(name)}") + hdef = hdef or {} + value = got.get(name.lower()) + if value is None: + if hdef.get("required"): + header_errors.append(f'Required response header "{name}" is missing') + continue + if headers is None or not hdef.get("schema"): + continue + schema, _ = _resolve(self.doc, f"{hptr}/schema") + header_errors += self._messages(self._validator(f"{hptr}/schema"), _header_value(schema or {}, value), f'header "{name}" ') + if header_errors: + return False, "header", header_errors + + # Without the raw text, the parsed body stands for it (JSON null is the text "null", not an empty body). + raw = raw_text if raw_text is not None else ("" if body is _UNPARSEABLE else (body if isinstance(body, str) else json.dumps(body))) + content = resp.get("content") or {} + head = method.lower() == "head" + if not content or status in _NO_BODY_STATUS or head: + # No body is documented (or the status / method has none): one that arrives anyway breaks the contract. + if raw.strip() and not head: + why = f"status {code} has no body" if status in _NO_BODY_STATUS else f"no content is documented for {matched}" + return False, "unexpected-body", [f"A body was returned but {why} ({len(raw)} bytes)"] return True, None, [] actual = (content_type or "").split(";")[0].strip().lower() # Compare without parameters: "application/json; v=1.0" documents "application/json". @@ -124,27 +242,35 @@ def validate(self, method: str, path: str, status: int, content_type: str | None if media is None: kind = actual.split("/")[0] media = next((k for k in content if base(k) == f"{kind}/*"), None) or next((k for k in content if base(k) == "*/*"), None) + # A declared but undocumented Content-Type is the more precise problem; an empty body comes next. + if not raw.strip() and (not actual or media is not None): + if any((m or {}).get("schema") for m in content.values()): + return False, "empty-body", [f"The body is empty but {matched} documents {', '.join(content)}"] + return True, None, [] if media is None: return False, "content-type", [f'Content-Type "{actual or "none"}" is not documented for {matched} (documented: {", ".join(content)})'] - if "json" not in media or not (content.get(media) or {}).get("schema"): + schema_ptr = f"{resp_ptr}/content/{_esc(media)}/schema" + if not (content.get(media) or {}).get("schema"): + self.notes.append(f"{matched} {media}: no schema documented, body not checked") + return True, None, [] + if base(media).startswith("text/"): + msgs = self._messages(self._validator(schema_ptr), raw) + return not msgs, ("schema" if msgs else None), msgs + if "json" not in base(media): + self.notes.append(f"{matched} {media}: media type not supported by the validator, body not checked") return True, None, [] if body is _UNPARSEABLE: return False, "unparseable-body", ["Body is not valid JSON"] - schema_ptr = f"{resp_ptr}/content/{_esc(media)}/schema" - validator = self._cache.get(schema_ptr) - if validator is None: - # The whole document is the root, so "#/components/..." refs resolve; "$ref" selects the response schema. - root = {**self.doc, "$ref": "#" + schema_ptr} - cls = Draft202012Validator if self.is31 else Draft7Validator - validator = self._cache[schema_ptr] = cls(root, format_checker=FormatChecker()) - errors = sorted(validator.iter_errors(body), key=lambda e: list(e.absolute_path)) - msgs = [f"/{'/'.join(str(p) for p in e.absolute_path) or '(root)'} {e.message}" for e in errors] + msgs = self._messages(self._validator(schema_ptr), body) return not msgs, ("schema" if msgs else None), msgs def expect(self, res: Any, method: str, path: str) -> Any: - """Status, content type and body must match the spec. Failures are tagged CONTRACT_MISMATCH.""" - content_type, body = _body(res) - ok, kind, errors = self.validate(method, path, res.status_code, content_type, body) + """Status, headers, content type and body must match the spec. Failures are tagged CONTRACT_MISMATCH.""" + 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)) + for note in self.notes: + warnings.warn(f"contract note: {note}", stacklevel=2) assert ok, f"CONTRACT_MISMATCH {method.upper()} {path} ({kind}): {'; '.join(errors)}" return None if body is _UNPARSEABLE else body diff --git a/src/contract/validator.ts b/src/contract/validator.ts index c74357c..9d5da94 100644 --- a/src/contract/validator.ts +++ b/src/contract/validator.ts @@ -4,6 +4,7 @@ * This file is deliberately self-contained (no imports from the agent): `generate` * copies it verbatim into tests/generated/_support/ so generated tests run without * the agent installed. Keep it dependency-light: ajv + ajv-formats only. + * src/contract/contract.py is its Python twin: keep the rules identical. */ import { Ajv, type ValidateFunction } from 'ajv'; import { Ajv2020 } from 'ajv/dist/2020.js'; @@ -11,7 +12,7 @@ import addFormatsModule from 'ajv-formats'; const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; -export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body'; +export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body' | 'empty-body' | 'unexpected-body' | 'header'; export interface ContractResult { ok: boolean; @@ -20,9 +21,26 @@ export interface ContractResult { kind?: ContractProblemKind; errors: string[]; matchedStatus?: string; + /** What was not checked and why (e.g. a media type without a supported schema). Never a failure. */ + notes?: string[]; +} + +export interface ResponseInput { + method: string; + path: string; + status: number; + contentType?: string | null; + /** Parsed JSON for JSON media types, the text otherwise; undefined when JSON could not be parsed. */ + body: unknown; + /** The raw response text: decides "empty" and "unexpected body". */ + rawText?: string; + /** Response headers (any case). */ + headers?: Record; } const DOC_ID = 'openapi.json'; +/** Statuses that never carry a body (RFC 9110). */ +const NO_BODY_STATUS = new Set([204, 205, 304]); export class ContractValidator { private readonly ajv: Ajv; @@ -31,14 +49,33 @@ export class ContractValidator { constructor(doc: any) { const is31 = /^3\.[12]\./.test(String(doc.openapi ?? '')); // 3.1 and 3.2: JSON Schema 2020-12 - this.doc = is31 ? structuredClone(doc) : nullableToJsonSchema(structuredClone(doc)); + const copy = structuredClone(doc); + // Responses only: a writeOnly property is never sent back, so it is never required in a response. + dropWriteOnlyFromRequired(copy); + this.doc = is31 ? copy : nullableToJsonSchema(copy); const opts = { strict: false, allErrors: true, validateSchema: false } as const; this.ajv = (is31 ? new Ajv2020(opts) : new Ajv(opts)) as Ajv; addFormats(this.ajv); + // writeOnly properties must not appear in a response. + this.ajv.removeKeyword('writeOnly'); // ajv knows it as an annotation; redefine it as a check + this.ajv.addKeyword({ keyword: 'writeOnly', schemaType: 'boolean', validate: (writeOnly: boolean) => !writeOnly, errors: false }); this.ajv.addSchema(this.doc, DOC_ID); } - validateResponse(input: { method: string; path: string; status: number; contentType?: string | null; body: unknown }): ContractResult { + private compile(pointer: string): ValidateFunction { + let validate = this.cache.get(pointer); + if (!validate) { + validate = this.ajv.compile({ $ref: `${DOC_ID}#${pointer}` }); + this.cache.set(pointer, validate); + } + return validate; + } + + private messages(validate: ValidateFunction, prefix = ''): string[] { + return (validate.errors ?? []).map((e) => `${prefix}${e.instancePath || '(root)'} ${e.keyword === 'writeOnly' ? 'is writeOnly and must not appear in a response' : e.message}`); + } + + validateResponse(input: ResponseInput): ContractResult { const opPtr = `/paths/${esc(input.path)}/${input.method.toLowerCase()}`; const responses = resolve(this.doc, `${opPtr}/responses`).node ?? {}; const code = String(input.status); @@ -52,11 +89,33 @@ export class ContractValidator { }; } const resp = resolve(this.doc, `${opPtr}/responses/${esc(matched)}`); + const notes: string[] = []; + + // Response headers: required ones present, every documented one matching its schema. + const headerErrors = this.checkHeaders(resp.node?.headers ?? {}, `${resp.pointer}/headers`, input.headers); + if (headerErrors.length) return { ok: false, bodyChecked: false, kind: 'header', matchedStatus: matched, errors: headerErrors }; + + // Without the raw text, the parsed body stands for it (JSON null is the text "null", not an empty body). + const raw = input.rawText ?? (typeof input.body === 'string' ? input.body : input.body === undefined ? '' : JSON.stringify(input.body)); const content = resp.node?.content; - if (!content || !Object.keys(content).length) return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const head = input.method.toLowerCase() === 'head'; + if (!content || !Object.keys(content).length || NO_BODY_STATUS.has(input.status) || head) { + // No body is documented (or the status / method has none): one that arrives anyway breaks the contract. + if (raw.trim().length && !head) { + const why = NO_BODY_STATUS.has(input.status) ? `status ${code} has no body` : `no content is documented for ${matched}`; + return { ok: false, bodyChecked: true, kind: 'unexpected-body', matchedStatus: matched, errors: [`A body was returned but ${why} (${raw.length} bytes)`] }; + } + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, ...(notes.length ? { notes } : {}) }; + } const actual = (input.contentType ?? '').split(';')[0].trim().toLowerCase(); const mediaKey = pickMedia(Object.keys(content), actual); + // A declared but undocumented Content-Type is the more precise problem; an empty body comes next. + if (!raw.trim().length && (!actual || mediaKey)) { + const hasSchema = Object.values(content).some((m) => m?.schema); + if (hasSchema) return { ok: false, bodyChecked: true, kind: 'empty-body', matchedStatus: matched, errors: [`The body is empty but ${matched} documents ${Object.keys(content).join(', ')}`] }; + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + } if (!mediaKey) { return { ok: false, @@ -66,28 +125,72 @@ export class ContractValidator { errors: [`Content-Type "${actual || 'none'}" is not documented for ${matched} (documented: ${Object.keys(content).join(', ')})`], }; } - if (!content[mediaKey]?.schema || !mediaKey.includes('json')) { - return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; + if (!content[mediaKey]?.schema) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: no schema documented, body not checked`] }; + } + if (baseMedia(mediaKey).startsWith('text/')) { + // Text bodies with a schema: the text is the (string) instance. + const validate = this.compile(schemaPtr); + const ok = validate(raw) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } + if (!baseMedia(mediaKey).includes('json')) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: media type not supported by the validator, body not checked`] }; } if (input.body === undefined) { return { ok: false, bodyChecked: true, kind: 'unparseable-body', matchedStatus: matched, errors: ['Body is not valid JSON'] }; } + const validate = this.compile(schemaPtr); + const ok = validate(input.body) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } - const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; - let validate = this.cache.get(schemaPtr); - if (!validate) { - validate = this.ajv.compile({ $ref: `${DOC_ID}#${schemaPtr}` }); - this.cache.set(schemaPtr, validate); + private checkHeaders(defs: Record, pointer: string, actual?: Record): string[] { + const errors: string[] = []; + const got = Object.fromEntries(Object.entries(actual ?? {}).map(([k, v]) => [k.toLowerCase(), v])); + for (const [name, raw] of Object.entries(defs)) { + if (name.toLowerCase() === 'content-type') continue; // OpenAPI: ignored, the media type decides + const def = raw?.$ref ? resolve(this.doc, raw.$ref.slice(1)).node : raw; + const value = got[name.toLowerCase()]; + if (value === undefined) { + if (def?.required) errors.push(`Required response header "${name}" is missing`); + continue; + } + if (!def?.schema || actual === undefined) continue; + const validate = this.compile(`${pointer}/${esc(name)}/schema`); + if (!(validate(headerValue(def.schema, value, this.doc)) as boolean)) errors.push(...this.messages(validate, `header "${name}" `)); } - const ok = validate(input.body) as boolean; - return { - ok, - bodyChecked: true, - kind: ok ? undefined : 'schema', - matchedStatus: matched, - errors: ok ? [] : (validate.errors ?? []).map((e) => `${e.instancePath || '(root)'} ${e.message}`), - }; + return errors; + } +} + +/** A header value as its schema expects it: numbers, booleans and comma-separated arrays (style: simple). */ +function headerValue(schemaRaw: any, value: string, doc: any): unknown { + const schema = schemaRaw?.$ref ? resolve(doc, schemaRaw.$ref.slice(1)).node : schemaRaw; + const types: string[] = schema?.type === undefined ? [] : Array.isArray(schema.type) ? schema.type : [schema.type]; + const scalar = (v: string, t: string[]) => { + if ((t.includes('integer') || t.includes('number')) && v.trim() !== '' && !Number.isNaN(Number(v))) return Number(v); + if (t.includes('boolean') && (v === 'true' || v === 'false')) return v === 'true'; + return v; + }; + if (types.includes('array')) { + const items = schema.items?.$ref ? resolve(doc, schema.items.$ref.slice(1)).node : schema.items; + const it: string[] = items?.type === undefined ? [] : Array.isArray(items.type) ? items.type : [items.type]; + return value.split(',').map((v) => scalar(v.trim(), it)); + } + return scalar(value, types); +} + +/** Removes writeOnly properties from every `required` list (they are never part of a response). */ +function dropWriteOnlyFromRequired(node: any, seen = new Set()): void { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node)) return node.forEach((n) => dropWriteOnlyFromRequired(n, seen)); + if (Array.isArray(node.required) && node.properties && typeof node.properties === 'object') { + node.required = node.required.filter((name: string) => node.properties[name]?.writeOnly !== true); } + for (const v of Object.values(node)) dropWriteOnlyFromRequired(v, seen); } /** Media types are compared without parameters: "application/json; v=1.0" documents "application/json". */ diff --git a/src/generate/body-cases.ts b/src/generate/body-cases.ts new file mode 100644 index 0000000..8eb647f --- /dev/null +++ b/src/generate/body-cases.ts @@ -0,0 +1,310 @@ +import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; +import { ARRAY, bodyPointer } from '../cases/ids.js'; +import type { NegCase } from './negative.js'; + +/** + * Request-body negative cases, recursive (docs/SUPPORT_MATRIX.md, stage 3). + * Start from a VALID payload and break exactly ONE rule per case, at any depth: `request.body#/customer/name`, + * `request.body#/items/*\/sku` (the first array element stands for `*`). A rule that cannot be broken without + * breaking another one too (or without a valid element to start from) becomes a coverage gap, never a guess. + */ + +export type PathSeg = string | typeof ARRAY; + +export interface CoverageGap { + code: string; // MISSING_VALID_SAMPLE, CANNOT_ISOLATE_RULE, UNSUPPORTED_SCHEMA_KEYWORD, CASE_LIMIT_REACHED, … + location: string; // case location, e.g. request.body#/customer/address + rule?: string; + reason: string; +} + +export interface BodyCaseResult { + cases: NegCase[]; + gaps: CoverageGap[]; + /** Every case found before the limit. */ + potential: number; + /** Cases dropped by the limit (also listed in gaps as CASE_LIMIT_REACHED). */ + dropped: { location: string; rule: string }[]; +} + +export const DEFAULT_MAX_BODY_CASES = 60; + +const deref = (doc: OpenApiDoc, s: any, depth = 0): any => (s?.$ref && depth < 20 ? deref(doc, resolvePointer(doc, s.$ref.slice(1)).node, depth + 1) : s); +const typesOf = (s: any): string[] => (s?.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type]); +const mainType = (s: any): string | undefined => typesOf(s).find((t) => t !== 'null') ?? (s?.properties ? 'object' : s?.items ? 'array' : undefined); +const allowsNull = (s: any) => typesOf(s).includes('null') || s?.nullable === true || (Array.isArray(s?.enum) && s.enum.includes(null)); +const isNum = (t?: string) => t === 'number' || t === 'integer'; + +/** Merges `allOf` parts that are plain objects (properties, required); anything else is left for the gap check. */ +function merged(doc: OpenApiDoc, raw: any): any { + const s = deref(doc, raw); + if (!s || !Array.isArray(s.allOf)) return s; + const { allOf, ...rest } = s; + const out: any = { ...rest }; + for (const partRaw of allOf) { + const part = merged(doc, partRaw); + if (!part || typeof part !== 'object') continue; + for (const [k, v] of Object.entries(part)) { + if (k === 'properties') out.properties = { ...(out.properties ?? {}), ...v }; + else if (k === 'required') out.required = [...new Set([...(out.required ?? []), ...v])]; + else if (out[k] === undefined) out[k] = v; + } + } + return out; +} + +const clone = (v: T): T => structuredClone(v); +function setAt(root: unknown, path: PathSeg[], value: unknown): unknown { + if (!path.length) return value; + const out = clone(root) as any; + let node = out; + for (let i = 0; i < path.length - 1; i++) node = node[path[i] === ARRAY ? 0 : (path[i] as string)]; + const last = path[path.length - 1]; + node[last === ARRAY ? 0 : (last as string)] = value; + return out; +} +function removeAt(root: unknown, path: PathSeg[]): unknown { + const out = clone(root) as any; + let node = out; + for (let i = 0; i < path.length - 1; i++) node = node[path[i] === ARRAY ? 0 : (path[i] as string)]; + delete node[path[path.length - 1] as string]; + return out; +} + +const label = (path: PathSeg[]) => path.map((p, i) => (p === ARRAY ? '[]' : `${i ? '.' : ''}${p}`)).join('') || '(body)'; + +/** A string that does not match `pattern`, within the length limits; undefined when none of the candidates works. */ +function violatePattern(pattern: string, minLength = 0, maxLength = Infinity): string | undefined { + let re: RegExp; + try { + re = new RegExp(pattern, 'u'); + } catch { + return undefined; + } + const seeds = ['!', '~', ' ', '#', '0', 'a', 'Z', '-', '_']; + for (const seed of seeds) { + for (let len = Math.max(minLength, 1); len <= Math.min(maxLength, Math.max(minLength, 1) + 3); len++) { + const v = seed.repeat(len); + if (!re.test(v)) return v; + } + } + return undefined; +} + +/** Strings that are certainly not of the format (and still strings). */ +const BAD_FORMAT: Record = { + email: 'not-an-email', + uuid: 'not-a-uuid', + 'date-time': 'not-a-date-time', + date: 'not-a-date', + time: 'not-a-time', + uri: 'not a uri', + url: 'not a url', + hostname: '-not_a_host-', + ipv4: '999.999.999.999', + ipv6: 'not-an-ipv6', +}; + +function wrongTypeValue(t: string): unknown { + return { string: 12345, integer: 'not-a-number', number: 'not-a-number', boolean: 'not-a-boolean', array: 'not-an-array', object: 'not-an-object' }[t]; +} + +export function bodyCasesDetailed(doc: OpenApiDoc, rawSchema: any, base: unknown, schemaName = 'body', maxCases = DEFAULT_MAX_BODY_CASES): BodyCaseResult { + const cases: NegCase[] = []; + const gaps: CoverageGap[] = []; + const loc = (path: PathSeg[]) => `request.body#${bodyPointer(path)}`; + const add = (path: PathSeg[], rule: string, title: string, data: unknown) => + cases.push({ title, source: `${schemaName}${path.length ? '.' + label(path) : ''}.${rule}`, data, target: { in: 'body', path, rule } }); + const gap = (path: PathSeg[], code: string, reason: string, rule?: string): void => { + gaps.push({ code, location: loc(path), ...(rule ? { rule } : {}), reason }); + }; + + const walk = (raw: any, value: unknown, path: PathSeg[], depth: number): void => { + if (depth > 12) return gap(path, 'UNSUPPORTED_SCHEMA_KEYWORD', 'schema nesting deeper than 12 levels'); + const s = merged(doc, raw); + if (!s || typeof s !== 'object') return; + if (s.readOnly) return; // not sent in requests + const name = label(path); + // Composition other than allOf: which branch rejects a broken value is not deterministic. + for (const k of ['oneOf', 'anyOf', 'not']) { + if (s[k] !== undefined) { + gap(path, 'UNSUPPORTED_SCHEMA_KEYWORD', `${k}${s.discriminator ? ' with discriminator' : ''}: a broken value may still match another branch, so no case is derived below this point`, k); + return; + } + } + const t = mainType(s); + + // type and null: the value of another type / null where null is not allowed. + if (path.length && t) { + const fixed = Array.isArray(s.enum) || s.const !== undefined; // another type / null would also break enum / const + const wt = wrongTypeValue(t); + if (fixed) gap(path, 'CANNOT_ISOLATE_RULE', 'a value of another type (or null) would also break enum / const; the enum / const case covers it', 'type'); + else { + if (wt !== undefined) add(path, 'type', `"${name}" has wrong type (${t} expected)`, setAt(base, path, wt)); + if (!allowsNull(s)) add(path, 'nullable', `"${name}" is null (not nullable)`, setAt(base, path, null)); + } + } + // enum / const for any scalar type. + if (Array.isArray(s.enum) && s.enum.length && path.length) { + const bad = t === 'string' ? '__not_in_enum__' : isNum(t) ? Math.max(...s.enum.filter((x: unknown) => typeof x === 'number')) + 1 : t === 'boolean' ? [true, false].find((b) => !s.enum.includes(b)) : undefined; + if (bad === undefined || !Number.isFinite(bad as number) && isNum(t)) gap(path, 'CANNOT_ISOLATE_RULE', `enum ${JSON.stringify(s.enum)} covers every value of type ${t}`, 'enum'); + else add(path, 'enum', `"${name}" not in enum`, setAt(base, path, bad)); + } + if (s.const !== undefined && path.length) { + const c = s.const; + const bad = typeof c === 'string' ? `${c}__other` : typeof c === 'number' ? c + 1 : typeof c === 'boolean' ? !c : undefined; + if (bad === undefined) gap(path, 'CANNOT_ISOLATE_RULE', 'const of a non-scalar type', 'const'); + else add(path, 'const', `"${name}" differs from const ${JSON.stringify(c)}`, setAt(base, path, bad)); + } + + if (t === 'string' && path.length) { + const others = (except: string) => ['pattern', 'format', 'enum', 'const'].filter((k) => k !== except && s[k] !== undefined); + const lengthOk = (v: string) => (s.minLength === undefined || v.length >= s.minLength) && (s.maxLength === undefined || v.length <= s.maxLength); + if (typeof s.minLength === 'number' && s.minLength > 0) { + if (others('').length) gap(path, 'CANNOT_ISOLATE_RULE', `a shorter string would also break ${others('').join(', ')}`, 'minLength'); + else add(path, 'minLength', `"${name}" shorter than minLength ${s.minLength}`, setAt(base, path, 'x'.repeat(s.minLength - 1))); + } + if (typeof s.maxLength === 'number') { + if (others('').length) gap(path, 'CANNOT_ISOLATE_RULE', `a longer string would also break ${others('').join(', ')}`, 'maxLength'); + else add(path, 'maxLength', `"${name}" longer than maxLength ${s.maxLength}`, setAt(base, path, 'x'.repeat(s.maxLength + 1))); + } + if (typeof s.pattern === 'string') { + const v = others('pattern').length ? undefined : violatePattern(s.pattern, s.minLength, s.maxLength); + if (v === undefined) gap(path, 'CANNOT_ISOLATE_RULE', others('pattern').length ? `a non-matching string would also break ${others('pattern').join(', ')}` : `no simple string violates ${s.pattern} within the length limits`, 'pattern'); + else add(path, 'pattern', `"${name}" does not match pattern ${s.pattern}`, setAt(base, path, v)); + } + if (typeof s.format === 'string') { + const v = BAD_FORMAT[s.format]; + if (v === undefined) gap(path, 'UNSUPPORTED_SCHEMA_KEYWORD', `format "${s.format}" has no known invalid value`, 'format'); + else if (others('format').length || !lengthOk(v)) gap(path, 'CANNOT_ISOLATE_RULE', `an invalid ${s.format} would also break ${[...others('format'), ...(lengthOk(v) ? [] : ['the length limits'])].join(', ')}`, 'format'); + else add(path, 'format', `"${name}" is not a valid ${s.format}`, setAt(base, path, v)); + } + } + + if (isNum(t) && path.length) { + const step = typeof s.multipleOf === 'number' && s.multipleOf > 0 ? s.multipleOf : t === 'integer' ? 1 : 1; + const isMultiple = (v: number) => typeof s.multipleOf !== 'number' || Math.abs(v / s.multipleOf - Math.round(v / s.multipleOf)) < 1e-9; + const inRange = (v: number, skip: string) => + (skip === 'minimum' || s.minimum === undefined || v >= s.minimum) && + (skip === 'maximum' || s.maximum === undefined || v <= s.maximum) && + (skip === 'exclusiveMinimum' || typeof s.exclusiveMinimum !== 'number' || v > s.exclusiveMinimum) && + (skip === 'exclusiveMaximum' || typeof s.exclusiveMaximum !== 'number' || v < s.exclusiveMaximum); + const tryAdd = (rule: string, v: number, title: string) => { + if ((t === 'integer' && !Number.isInteger(v)) || !isMultiple(v) || !inRange(v, rule) || (Array.isArray(s.enum) && s.enum.length)) gap(path, 'CANNOT_ISOLATE_RULE', `${title}: the value ${v} would also break another constraint`, rule); + else add(path, rule, title, setAt(base, path, v)); + }; + if (typeof s.minimum === 'number') { + // OpenAPI 3.0: exclusiveMinimum: true makes the minimum itself invalid. + if (s.exclusiveMinimum === true) tryAdd('exclusiveMinimum', s.minimum, `"${name}" equals the exclusive minimum ${s.minimum}`); + else tryAdd('minimum', s.minimum - step, `"${name}" below minimum ${s.minimum}`); + } + if (typeof s.maximum === 'number') { + if (s.exclusiveMaximum === true) tryAdd('exclusiveMaximum', s.maximum, `"${name}" equals the exclusive maximum ${s.maximum}`); + else tryAdd('maximum', s.maximum + step, `"${name}" above maximum ${s.maximum}`); + } + if (typeof s.exclusiveMinimum === 'number') tryAdd('exclusiveMinimum', s.exclusiveMinimum, `"${name}" equals the exclusive minimum ${s.exclusiveMinimum}`); + if (typeof s.exclusiveMaximum === 'number') tryAdd('exclusiveMaximum', s.exclusiveMaximum, `"${name}" equals the exclusive maximum ${s.exclusiveMaximum}`); + if (typeof s.multipleOf === 'number' && s.multipleOf > 0) { + const cur = typeof value === 'number' ? value : 0; + const candidates = t === 'integer' ? [cur + 1, cur - 1] : [cur + s.multipleOf / 2, cur - s.multipleOf / 2]; + const v = candidates.find((c) => (t !== 'integer' || Number.isInteger(c)) && !isMultipleOf(c, s.multipleOf) && inRange(c, 'multipleOf') && !(Array.isArray(s.enum) && s.enum.length)); + if (v === undefined) gap(path, 'CANNOT_ISOLATE_RULE', `no value next to ${cur} breaks multipleOf ${s.multipleOf} alone`, 'multipleOf'); + else add(path, 'multipleOf', `"${name}" is not a multiple of ${s.multipleOf}`, setAt(base, path, v)); + } + } + + if (t === 'array') { + const arr = Array.isArray(value) ? value : undefined; + if (!arr) return gap(path, 'MISSING_VALID_SAMPLE', 'no valid array value to start from'); + if (typeof s.minItems === 'number' && s.minItems > 0) add(path, 'minItems', `"${name}" has fewer than minItems ${s.minItems}`, setAt(base, path, arr.slice(0, s.minItems - 1))); + if (typeof s.maxItems === 'number') { + if (!arr.length) gap(path, 'MISSING_VALID_SAMPLE', 'no element to repeat', 'maxItems'); + else if (s.uniqueItems) gap(path, 'CANNOT_ISOLATE_RULE', 'repeating an element would also break uniqueItems', 'maxItems'); + else add(path, 'maxItems', `"${name}" has more than maxItems ${s.maxItems}`, setAt(base, path, Array.from({ length: s.maxItems + 1 }, (_, i) => arr[i % arr.length]))); + } + if (s.uniqueItems === true) { + if (!arr.length) gap(path, 'MISSING_VALID_SAMPLE', 'no element to duplicate', 'uniqueItems'); + else { + const dup = arr.length >= 2 ? [arr[0], arr[0], ...arr.slice(2)] : [arr[0], arr[0]]; + if (typeof s.maxItems === 'number' && dup.length > s.maxItems) gap(path, 'CANNOT_ISOLATE_RULE', 'a duplicate element would also break maxItems', 'uniqueItems'); + else add(path, 'uniqueItems', `"${name}" has duplicate items`, setAt(base, path, dup)); + } + } + if (s.items) { + if (!arr.length) gap([...path, ARRAY], 'MISSING_VALID_SAMPLE', 'the array has no element to break constraints of its items'); + else walk(s.items, arr[0], [...path, ARRAY], depth + 1); + } + return; + } + + if (t === 'object' || s.properties) { + const obj = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : undefined; + if (!obj) return gap(path, 'MISSING_VALID_SAMPLE', 'no valid object value to start from'); + const props: Record = s.properties ?? {}; + const required: string[] = s.required ?? []; + for (const r of required) { + if (r in obj) add([...path, r], 'required', `missing required field "${label([...path, r])}"`, removeAt(base, [...path, r])); + else gap([...path, r], 'MISSING_VALID_SAMPLE', `required "${r}" has no valid value in the sample`, 'required'); + } + if (s.additionalProperties === false) { + const extra = '__unexpected_field__'; + if (typeof s.maxProperties === 'number' && Object.keys(obj).length + 1 > s.maxProperties) gap(path, 'CANNOT_ISOLATE_RULE', 'an unknown field would also break maxProperties', 'additionalProperties'); + else add(path, 'additionalProperties', path.length ? `"${name}" has an unknown field (additionalProperties: false)` : 'unknown field is rejected (additionalProperties: false)', setAt(base, path, { ...obj, [extra]: 'api-agent' })); + } + if (typeof s.minProperties === 'number' && s.minProperties > 0) { + // Drop optional properties only, until one fewer than minProperties remain. + const count = Object.keys(obj).length; + const drop = count - s.minProperties + 1; + const optional = Object.keys(obj).filter((k) => !required.includes(k)); + if (count < s.minProperties) gap(path, 'MISSING_VALID_SAMPLE', 'the sample already breaks minProperties'); + else if (optional.length < drop) gap(path, 'CANNOT_ISOLATE_RULE', 'fewer properties would also drop a required one', 'minProperties'); + else { + const removed = optional.slice(0, drop); + add(path, 'minProperties', `"${name}" has fewer than minProperties ${s.minProperties}`, setAt(base, path, Object.fromEntries(Object.entries(obj).filter(([k]) => !removed.includes(k))))); + } + } + if (typeof s.maxProperties === 'number') { + const free = Object.keys(props).filter((k) => !(k in obj) && !deref(doc, props[k])?.readOnly); + const need = s.maxProperties + 1 - Object.keys(obj).length; + if (need <= 0) gap(path, 'MISSING_VALID_SAMPLE', 'the sample already breaks maxProperties'); + else if (s.additionalProperties !== false) add(path, 'maxProperties', `"${name}" has more than maxProperties ${s.maxProperties}`, setAt(base, path, { ...obj, ...Object.fromEntries(Array.from({ length: need }, (_, i) => [`__extra_${i}__`, 'api-agent'])) })); + else gap(path, 'CANNOT_ISOLATE_RULE', `extra properties would break additionalProperties: false (${free.length} documented optional ones have no valid sample)`, 'maxProperties'); + } + for (const [prop, sub] of Object.entries(props)) { + if (prop in obj) walk(sub, obj[prop], [...path, prop], depth + 1); + } + } + }; + + walk(rawSchema, base, [], 0); + const potential = cases.length; + const kept = cases.slice(0, maxCases); + const dropped = cases.slice(maxCases).map((c) => ({ location: loc((c.target as any).path), rule: c.target!.rule })); + for (const d of dropped) gaps.push({ code: 'CASE_LIMIT_REACHED', location: d.location, rule: d.rule, reason: `limit of ${maxCases} body cases per operation (--max-cases)` }); + return { cases: kept, gaps, potential, dropped }; +} + +/** + * oneOf / anyOf in a payload that is sent: one branch is exercised (the example's, or the first), the others are + * reported as UNCOVERED_VARIANT, never dropped silently. + */ +export function compositionGaps(doc: OpenApiDoc, rawSchema: any, value: unknown, path: PathSeg[] = [], depth = 0): CoverageGap[] { + if (depth > 12) return []; + const s = merged(doc, rawSchema); + if (!s || typeof s !== 'object') return []; + const out: CoverageGap[] = []; + for (const k of ['oneOf', 'anyOf']) { + if (Array.isArray(s[k]) && s[k].length > 1) { + out.push({ code: 'UNCOVERED_VARIANT', location: `request.body#${bodyPointer(path)}`, rule: k, reason: `${k}: one of ${s[k].length} branches is sent; ${s[k].length - 1} other(s) are not exercised` }); + } + } + if (Array.isArray(value) && s.items && value.length) out.push(...compositionGaps(doc, s.items, value[0], [...path, ARRAY], depth + 1)); + else if (value && typeof value === 'object' && !Array.isArray(value) && s.properties) { + for (const [prop, sub] of Object.entries(s.properties)) if (prop in (value as object)) out.push(...compositionGaps(doc, sub, (value as any)[prop], [...path, prop], depth + 1)); + } + return out; +} + +function isMultipleOf(v: number, m: number): boolean { + return Math.abs(v / m - Math.round(v / m)) < 1e-9; +} diff --git a/src/generate/boundaries.ts b/src/generate/boundaries.ts new file mode 100644 index 0000000..c813baf --- /dev/null +++ b/src/generate/boundaries.ts @@ -0,0 +1,29 @@ +/** Boundary-valid values shared by the generator (accepted-value cases) and registry validation. */ + +/** + * The valid limits of a scalar schema: minimum / maximum (inside exclusive bounds, on multipleOf) and the shortest / + * longest string (strings without pattern / format, at most 64 characters so the case ID stays readable). + */ +export function boundaryValues(schema: any): (string | number)[] { + const t = Array.isArray(schema?.type) ? schema.type.find((x: string) => x !== 'null') : schema?.type; + const out: (string | number)[] = []; + if (t === 'integer' || t === 'number') { + const m = typeof schema.multipleOf === 'number' && schema.multipleOf > 0 ? schema.multipleOf : t === 'integer' ? 1 : undefined; + const fits = (v: number) => + (t !== 'integer' || Number.isInteger(v)) && + (m === undefined || Math.abs(v / m - Math.round(v / m)) < 1e-9) && + (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) && + !(schema.exclusiveMinimum === true && v === schema.minimum) && + !(schema.exclusiveMaximum === true && v === schema.maximum); + const lo = typeof schema.minimum === 'number' ? schema.minimum : typeof schema.exclusiveMinimum === 'number' && m ? Math.floor(schema.exclusiveMinimum / m + 1) * m : undefined; + const hi = typeof schema.maximum === 'number' ? schema.maximum : typeof schema.exclusiveMaximum === 'number' && m ? Math.ceil(schema.exclusiveMaximum / m - 1) * m : undefined; + for (const v of [lo, hi]) if (v !== undefined && fits(v) && !out.includes(v)) out.push(v); + } + if (t === 'string' && !schema.pattern && !schema.format) { + for (const n of [schema.minLength, schema.maxLength]) if (typeof n === 'number' && n > 0 && n <= 64 && !out.includes('x'.repeat(n))) out.push('x'.repeat(n)); + } + return out; +} diff --git a/src/generate/coverage.ts b/src/generate/coverage.ts new file mode 100644 index 0000000..c1e2b0b --- /dev/null +++ b/src/generate/coverage.ts @@ -0,0 +1,86 @@ +import type { Operation } from '../types.js'; +import type { CoverageGap } from './body-cases.js'; +import type { ErrorPlan } from './error-cases.js'; + +/** + * Coverage report helpers (docs/SUPPORT_MATRIX.md, stage 10): machine codes for every reason a check is missing, + * and what the generated suite leaves unchecked per operation. + */ + +/** Stable machine codes. A new reason gets a new code; a code is never renamed. */ +export const GAP_CODES = [ + 'MISSING_VALID_SAMPLE', + 'MISSING_RESOURCE_SOURCE', + 'MISSING_CLEANUP', + 'MISSING_RESPONSE_SCHEMA', + 'UNSUPPORTED_SCHEMA_KEYWORD', + 'UNSUPPORTED_MEDIA_TYPE', + 'UNCONFIRMED_BUSINESS_RULE', + 'UNCOVERED_VARIANT', + 'CANNOT_ISOLATE_RULE', + 'CASE_LIMIT_REACHED', + 'UNREACHABLE_RESPONSE_STATUS', + 'UNSAFE_LIVE_CHECK', + 'DEPRECATED_OPERATION', + 'NO_DOCUMENTED_REJECTION', +] as const; + +/** The code behind a positive-blocked reason the generator writes in prose. */ +export function positiveCode(reason: string | undefined): string | null { + if (!reason) return null; + if (/deprecated/i.test(reason)) return 'DEPRECATED_OPERATION'; + if (/ends the session/i.test(reason)) return 'UNSAFE_LIVE_CHECK'; + if (/no confirmed precondition\/cleanup|cleaned up|No delete operation/i.test(reason)) return 'MISSING_CLEANUP'; + if (/No example-backed payload|Cannot build a valid|cannot derive/i.test(reason)) return 'MISSING_VALID_SAMPLE'; + if (/No concrete 2xx/i.test(reason)) return 'UNREACHABLE_RESPONSE_STATUS'; + if (/candidate|unconfirmed|Confirm|link the operation/i.test(reason)) return 'MISSING_RESOURCE_SOURCE'; + if (/No value for|spec example|with no value/i.test(reason)) return 'MISSING_RESOURCE_SOURCE'; + return 'UNCONFIRMED_BUSINESS_RULE'; +} + +export interface Exercised { + positive: boolean; + notFound: boolean; + unauthorized: boolean; + validation: string[]; // statuses expected by body / parameter cases + invalidInput: boolean; // there are body / parameter cases + errors?: ErrorPlan; + deleteTwice: boolean; +} + +/** Documented statuses no generated test exercises (2xx counts as exercised by the success call). */ +export function uncheckedStatuses(op: Operation, x: Exercised): { status: string; code: string }[] { + const hit = new Set(); + if (x.positive) for (const r of op.responses) if (/^2/.test(r.status)) hit.add(r.status); + if (x.notFound || x.deleteTwice) hit.add('404'); + if (x.unauthorized || x.errors?.invalidCredentials) hit.add('401'); + if (x.invalidInput) for (const v of x.validation) hit.add(v.toUpperCase()); + if (x.errors?.methodNotAllowed) hit.add('405'); + if (x.errors?.conflict) hit.add('409'); + if (x.errors?.preconditionFailed) hit.add('412'); + if (x.errors?.unsupportedMediaType) hit.add('415'); + // The precise reason when an error gap names this status; otherwise a code by status class. + const reason = (status: string) => x.errors?.gaps.find((g) => g.location === `response.status#/${status}`)?.code; + return op.responses + .filter((r) => !hit.has(r.status.toUpperCase())) + .map((r) => ({ status: r.status, code: reason(r.status) ?? (/^(5|default)/i.test(r.status) ? 'UNREACHABLE_RESPONSE_STATUS' : /^4/.test(r.status) ? 'NO_DOCUMENTED_REJECTION' : 'UNCONFIRMED_BUSINESS_RULE') })); +} + +/** Request media types the suite never sends (it sends JSON), and security alternatives beyond the one it uses. */ +export function uncheckedRequest(op: Operation): { contentTypes: string[]; securityAlternatives: string[][] } { + const json = op.requestContentTypes.find((c) => c.toLowerCase().includes('json')); + return { + contentTypes: op.requestContentTypes.filter((c) => c !== json), + securityAlternatives: op.security.length > 1 ? op.security.slice(1) : [], + }; +} + +/** Totals by code across operations. */ +export function summarize(ops: { gaps: CoverageGap[]; positiveBlockedCode?: string | null }[]): Record { + const out: Record = {}; + for (const o of ops) { + for (const g of o.gaps) out[g.code] = (out[g.code] ?? 0) + 1; + if (o.positiveBlockedCode) out[o.positiveBlockedCode] = (out[o.positiveBlockedCode] ?? 0) + 1; + } + return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b))); +} diff --git a/src/generate/error-cases.ts b/src/generate/error-cases.ts new file mode 100644 index 0000000..0ffd7bd --- /dev/null +++ b/src/generate/error-cases.ts @@ -0,0 +1,105 @@ +import type { OpenApiDoc } from '../spec/loader.js'; +import type { Operation } from '../types.js'; +import type { CrudChain } from './graph.js'; +import type { CoverageGap } from './body-cases.js'; + +/** + * Documented error responses beyond 400 / 401 (missing credentials) / 404 / 422 (docs/SUPPORT_MATRIX.md, stage 6). + * A case is generated only when the request that triggers the error is safe and its expectation is documented; + * everything else is a gap with its reason. Nothing here guesses business rules. + */ + +export interface ErrorPlan { + /** 401 with a credential that is certainly invalid (per security scheme), sent without the real ones. */ + invalidCredentials?: { headers: Record; params: Record }; + /** 405: a GET to a path that defines no GET (the only method that is safe to send to an unknown route). */ + methodNotAllowed?: { method: 'get' }; + /** 415: the documented body sent as text/plain (create / update with confirmed cleanup). */ + unsupportedMediaType?: true; + /** 412: a precondition header that cannot match, on a resource the test created. */ + preconditionFailed?: { header: string; value: string }; + /** 409: the same create payload twice, on fields a reviewed deps file names (conflictOn). */ + conflict?: { fields: string[] }; + gaps: CoverageGap[]; +} + +const INVALID_TOKEN = 'api-agent-invalid-token'; +const PRECONDITION_VALUES: Record = { + 'if-match': '"api-agent-no-such-etag"', + 'if-unmodified-since': 'Thu, 01 Jan 1970 00:00:00 GMT', +}; +/** Statuses with a handler in this module or elsewhere in the generator. */ +const HANDLED = new Set(['400', '401', '403', '404', '405', '409', '412', '415', '422', '429', '4XX']); + +export interface ErrorInput { + doc: OpenApiDoc; + op: Operation; + ops: Operation[]; + chain?: CrudChain; + role?: 'create' | 'read' | 'update' | 'delete'; + hasUpdatePayload: boolean; + /** Write requests may be sent only with a confirmed cleanup (or for safe methods). */ + reachable: boolean; + /** The operation is the first one of its path documenting 405 (one case per path). */ + firstWith405: boolean; +} + +export function errorPlan(i: ErrorInput): ErrorPlan { + const { doc, op } = i; + const plan: ErrorPlan = { gaps: [] }; + const codes = new Set(op.responses.map((r) => r.status.toUpperCase())); + const gap = (code: string, status: string, reason: string) => plan.gaps.push({ code, location: `response.status#/${status}`, reason }); + + // 401: an invalid credential of the scheme the operation uses. + if (codes.has('401') && i.reachable && op.security.length && !op.security.some((a) => a.length === 0)) { + const schemes = (doc as any).components?.securitySchemes ?? {}; + const headers: Record = {}; + const params: Record = {}; + let unknown: string | undefined; + for (const name of op.security[0]) { + const s = schemes[name]; + const type = String(s?.type ?? '').toLowerCase(); + if (type === 'http' && String(s.scheme).toLowerCase() === 'basic') headers.Authorization = `Basic ${Buffer.from('api-agent:invalid').toString('base64')}`; + else if (type === 'http' || type === 'oauth2' || type === 'openidconnect') headers.Authorization = `Bearer ${INVALID_TOKEN}`; + else if (type === 'apikey' && s.in === 'header') headers[s.name] = 'api-agent-invalid-key'; + else if (type === 'apikey' && s.in === 'query') params[s.name] = 'api-agent-invalid-key'; + else if (type === 'apikey' && s.in === 'cookie') headers.Cookie = `${s.name}=api-agent-invalid-key`; + else unknown = name; + } + if (unknown) gap('UNSUPPORTED_SCHEMA_KEYWORD', '401', `security scheme "${unknown}" has no known invalid credential`); + else plan.invalidCredentials = { headers, params }; + } + + // 405: only a GET may be sent to an undocumented method of a path. + if (codes.has('405') && i.firstWith405) { + const defined = new Set(i.ops.filter((o) => o.path === op.path).map((o) => o.method)); + if (!defined.has('get')) plan.methodNotAllowed = { method: 'get' }; + else gap('UNSAFE_LIVE_CHECK', '405', `every undocumented method of ${op.path} could change data if the API implements it`); + } + + // 415: the body as text/plain, where a created resource can be cleaned up. + if (codes.has('415')) { + if (!op.hasRequestBody) gap('UNREACHABLE_RESPONSE_STATUS', '415', 'the operation has no request body'); + else if (i.role === 'create' || (i.role === 'update' && i.hasUpdatePayload)) plan.unsupportedMediaType = true; + else gap('MISSING_CLEANUP', '415', 'a write without a confirmed precondition and cleanup is not sent'); + } + + // 412: a precondition header that cannot match, on the test's own resource. + if (codes.has('412')) { + const header = op.params.find((p) => p.in === 'header' && PRECONDITION_VALUES[p.name.toLowerCase()]); + if (!header) gap('UNCONFIRMED_BUSINESS_RULE', '412', 'no If-Match / If-Unmodified-Since header is documented to trigger it'); + else if ((i.role === 'update' && i.hasUpdatePayload) || i.role === 'delete') plan.preconditionFailed = { header: header.name, value: PRECONDITION_VALUES[header.name.toLowerCase()] }; + else gap('MISSING_CLEANUP', '412', 'needs a resource the test creates and removes (a confirmed update / delete chain)'); + } + + // 409: duplicate create, only on fields a reviewed deps file names. + if (codes.has('409')) { + if (i.role === 'create' && i.chain?.conflictOn?.length) plan.conflict = { fields: i.chain.conflictOn }; + else gap('UNCONFIRMED_BUSINESS_RULE', '409', i.role === 'create' ? 'which fields conflict is not confirmed: add "conflictOn" to the deps file' : 'what makes this operation conflict is not documented'); + } + + if (codes.has('403')) gap('UNCONFIRMED_BUSINESS_RULE', '403', 'needs a reviewed role / scope configuration (an account that must be refused)'); + if (codes.has('429')) gap('UNSAFE_LIVE_CHECK', '429', 'rate limiting is not exercised (it would load the target)'); + for (const c of codes) if (/^4\d\d$/.test(c) && !HANDLED.has(c)) gap('UNREACHABLE_RESPONSE_STATUS', c, `no deterministic request triggers ${c}`); + return plan; +} diff --git a/src/generate/generate.ts b/src/generate/generate.ts index d4401f4..2ca8f2c 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -12,8 +12,13 @@ import { assignCaseIds, type CaseRecord, type ScenarioDefinition } from '../case import { buildRegistry, canonicalJson, fileHash, readRegistry, resolveOperationUids } from '../cases/registry.js'; import { headRevision } from '../change/baseline.js'; import { isUrl } from '../change/network.js'; -import { bodyCases, documentedRejections, nonexistentIdExpr, queryCases } from './negative.js'; -import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; +import { bodyCasesDetailed, compositionGaps, type CoverageGap } from './body-cases.js'; +import { paramCasesDetailed, sendable } from './param-cases.js'; +import { errorPlan } from './error-cases.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 { API_BASE, buildApiIndex, renderApiBaseClass, renderApiChildClass, renderApis } from './api-objects.js'; import { PY_FILES, pyName, renderConftest, renderPyContract, renderPyFunctional, renderPyResource, renderPyScenarios, resourceModule } from './python.js'; @@ -32,6 +37,10 @@ export interface GenerateOptions { deps?: DepsFile; version: string; lang?: TestLang; // default typescript + /** Body negative cases per operation (default 60); the rest is reported as CASE_LIMIT_REACHED. */ + maxCases?: number; + /** Reviewed business scenarios (validated with validateScenarios against the same operations). */ + scenarios?: ResolvedScenario[]; } export interface Scenario { @@ -52,6 +61,8 @@ export interface GenerateResult { coverage: Coverage[]; /** Test data the generated cleanup could not remove during --run (it stays on the target). */ cleanupFailures: CleanupFailure[]; + /** After --run: every physical test has its own registered case ID. */ + caseIdCheck?: CaseIdCheck; } export interface CleanupFailure { @@ -66,6 +77,20 @@ export interface Coverage { positiveBlocked: string | null; negativeGaps: string[]; lifecycle: string | null; + /** Checks that could not be generated, each with a machine code and its exact location. */ + gaps: CoverageGap[]; + /** Body negative cases found / generated / dropped by the limit. */ + bodyCases?: { potential: number; generated: number; dropped: number }; + /** Machine code of positiveBlocked. */ + positiveBlockedCode: string | null; + /** Per suite: generated tests, and the code when the suite is empty. */ + suites: Record; + /** Documented statuses no generated test exercises. */ + uncheckedStatuses: { status: string; code: string }[]; + /** Request media types never sent (the suite sends JSON). */ + uncheckedRequestContentTypes: string[]; + /** Security alternatives beyond the one the suite uses. */ + uncheckedSecurityAlternatives: string[][]; } function jsonBodySchema(spec: LoadedSpec, op: Operation): any { @@ -218,6 +243,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp // 2. Per operation: //{functional,contract,scenarios}.spec.ts, each only when it has a case. // Polarity (positive/negative) is a tag inside the files, not a file of its own. const used = new Set(); + const paths405 = new Set(); // one 405 case per path for (const op of ops) { let { resource, action } = operationFolder(op); if (py) { @@ -233,7 +259,8 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const safe = SAFE_METHODS.includes(op.method); const pathParams = op.params.filter((p) => p.in === 'path'); const unresolvedPath = pathParams.filter((p) => p.knownValue === undefined && p.name !== plan?.chain.param); - const unresolvedQuery = op.params.filter((p) => p.in === 'query' && p.required && p.knownValue === undefined); + // Required query / header / cookie parameters need a documented value, or no valid request exists. + const unresolvedQuery = op.params.filter((p) => p.in !== 'path' && p.required && p.knownValue === undefined && sendable(p)); // --- positive let posReason: string | undefined; @@ -260,7 +287,9 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const reachable = safe || !!plan; // never fire write requests at operations without confirmed cleanup const why: string[] = []; let bCases: ReturnType = []; - let qCases: ReturnType = []; + let bodyGaps: CoverageGap[] = []; + let bodyStats: Coverage['bodyCases']; + let qCases: NegCase[] = []; let notFound: { idExpr: string; param: string } | undefined; let unauthorized = false; @@ -271,8 +300,17 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const schema = jsonBodySchema(spec, op); const base = plan?.chain.create === op ? plan.createPayload : plan?.chain.update === op ? plan.updatePayload : undefined; const bodyTarget = schema && base && typeof base === 'object' && (plan?.chain.create === op || plan?.chain.update === op); - if (bodyTarget) bCases = bodyCases(spec.doc, schema, base as Record, schema.$ref?.split('/').pop() ?? 'body'); - if (!unresolvedPath.length) qCases = queryCases(op); + if (bodyTarget) { + const detailed = bodyCasesDetailed(spec.doc, schema, base, schema.$ref?.split('/').pop() ?? 'body', o.maxCases); + bCases = detailed.cases; + bodyGaps = detailed.gaps; + bodyStats = { potential: detailed.potential, generated: detailed.cases.length, dropped: detailed.dropped.length }; + } + // Path parameters: only where an invalid value cannot reach a request body we cannot build. + const allowPath = !op.requestBodyRequired; + const pc = paramCasesDetailed(spec.doc, op, { allowPath, allowOthers: !unresolvedPath.length }); + qCases = pc.cases; + bodyGaps = [...bodyGaps, ...pc.gaps]; if (!bCases.length && !qCases.length) why.push(`${rej.validation.join('/')} is documented but there is no constraint the agent can break safely`); } else why.push('no 400/422 documented'); @@ -289,12 +327,52 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp } // --- suites - const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, queryCases: qCases, notFound, unauthorized }; + // Documented error responses with a safe trigger; the rest are gaps (stage 6). + const errRole = !plan ? undefined : plan.chain.create === op ? 'create' : plan.chain.read === op ? 'read' : plan.chain.update === op ? 'update' : plan.chain.delete === op ? 'delete' : undefined; + const firstWith405 = op.responses.some((r) => r.status === '405') && !paths405.has(op.path); + if (firstWith405) paths405.add(op.path); + const errors = op.deprecated ? { gaps: [] } : errorPlan({ doc: spec.doc, op, ops, chain: plan?.chain, role: errRole, hasUpdatePayload: plan?.updatePayload !== undefined, reachable, firstWith405 }); + const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors, business: (o.scenarios ?? []).filter((b) => b.primaryOp === op) }; const counts = suiteCounts(input); - const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, queryCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input) }, uidOf); + const variants = input.positive && !plan && op.method === 'get' ? queryVariants(op) : []; + const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants, errors, business: input.business }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. - coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null }); + // oneOf / anyOf in a payload that is sent: the other branches are reported (never dropped silently). + const payloadSchema = plan && (plan.chain.create === op || plan.chain.update === op) ? jsonBodySchema(spec, op) : undefined; + const payloadValue = plan?.chain.create === op ? plan.createPayload : plan?.chain.update === op ? plan.updatePayload : undefined; + const variantGaps: CoverageGap[] = payloadSchema && payloadValue !== undefined ? compositionGaps(spec.doc, payloadSchema, payloadValue) : []; + // Response bodies the validator cannot check: said explicitly, never passed silently. + const responseGaps: CoverageGap[] = op.responses.flatMap((resp) => + resp.contentTypes.flatMap((ct): CoverageGap[] => { + const media = ct.split(';')[0].trim().toLowerCase(); + const loc = `response.content-type#/${media.replace(/~/g, '~0').replace(/\//g, '~1')}`; + if (!resp.hasSchema) return [{ code: 'MISSING_RESPONSE_SCHEMA', location: loc, reason: `${resp.status} ${media}: no schema documented, the body is not checked` }]; + if (!media.includes('json') && !media.startsWith('text/')) return [{ code: 'UNSUPPORTED_MEDIA_TYPE', location: loc, reason: `${resp.status} ${media}: the validator checks JSON and text bodies only` }]; + return []; + }), + ); + const pCode = positiveCode(posReason); + const req = uncheckedRequest(op); + const scn = scenarioCases(input); + coverage.push({ + operation: op.key, + counts, + positiveBlocked: posReason ?? null, + positiveBlockedCode: pCode, + negativeGaps: why, + lifecycle: plan ? plan.chain.name : null, + gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps], + ...(bodyStats ? { bodyCases: bodyStats } : {}), + suites: { + functional: { generated: counts.functional, missingCode: counts.functional ? null : pCode ?? 'NO_DOCUMENTED_REJECTION' }, + contract: { generated: counts.contract, missingCode: counts.contract ? null : pCode ?? 'NO_DOCUMENTED_REJECTION' }, + scenario: { generated: counts.scenario, missingCode: counts.scenario ? null : plan ? pCode ?? 'UNCONFIRMED_BUSINESS_RULE' : 'UNCONFIRMED_BUSINESS_RULE' }, + }, + uncheckedStatuses: uncheckedStatuses(op, { positive: input.positive, notFound: !!notFound, unauthorized, validation: rej.validation, invalidInput: bCases.length + qCases.length > 0, errors, deleteTwice: scn.deleteTwice }), + uncheckedRequestContentTypes: req.contentTypes, + uncheckedSecurityAlternatives: req.securityAlternatives, + }); const render: Record string> = py ? { functional: renderPyFunctional, contract: renderPyContract, scenario: renderPyScenarios } : { functional: renderFunctional, contract: renderContract, scenario: renderScenarios }; @@ -476,8 +554,15 @@ export async function runGenerated(result: GenerateResult, env: { baseUrl: strin const cleanupLog = resolve(outDir, 'cleanup-failures.jsonl'); await mkdir(dirname(cleanupLog), { recursive: true }); await rm(cleanupLog, { force: true }); - const runEnv = { ...process.env, API_BASE_URL: env.baseUrl, API_AGENT_CLEANUP_LOG: cleanupLog }; + 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 }; 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 { @@ -489,6 +574,52 @@ export async function runGenerated(result: GenerateResult, env: { baseUrl: strin : []; } +export interface CaseIdCheck { + tests: number; + /** Tests without a case ID. */ + missing: string[]; + /** Case IDs carried by more than one physical test. */ + duplicates: string[]; + /** Case IDs that are not in _support/cases.json. */ + unregistered: string[]; +} + +export function checkCaseIds(tests: { test: string; caseId: string | null }[], registered: Set): CaseIdCheck { + const count = new Map(); + for (const t of tests) if (t.caseId) count.set(t.caseId, (count.get(t.caseId) ?? 0) + 1); + return { + tests: tests.length, + missing: tests.filter((t) => !t.caseId).map((t) => t.test), + duplicates: [...count].filter(([, n]) => n > 1).map(([id]) => id), + unregistered: [...count.keys()].filter((id) => !registered.has(id)), + }; +} + +async function readCollected(file: string): Promise<{ test: string; caseId: string | null }[]> { + if (!existsSync(file)) return []; + return (await readFile(file, 'utf8')).split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l)); +} + +/** Case IDs from the Playwright JSON report: the `caseId` annotation of every test. */ +async function playwrightCaseIds(file: string): Promise<{ test: string; caseId: string | null }[]> { + if (!existsSync(file)) return []; + const report = JSON.parse(await readFile(file, 'utf8')); + const out: { test: string; caseId: string | null }[] = []; + const walk = (suite: any, file?: string) => { + const f = suite.file ?? file; + for (const spec of suite.specs ?? []) { + for (const t of spec.tests ?? []) { + const annotations = [...(t.annotations ?? []), ...(t.results ?? []).flatMap((r: any) => r.annotations ?? [])]; + const id = annotations.find((a: any) => a.type === 'caseId')?.description ?? null; + out.push({ test: `${f} › ${spec.title}`, caseId: id }); + } + } + for (const s of suite.suites ?? []) walk(s, f); + }; + for (const s of report.suites ?? []) walk(s); + return out; +} + /** Groups cleanup failures by operation and status: "DELETE /brands/{brandId} → 403: 13 record(s)". */ export function cleanupSummary(failures: CleanupFailure[]): string[] { const groups = new Map(); diff --git a/src/generate/graph.ts b/src/generate/graph.ts index 3506823..8becfcc 100644 --- a/src/generate/graph.ts +++ b/src/generate/graph.ts @@ -19,6 +19,10 @@ export interface CrudChain { source: string; /** Body fields of create taken from existing data at run time (deps file "fill"), never created by the test. */ fill?: FillRule[]; + /** Create body fields a reviewed deps file names as unique: the same values twice must give the documented 409. */ + conflictOn?: string[]; + /** Create body fields the create response returns unchanged (a reviewed mapping): asserted in the create test. */ + echoes?: string[]; } export interface FillRule { @@ -46,6 +50,10 @@ export interface DepsFile { delete?: string; /** field → where its value comes from at run time: { "product_id": { "from": "getProducts", "pointer": "/data/0/id" } } */ fill?: Record; + /** Fields whose repeated values make create answer 409 (a reviewed business rule). */ + conflictOn?: string[]; + /** Fields the create response returns as sent. */ + echoes?: string[]; }[]; } @@ -69,6 +77,8 @@ export function findChains(doc: OpenApiDoc, ops: Operation[], deps?: DepsFile): delete: s.delete ? byId.get(s.delete) : undefined, source: 'deps file (human-confirmed)', ...(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) } : {}), }); } diff --git a/src/generate/negative.ts b/src/generate/negative.ts index 4e297dd..45a11ae 100644 --- a/src/generate/negative.ts +++ b/src/generate/negative.ts @@ -1,5 +1,8 @@ import type { Operation } from '../types.js'; import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; +import type { ARRAY } from '../cases/ids.js'; +import { bodyCasesDetailed } from './body-cases.js'; +import type { ParamRequest } from './param-cases.js'; /** * Negative cases derived ONLY from what the spec states: @@ -12,23 +15,13 @@ export interface NegCase { source: string; data?: unknown; query?: Record; - /** What the case breaks, for its case ID: a top-level body field (null = the body root) or a query parameter, and the rule. */ - target?: { in: 'body' | 'query'; field: string | null; rule: string }; + /** 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 }; + /** Parameter cases: the whole request (valid parameters plus the one under test). */ + request?: ParamRequest; } -/** Derives the target from the source ("..", ".", "query.."). */ -function withTargets(cases: NegCase[], prefix: string, where: 'body' | 'query'): NegCase[] { - return cases.map((c) => { - const rest = c.source.startsWith(prefix + '.') ? c.source.slice(prefix.length + 1) : c.source; - const dot = rest.lastIndexOf('.'); - const rule = dot < 0 ? rest : rest.slice(dot + 1); - let field = dot < 0 ? null : rest.slice(0, dot); - if (where === 'body' && field === null && rule === 'required') field = c.title.match(/missing required field "(.*)"$/)?.[1] ?? null; - return { ...c, target: { in: where, field, rule } }; - }); -} -const MAX_CASES = 20; export function documentedRejections(op: Operation): { validation: string[]; notFound: boolean; unauthorized: boolean } { const codes = op.responses.map((r) => r.status.toUpperCase()); @@ -61,97 +54,11 @@ function wrongType(type: string): unknown { const typeOf = (s: any): string | undefined => (Array.isArray(s?.type) ? s.type.find((t: string) => t !== 'null') : s?.type); -/** Body cases: start from a VALID base payload and break exactly one rule per case. */ -export function bodyCases(doc: OpenApiDoc, rawSchema: any, base: Record, schemaName = 'body'): NegCase[] { - const schema = deref(doc, rawSchema); - if (!schema || typeOf(schema) !== 'object' && !schema.properties) return []; - const cases: NegCase[] = []; - const props: Record = schema.properties ?? {}; - const required: string[] = schema.required ?? []; - - for (const r of required) { - if (!(r in base)) continue; - const { [r]: _omit, ...rest } = base; - cases.push({ title: `missing required field "${r}"`, source: `${schemaName}.required`, data: rest }); - } - - for (const [name, raw] of Object.entries(props)) { - const p = deref(doc, raw); - if (!p || p.readOnly) continue; - const t = typeOf(p); - const at = `${schemaName}.${name}`; - const withValue = (v: unknown) => ({ ...base, [name]: v }); - - const wt = t ? wrongType(t) : undefined; - if (wt !== undefined) cases.push({ title: `"${name}" has wrong type (${t} expected)`, source: `${at}.type`, data: withValue(wt) }); - - if (t === 'string') { - if (typeof p.minLength === 'number' && p.minLength > 0) cases.push({ title: `"${name}" shorter than minLength ${p.minLength}`, source: `${at}.minLength`, data: withValue('x'.repeat(p.minLength - 1)) }); - if (typeof p.maxLength === 'number') cases.push({ title: `"${name}" longer than maxLength ${p.maxLength}`, source: `${at}.maxLength`, data: withValue('x'.repeat(p.maxLength + 1)) }); - } - if (t === 'number' || t === 'integer') { - if (typeof p.minimum === 'number') cases.push({ title: `"${name}" below minimum ${p.minimum}`, source: `${at}.minimum`, data: withValue(p.minimum - 1) }); - if (typeof p.maximum === 'number') cases.push({ title: `"${name}" above maximum ${p.maximum}`, source: `${at}.maximum`, data: withValue(p.maximum + 1) }); - } - if (Array.isArray(p.enum) && p.enum.length && t === 'string') { - cases.push({ title: `"${name}" not in enum`, source: `${at}.enum`, data: withValue('__not_in_enum__') }); - } - if ((t === 'number' || t === 'integer') && typeof p.exclusiveMinimum === 'number') { - cases.push({ title: `"${name}" violates exclusiveMinimum ${p.exclusiveMinimum}`, source: `${at}.exclusiveMinimum`, data: withValue(p.exclusiveMinimum) }); - } - if ((t === 'number' || t === 'integer') && typeof p.exclusiveMaximum === 'number') { - cases.push({ title: `"${name}" violates exclusiveMaximum ${p.exclusiveMaximum}`, source: `${at}.exclusiveMaximum`, data: withValue(p.exclusiveMaximum) }); - } - if (t === 'array' && typeof p.minItems === 'number' && p.minItems > 0) { - cases.push({ title: `"${name}" has fewer than minItems ${p.minItems}`, source: `${at}.minItems`, data: withValue([]) }); - } - if (t === 'array' && typeof p.maxItems === 'number') { - const item = deref(doc, p.items); - const sample = item?.example ?? (typeOf(item) === 'string' ? 'x' : typeOf(item) === 'number' || typeOf(item) === 'integer' ? 1 : undefined); - if (sample !== undefined) cases.push({ title: `"${name}" has more than maxItems ${p.maxItems}`, source: `${at}.maxItems`, data: withValue(Array.from({ length: p.maxItems + 1 }, () => sample)) }); - } - } - - if (schema.additionalProperties === false) { - cases.push({ title: 'unknown field is rejected (additionalProperties: false)', source: `${schemaName}.additionalProperties`, data: { ...base, unexpectedField: 'api-agent' } }); - } - if (typeof schema.minProperties === 'number' && schema.minProperties > 0) { - cases.push({ title: `empty object (minProperties ${schema.minProperties})`, source: `${schemaName}.minProperties`, data: {} }); - } - return withTargets(cases.slice(0, MAX_CASES), schemaName, 'body'); +/** Body cases: start from a VALID base payload and break exactly one rule per case, at any depth (see body-cases.ts). */ +export function bodyCases(doc: OpenApiDoc, rawSchema: any, base: Record, schemaName = "body", maxCases?: number): NegCase[] { + return bodyCasesDetailed(doc, rawSchema, base, schemaName, maxCases).cases; } -/** Query cases: break one documented query-parameter constraint per case. */ -export function queryCases(op: Operation): NegCase[] { - const cases: NegCase[] = []; - const query = op.params.filter((p) => p.in === 'query'); - const valid: Record = Object.fromEntries(query.filter((p) => p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); - - for (const p of query) { - const s = p.schema ?? {}; - const t = typeOf(s); - const at = `query.${p.name}`; - const withValue = (v: unknown) => ({ ...valid, [p.name]: v }); - if (p.required && p.name in valid) { - const { [p.name]: _omit, ...rest } = valid; - cases.push({ title: `missing required query "${p.name}"`, source: `${at}.required`, query: rest }); - } - if (t === 'integer' || t === 'number') { - cases.push({ title: `query "${p.name}" is not a number`, source: `${at}.type`, query: withValue('abc') }); - if (typeof s.minimum === 'number') cases.push({ title: `query "${p.name}" below minimum ${s.minimum}`, source: `${at}.minimum`, query: withValue(s.minimum - 1) }); - if (typeof s.maximum === 'number') cases.push({ title: `query "${p.name}" above maximum ${s.maximum}`, source: `${at}.maximum`, query: withValue(s.maximum + 1) }); - } - if (t === 'integer' || t === 'number') { - if (typeof s.exclusiveMinimum === 'number') cases.push({ title: `query "${p.name}" violates exclusiveMinimum ${s.exclusiveMinimum}`, source: `${at}.exclusiveMinimum`, query: withValue(s.exclusiveMinimum) }); - if (typeof s.exclusiveMaximum === 'number') cases.push({ title: `query "${p.name}" violates exclusiveMaximum ${s.exclusiveMaximum}`, source: `${at}.exclusiveMaximum`, query: withValue(s.exclusiveMaximum) }); - } - if (t === 'string' && typeof s.minLength === 'number' && s.minLength > 0) cases.push({ title: `query "${p.name}" shorter than minLength ${s.minLength}`, source: `${at}.minLength`, query: withValue('x'.repeat(s.minLength - 1)) }); - if (t === 'boolean') cases.push({ title: `query "${p.name}" is not a boolean`, source: `${at}.type`, query: withValue('not-a-boolean') }); - if (t === 'string' && Array.isArray(s.enum) && s.enum.length) cases.push({ title: `query "${p.name}" not in enum`, source: `${at}.enum`, query: withValue('__not_in_enum__') }); - if (t === 'string' && typeof s.maxLength === 'number') cases.push({ title: `query "${p.name}" longer than maxLength ${s.maxLength}`, source: `${at}.maxLength`, query: withValue('x'.repeat(s.maxLength + 1)) }); - } - return withTargets(cases.slice(0, MAX_CASES), 'query', 'query'); -} /** A runtime expression (TypeScript source) for an id that should not exist, matching the param's schema. */ export function nonexistentIdExpr(schema: any): string { diff --git a/src/generate/param-cases.ts b/src/generate/param-cases.ts new file mode 100644 index 0000000..94d9522 --- /dev/null +++ b/src/generate/param-cases.ts @@ -0,0 +1,180 @@ +import type { OpenApiDoc } from '../spec/loader.js'; +import type { Operation, ParamInfo } from '../types.js'; +import { location } from '../cases/ids.js'; +import { bodyCasesDetailed, type CoverageGap } from './body-cases.js'; +import type { NegCase } from './negative.js'; +import { sampleFromSchema } from './sample.js'; + +/** + * Parameter negative cases for query, header, cookie and path (docs/SUPPORT_MATRIX.md, stage 4). + * Each case is a valid request (every required parameter with its documented value) with exactly one parameter + * breaking exactly one rule. The rules come from the same recursive engine as bodies; what does not make sense on the + * wire is dropped (a string parameter cannot have the wrong type, null cannot be sent), and what cannot be sent + * safely or serialized deterministically is a gap. + */ + +export type ParamIn = 'query' | 'header' | 'cookie' | 'path'; + +export interface ParamRequest { + /** Query as an object, or a serialized string when an array needs its documented style. */ + params?: Record | string; + headers?: Record; + /** Path parameter values by name (only the parameter under test; the others keep their documented values). */ + path?: Record; +} + +/** Headers the spec cannot define as parameters (OpenAPI ignores them) or that credentials own. */ +const RESERVED_HEADERS = new Set(['authorization', 'content-type', 'accept']); +const NUMERIC_RULES = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf']; + +export const sendable = (p: ParamInfo) => !(p.in === 'header' && RESERVED_HEADERS.has(p.name.toLowerCase())); + +/** Required query / header / cookie parameters with their documented values: the valid part of every request. */ +export function requiredRequest(op: Operation): { params: Record; headers: Record; missing: ParamInfo[] } { + const params: Record = {}; + const cookies: string[] = []; + const headers: Record = {}; + const missing: ParamInfo[] = []; + for (const p of op.params.filter((x) => x.required && x.in !== 'path' && sendable(x))) { + if (p.knownValue === undefined || (typeof p.knownValue === 'object' && p.knownValue !== null)) { + missing.push(p); + continue; + } + const v = p.knownValue as string | number | boolean; + if (p.in === 'query') params[p.name] = v; + else if (p.in === 'header') headers[p.name] = String(v); + else if (p.in === 'cookie') cookies.push(`${p.name}=${String(v)}`); + } + if (cookies.length) headers.Cookie = cookies.join('; '); + return { params, headers, missing }; +} + +/** OpenAPI serialization of a query array: form (explode: true → repeated keys, false → comma), spaceDelimited, pipeDelimited. */ +function serializeQuery(p: ParamInfo & { style?: string; explode?: boolean }, value: unknown, rest: Record): string | undefined { + const parts = Object.entries(rest).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`); + if (!Array.isArray(value)) return undefined; + if (value.some((v) => v !== null && typeof v === 'object')) return undefined; + const style = p.style ?? 'form'; + const explode = p.explode ?? style === 'form'; + const name = encodeURIComponent(p.name); + if (style === 'form' && explode) parts.push(...value.map((v) => `${name}=${encodeURIComponent(String(v))}`)); + else if (style === 'form') parts.push(`${name}=${value.map((v) => encodeURIComponent(String(v))).join(',')}`); + else if (style === 'spaceDelimited' && !explode) parts.push(`${name}=${value.map((v) => encodeURIComponent(String(v))).join('%20')}`); + else if (style === 'pipeDelimited' && !explode) parts.push(`${name}=${value.map((v) => encodeURIComponent(String(v))).join('|')}`); + else return undefined; + return parts.join('&'); +} + +const locOf = (where: ParamIn, name: string) => + where === 'query' ? location.query(name) : where === 'header' ? location.header(name) : where === 'cookie' ? location.cookie(name) : location.path(name); + +export function paramCasesDetailed(doc: OpenApiDoc, op: Operation, opts: { allowPath: boolean; allowOthers: boolean }): { cases: (NegCase & { request: ParamRequest })[]; gaps: CoverageGap[] } { + const cases: (NegCase & { request: ParamRequest })[] = []; + const gaps: CoverageGap[] = []; + const base = requiredRequest(op); + if (base.missing.length) { + for (const p of base.missing) gaps.push({ code: 'MISSING_VALID_SAMPLE', location: locOf(p.in as ParamIn, p.name), reason: `required ${p.in} "${p.name}" has no documented value, so no valid request can be built` }); + return { cases, gaps }; + } + const isWrite = !['get', 'head', 'options'].includes(op.method); + for (const p of op.params.filter(sendable) as (ParamInfo & { style?: string; explode?: boolean })[]) { + const where = p.in as ParamIn; + const loc = locOf(where, p.name); + const s = p.schema ?? {}; + if (where === 'path' ? !opts.allowPath : !opts.allowOthers) continue; + if (where === 'path' && op.params.some((x) => x.in === 'path' && x !== p && x.knownValue === undefined)) { + gaps.push({ code: 'MISSING_RESOURCE_SOURCE', location: loc, reason: 'another path parameter has no documented value' }); + continue; + } + // A valid value of the parameter under test to start from. + let value: unknown = p.knownValue; + if (value === undefined) { + const sample = sampleFromSchema(doc, s); + if (sample.ok) value = sample.value; + } + if (value === undefined) { + // A scalar optional parameter is not sent in the valid request; its cases set the violating value directly, + // so a placeholder is enough. Arrays need a real element to start from. + const scalar = !['array', 'object'].includes(Array.isArray(s.type) ? s.type.find((x: string) => x !== 'null') : s.type); + if (scalar && !p.required) value = null; + else { + gaps.push({ code: 'MISSING_VALID_SAMPLE', location: loc, reason: `${where} "${p.name}" has no documented or derivable valid value` }); + continue; + } + } + const required = p.required && where !== 'path'; + const holder = { type: 'object', properties: { [p.name]: s }, ...(required ? { required: [p.name] } : {}) }; + const r = bodyCasesDetailed(doc, holder, { [p.name]: value }, where, 1000); + const t = Array.isArray(s.type) ? s.type.find((x: string) => x !== 'null') : s.type; + for (const g of r.gaps) if (g.location !== 'request.body#') gaps.push({ ...g, location: loc }); + for (const c of r.cases) { + const tgt = c.target as { path: (string | symbol)[]; rule: string }; + const rule = tgt.rule; + // On the wire every value is text: a string parameter cannot have a wrong type, null cannot be sent, + // and a single value is a valid one-element array. + if (rule === 'nullable' || (rule === 'type' && (t === 'string' || t === 'array' || t === undefined))) continue; + if (tgt.path.length > 1) { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: `constraints of array items / object members in a ${where} parameter are not derived` }); + continue; + } + if (where === 'path' && isWrite && NUMERIC_RULES.includes(rule)) { + gaps.push({ code: 'UNSAFE_LIVE_CHECK', location: loc, rule, reason: `an out-of-range id could address an existing record of ${op.key}` }); + continue; + } + const data = c.data as Record; + const missing = !(p.name in data); + const v = data[p.name]; + const request: ParamRequest = {}; + const params = { ...base.params }; + const headers = { ...base.headers }; + if (where === 'query') { + delete params[p.name]; + if (missing) request.params = params; + else if (Array.isArray(v)) { + const q = serializeQuery(p, v, params); + if (q === undefined) { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: `style "${p.style ?? 'form'}" / explode ${p.explode ?? '(default)'} is not serialized` }); + continue; + } + request.params = q; + } else if (v !== null && typeof v === 'object') { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'object query parameters are not serialized' }); + continue; + } else request.params = { ...params, [p.name]: v as string | number | boolean }; + } else { + if (Object.keys(params).length) request.params = params; + if (where === 'header') { + for (const k of Object.keys(headers)) if (k.toLowerCase() === p.name.toLowerCase()) delete headers[k]; + if (!missing) { + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'object headers are not serialized' }); + continue; + } + headers[p.name] = Array.isArray(v) ? v.map(String).join(',') : String(v); // style: simple + } + } else if (where === 'cookie') { + const others = (headers.Cookie ?? '').split('; ').filter((x) => x && !x.startsWith(`${p.name}=`)); + if (!missing) { + if (v !== null && typeof v === 'object') { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'array / object cookies are not serialized' }); + continue; + } + others.push(`${p.name}=${String(v)}`); + } + if (others.length) headers.Cookie = others.join('; '); + else delete headers.Cookie; + } else { + if (v !== null && typeof v === 'object') { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'array / object path parameters are not serialized' }); + continue; + } + request.path = { [p.name]: String(v) }; + } + } + 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 } }); + } + } + return { cases, gaps }; +} diff --git a/src/generate/python.ts b/src/generate/python.ts index 1f27baf..828cb5d 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -1,5 +1,8 @@ import type { Operation } from '../types.js'; -import { hasFill, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; +import { requiredRequest } from './param-cases.js'; +import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/dsl.js'; +import type { CrudChain } from './graph.js'; +import { hasFill, queryVariants, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; /** * pytest + requests output. Same cases and safety rules as the TypeScript templates; @@ -51,6 +54,25 @@ function pathExpr(op: Operation, chainParam?: string, idVar = 'resource_id'): st return `f${str(p)}`; } +/** Keyword arguments with the operation's required query / header / cookie parameters (documented values). */ +function pyRequired(op: Operation, skip: ('params' | 'headers')[] = []): string { + const r = requiredRequest(op); + return [ + Object.keys(r.params).length && !skip.includes('params') ? `, params=${pyLit(r.params, 4)}` : '', + Object.keys(r.headers).length && !skip.includes('headers') ? `, headers=${pyLit(r.headers, 4)}` : '', + ].join(''); +} + +/** Path whose parameters come from the row's "path" values, else their documented values. */ +function pathFromParts(op: Operation): string { + let p = op.path.replace(/^\//, '').replace(/[{}]/g, (c) => c + c); + for (const param of op.params.filter((x) => x.in === 'path')) { + const known = param.knownValue === undefined ? "'unused'" : `'${String(param.knownValue).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`; + p = p.replace(`{{${param.name}}}`, `{quote(str(path.get('${param.name}', ${known})), safe='')}`); + } + return `f${str(p)}`; +} + const header = (kind: string, op: Operation, meta: Meta, extra: string[]) => [ `"""${op.key} · ${kind} cases. Generated by api-test-agent ${meta.version}.`, @@ -234,6 +256,17 @@ def pytest_configure(config): config.addinivalue_line("markers", "api_case_id(id): stable case ID from _support/cases.json") +def pytest_collection_modifyitems(config, items): + # api-test-agent sets API_AGENT_CASES_OUT to check that every collected test has its own case ID. + out = os.environ.get("API_AGENT_CASES_OUT") + if not out: + return + with open(out, "w", encoding="utf-8") as f: + for item in items: + mark = item.get_closest_marker("api_case_id") + f.write(json.dumps({"test": item.nodeid, "caseId": mark.args[0] if mark else None}) + "\\n") + + class ApiClient(requests.Session): """requests.Session with a base URL, JSON accept header and a default timeout.""" @@ -328,7 +361,7 @@ function pyHeader(suite: SuiteType, s: SuiteInput, meta: Meta, extra: string[]): const lines = [...extra]; if (s.plan) lines.unshift(`Preconditions and cleanup: ${s.plan.chain.source}`); lines.push('Polarity is a marker: run one side with -m positive or -m negative.'); - return [header(suite, s.op, meta, lines), 'import uuid # noqa: F401', 'from urllib.parse import quote # noqa: F401', '', 'import pytest', '', 'from contract import read_pointer # noqa: F401', '', `pytestmark = pytest.mark.${suite}`, '', '']; + return [header(suite, s.op, meta, lines), 'import json # noqa: F401', 'import uuid # noqa: F401', 'from urllib.parse import quote # noqa: F401', '', 'import pytest', '', 'from contract import fill_vars, read_pointer, report_cleanup_failure # noqa: F401', '', `pytestmark = pytest.mark.${suite}`, '', '']; } /** The successful call with its precondition (fixtures) and cleanup; `assert` returns the assertion lines. */ @@ -339,16 +372,14 @@ function pyPositive(s: SuiteInput, name: string, assert: (indent: string) => str const role = roleOf(op, plan); const res = plan ? resourceModule(plan).replace(/_resource$/, '') : ''; if (!role) { - const query = Object.fromEntries(op.params.filter((p) => p.in === 'query' && p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); - const params = Object.keys(query).length ? `, params=${pyLit(query, 4)}` : ''; - return [POS, `def ${name}(api, contract):`, ` res = api.${op.method}(${pathExpr(op)}${params})`, ...assert(' '), '', '']; + return [POS, `def ${name}(api, contract):`, ` res = api.${op.method}(${pathExpr(op)}${pyRequired(op)})`, ...assert(' '), '', '']; } if (role === 'create') { - return [POS, `def ${name}(api, contract, ${res}):`, ` res = api.${op.method}(${pathExpr(op)}, json=${res}.new_create_payload())`, ' try:', ...assert(' '), ' finally:', ` ${res}.remove_if_created(res)`, '', '']; + return [POS, `def ${name}(api, contract, ${res}):`, ` payload = ${res}.new_create_payload()`, ` res = api.${op.method}(${pathExpr(op)}, json=payload${pyRequired(op)})`, ' try:', ...assert(' '), ' finally:', ` ${res}.remove_if_created(res)`, '', '']; } const body = role === 'update' ? `, json=${res}.new_update_payload()` : ''; // created_ removes the resource after the test (best effort: a deleted one is already gone). - return [POS, `def ${name}(api, contract, ${res}, created_${res}):`, ` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}${body})`, ...assert(' '), '', '']; + return [POS, `def ${name}(api, contract, ${res}, created_${res}):`, ` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}${body}${pyRequired(op)})`, ...assert(' '), '', '']; } const pyNotFoundId = (idExpr: string) => (idExpr === 'randomUUID()' ? 'str(uuid.uuid4())' : /^\d+$/.test(idExpr) ? `str(${idExpr})` : 'f"nonexistent-{uuid.uuid4().hex}"'); @@ -362,7 +393,7 @@ function pyNotFound(s: SuiteInput, name: string, mark: string, assert: string): mark, `def ${name}(api, contract${body ? `, ${res}` : ''}):`, ` missing_id = ${pyNotFoundId(s.notFound!.idExpr)}`, - ` res = api.${op.method}(${pathExpr(op, chain?.param ?? s.notFound!.param, 'missing_id')}${body ? `, json=${res}.new_update_payload()` : ''})`, + ` res = api.${op.method}(${pathExpr(op, chain?.param ?? s.notFound!.param, 'missing_id')}${body ? `, json=${res}.new_update_payload()` : ''}${pyRequired(op)})`, ` ${assert}`, '', '', @@ -370,7 +401,7 @@ function pyNotFound(s: SuiteInput, name: string, mark: string, assert: string): } function pyAnonymous(s: SuiteInput, name: string, mark: string, assert: string): string[] { - return [mark, `def ${name}(anonymous_api, contract):`, ` res = anonymous_api.${s.op.method}(${pathExpr(s.op, s.plan?.chain.param, '"unused"')})`, ` ${assert}`, '', '']; + return [mark, `def ${name}(anonymous_api, contract):`, ` res = anonymous_api.${s.op.method}(${pathExpr(s.op, s.plan?.chain.param, '"unused"')}${pyRequired(s.op)})`, ` ${assert}`, '', '']; } const statusIs = (op: Operation, code: string) => @@ -395,17 +426,133 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { L.push( ...pyPositive(s, names[role ?? 'none'], (i) => { const a = [`${i}${assertSuccess(op)}`]; - if (role === 'create') a.push(`${i}assert read_pointer(res.json(), ${ptr}) not in (None, ""), "identifier at $response.body#${plan!.chain.idPointer}"`); + if (role === 'create') { + a.push(`${i}assert read_pointer(res.json(), ${ptr}) not in (None, ""), "identifier at $response.body#${plan!.chain.idPointer}"`); + // Fields a reviewed deps file says the create response returns as sent. + for (const field of plan!.chain.echoes ?? []) a.push(`${i}assert read_pointer(res.json(), ${str('/' + field.replace(/~/g, '~0').replace(/\//g, '~1'))}) == payload[${str(field)}], ${str(`${field} returned as sent`)}`); + } if (role === 'read') a.push(`${i}assert str(read_pointer(res.json(), ${ptr})) == created_${res}, "same resource"`); return a; }, s.ids?.functional.success), ); } + // One physical test (and case ID) per documented query value, as in the TypeScript suite. + const variants = s.positive && !plan && op.method === 'get' ? queryVariants(op) : []; + if (variants.length) { + 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)}`, '', ''); + } if (s.notFound) L.push(...pyNotFound(s, 'test_returns_documented_404_for_unknown_id', withId(NEG, s.ids?.functional.notFound), statusIs(op, '404'))); if (s.unauthorized) L.push(...pyAnonymous(s, 'test_returns_documented_401_without_credentials', withId(NEG, s.ids?.functional.unauthorized), statusIs(op, '401'))); + L.push(...pyErrorTests(s)); return finish(L); } +/** Documented error responses with a safe trigger (stage 6), as in the TypeScript suite. */ +function pyErrorTests(s: SuiteInput): string[] { + const { op, plan } = s; + const e = s.errors; + if (!e) return []; + const req = requiredRequest(op); + const L: string[] = []; + if (e.invalidCredentials) { + const params = { ...req.params, ...e.invalidCredentials.params }; + const headers = { ...req.headers, ...e.invalidCredentials.headers }; + // anonymous_api carries no credentials of its own: only the invalid one is sent. + L.push( + withId(NEG, s.ids?.functional.invalidCredentials), + 'def test_returns_documented_401_for_invalid_credentials(anonymous_api):', + ` res = anonymous_api.${op.method}(${pathExpr(op, plan?.chain.param, '"unused"')}${Object.keys(params).length ? `, params=${pyLit(params, 4)}` : ''}, headers=${pyLit(headers, 4)})`, + ` ${statusIs(op, '401')}`, + '', + '', + ); + } + if (e.methodNotAllowed) { + const path = op.path.replace(/^\//, '').replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(String(op.params.find((p) => p.in === 'path' && p.name === name)?.knownValue ?? 'unused'))); + // GET is the only method that is safe to send to a route the spec does not define. + L.push(withId(NEG, s.ids?.functional.methodNotAllowed), 'def test_answers_documented_405_to_a_method_the_path_does_not_define(api):', ` res = api.get(${str(path)})`, ` ${statusIs(op, '405')}`, '', ''); + } + if (e.preconditionFailed && plan) { + const res = resourceModule(plan).replace(/_resource$/, ''); + const headers = { ...req.headers, [e.preconditionFailed.header]: e.preconditionFailed.value }; + const data = plan.chain.update === op ? `, json=${res}.new_update_payload()` : ''; + const params = Object.keys(req.params).length ? `, params=${pyLit(req.params, 4)}` : ''; + L.push( + withId(NEG, s.ids?.functional.preconditionFailed), + `def test_returns_documented_412_when_precondition_does_not_match(api, ${res}, created_${res}):`, + ` res = api.${op.method}(${pathExpr(op, plan.chain.param, `created_${res}`)}${data}${params}, headers=${pyLit(headers, 4)})`, + ` ${statusIs(op, '412')}`, + '', + '', + ); + } + return L; +} + +/** A reviewed business scenario: steps in order, saved values, expected statuses; cleanup steps in finally. */ +function pyBusinessTest(s: SuiteInput, sc: ResolvedScenario, id?: string): string[] { + const L: string[] = [withId(sc.polarity === 'positive' ? POS : NEG, id), `def test_${pyName(sc.id)}(api):`, ` """${sc.title.replace(/"/g, "'")}"""`, ' saved = {}']; + const callOf = (st: ResolvedStep) => { + // Concatenation, not an f-string: the values are string literals, which an f-string expression cannot + // hold with escapes before Python 3.12. + const parts = st.op.path.replace(/^\//, '').split(/(\{[^}]+\})/).filter((x) => x !== ''); + const p = parts + .map((part) => { + const m = part.match(/^\{(.+)\}$/); + if (!m) return str(part); + const given = st.params?.[m[1]]; + const known = st.op.params.find((x) => x.in === 'path' && x.name === m[1])?.knownValue; + return `quote(str(${given !== undefined ? `fill_vars(${pyLit(given)}, saved)` : str(String(known))}), safe='')`; + }) + .join(' + '); + const req = requiredRequest(st.op); + const query = Object.fromEntries(Object.entries(st.params ?? {}).filter(([k]) => st.op.params.some((x) => x.in === 'query' && x.name === k))); + const args = [ + Object.keys(query).length || Object.keys(req.params).length ? `params={**${pyLit(req.params)}, **fill_vars(${pyLit(query)}, saved)}` : '', + st.body !== undefined ? `json=fill_vars(${pyLit(st.body)}, saved)` : '', + Object.keys(req.headers).length ? `headers=${pyLit(req.headers)}` : '', + ].filter(Boolean); + return `api.${st.op.method}(${p}${args.length ? ', ' + args.join(', ') : ''})`; + }; + const main = sc.steps.filter((st) => st.phase !== 'cleanup'); + const cleanup = sc.steps.filter((st) => st.phase === 'cleanup'); + L.push(' try:'); + main.forEach((st, j) => { + L.push(` # ${st.phase}${st.name ? ` ${st.name}` : ''}: ${st.op.key}`, ` res${j} = ${callOf(st)}`); + if (st.expect) { + const e = String(st.expect).toUpperCase(); + const cond = /^\dXX$/.test(e) ? `str(res${j}.status_code)[0] == "${e[0]}"` : `res${j}.status_code == ${e}`; + L.push(` assert ${cond}, f"CONTRACT_MISMATCH ${st.op.method.toUpperCase()} ${st.op.path.replace(/[{}]/g, (c) => c + c)}: expected ${e}, got {res${j}.status_code}"`); + } + if (Object.keys(st.save ?? {}).length) { + L.push(` body${j} = res${j}.json() if res${j}.content else None`); + for (const [name, ptr] of Object.entries(st.save ?? {})) L.push(` saved[${str(name)}] = read_pointer(body${j}, ${str(ptr)})`); + } + }); + if (!main.length) L.push(' pass'); + L.push(' finally:'); + if (!cleanup.length) L.push(' pass'); + cleanup.forEach((st, j) => { + const needs = varsIn([st.params, st.body]); + const guard = needs.length ? needs.map((v) => `saved.get(${str(v)}) is not None`).join(' and ') : 'True'; + L.push( + ` if ${guard}:`, + ' try:', + ` clean${j} = ${callOf(st)}`, + ' except Exception: # noqa: BLE001 - cleanup must not hide the real failure', + ` clean${j} = None`, + ` if clean${j} is None or (not clean${j}.ok and clean${j}.status_code != 404):`, + ` report_cleanup_failure(${str(st.op.key)}, str(${needs.length ? `saved.get(${str(needs[0])})` : '""'}), clean${j}.status_code if clean${j} is not None else "no response")`, + ); + }); + L.push('', ''); + return L; +} + /** test_contract.py: responses match OpenAPI; invalid requests are rejected as documented. */ export function renderPyContract(s: SuiteInput, meta: Meta): string { const { op, plan } = s; @@ -415,7 +562,7 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { const needsExisting = !!chain && chain.create !== op && op.params.some((p) => p.in === 'path' && p.name === chain.param); const expect = `contract.expect(res, ${str(op.method)}, ${str(op.path)})`; const L = pyHeader('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.']); - if (s.bodyCases.length || s.queryCases.length) L.push(`REJECTION = ${pyLit(s.validation)} # documented in the spec`, '', ''); + if (s.bodyCases.length || s.paramCases.length) L.push(`REJECTION = ${pyLit(s.validation)} # documented in the spec`, '', ''); if (s.positive) L.push(...pyPositive(s, 'test_success_response_matches_contract', (i) => [`${i}${expect}`], s.ids?.contract.success)); if (s.notFound) L.push(...pyNotFound(s, 'test_response_for_unknown_id_matches_contract', withId(POS, s.ids?.contract.notFound), expect)); if (s.unauthorized) L.push(...pyAnonymous(s, 'test_response_without_credentials_matches_contract', withId(POS, s.ids?.contract.unauthorized), expect)); @@ -426,19 +573,38 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { L.push(']', '', '', NEG, '@pytest.mark.parametrize("payload", INVALID_BODIES)'); if (needsExisting) { L.push(`def test_rejects_invalid_body(api, contract, created_${res}, payload):`); - L.push(` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}, json=payload)`); + L.push(` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}, json=payload${pyRequired(op)})`); } else { L.push(`def test_rejects_invalid_body(api, contract${isCreate ? `, ${res}` : ''}, payload):`); - L.push(` res = api.${op.method}(${pathExpr(op, chain?.param)}, json=payload)`); + L.push(` res = api.${op.method}(${pathExpr(op, chain?.param)}, json=payload${pyRequired(op)})`); if (isCreate) L.push(` ${res}.remove_if_created(res)`); } L.push(` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, '', ''); } - if (s.queryCases.length) { - L.push('INVALID_QUERIES = ['); - s.queryCases.forEach((c, n) => L.push(` pytest.param(${pyLit(c.query, 4)}, id=${str(c.title)}${paramMarks(s.ids?.contract.query[n])}), # ${c.source}`)); - L.push(']', '', '', NEG, '@pytest.mark.parametrize("params", INVALID_QUERIES)', 'def test_rejects_invalid_query(api, contract, params):'); - L.push(` res = api.${op.method}(${pathExpr(op)}, params=params)`, ` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, '', ''); + if (s.paramCases.length) { + // Each row is a whole request: the valid required parameters plus the one parameter under test. + 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)); + 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(' 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)})`, '', ''); + } + if (s.errors?.unsupportedMediaType && chain) { + // 415: the documented body, but declared as text/plain. Anything the API wrongly creates is removed. + const req = requiredRequest(op); + const headers = pyLit({ ...req.headers, 'content-type': 'text/plain' }, 4); + const params = Object.keys(req.params).length ? `, params=${pyLit(req.params, 4)}` : ''; + L.push(withId(NEG, s.ids?.contract.unsupportedMediaType)); + if (isCreate) { + L.push(`def test_rejects_a_body_sent_as_text_plain(api, contract, ${res}):`, ` res = api.${op.method}(${pathExpr(op)}, data=json.dumps(${res}.new_create_payload())${params}, headers=${headers})`, ` ${res}.remove_if_created(res)`); + } else { + L.push(`def test_rejects_a_body_sent_as_text_plain(api, contract, ${res}, created_${res}):`, ` res = api.${op.method}(${pathExpr(op, chain.param, `created_${res}`)}, data=json.dumps(${res}.new_update_payload())${params}, headers=${headers})`); + } + L.push(` contract.expect_rejected(res, ["415"], ${str(op.method)}, ${str(op.path)})`, '', ''); } return finish(L); } @@ -446,14 +612,50 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { /** test_scenarios.py: multi-request flows whose primary (action under test) is this operation. */ export function renderPyScenarios(s: SuiteInput, meta: Meta): string { const { op, plan } = s; - const chain = plan!.chain; - const r = chain.read!; - const res = resourceModule(plan!).replace(/_resource$/, ''); + // CRUD flows need the confirmed chain; reviewed business scenarios (--scenarios) do not. + const chain = plan?.chain as CrudChain; + const r = chain?.read as Operation; + const res = plan ? resourceModule(plan).replace(/_resource$/, '') : ''; const sc = scenarioCases(s); - const extra = ['Each scenario: setup (create) → action (this operation) → assertion (read) → cleanup (delete).']; + const business = s.business ?? []; + const extra = plan ? ['Each scenario: setup (create) → action (this operation) → assertion (read) → cleanup (delete).'] : []; + if (business.length) extra.push('Business scenarios come from the reviewed scenarios file: steps, expected statuses and cleanup as written there.'); if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = pyHeader('scenario', s, meta, extra); const id = `created_${res}`; + if (sc.deleteTwice) { + // A repeated delete of the same resource gets the documented 404. + L.push( + withId(NEG, s.ids?.scenario.deleteTwice), + `def test_deleting_the_same_resource_again_gets_404(api, ${id}):`, + ` first = api.${op.method}(${pathExpr(op, chain.param, id)}${pyRequired(op)})`, + ` ${assertSuccess(op, 'first')}`, + ` res = api.${op.method}(${pathExpr(op, chain.param, id)}${pyRequired(op)})`, + ` ${statusIs(op, '404')}`, + '', + '', + ); + } + business.forEach((b, n) => L.push(...pyBusinessTest(s, b, s.ids?.scenario.business[n]))); + if (sc.conflict) { + // 409 on the fields a reviewed deps file names: the same payload twice. Both records are removed. + L.push( + withId(NEG, s.ids?.scenario.conflict), + `def test_second_create_with_the_same_fields_conflicts(api, ${res}):`, + ` payload = ${res}.new_create_payload()`, + ` first_id, _ = ${res}.create(payload)`, + ' try:', + ` res = api.${op.method}(${pathExpr(op)}, json=payload${pyRequired(op)})`, + ' try:', + ` ${statusIs(op, '409')}`, + ' finally:', + ` ${res}.remove_if_created(res)`, + ' finally:', + ` ${res}.remove(first_id)`, + '', + '', + ); + } if (sc.createRead) { L.push( withId(POS, s.ids?.scenario.createRead), diff --git a/src/generate/sample.ts b/src/generate/sample.ts index 6b4d20f..2cc8fff 100644 --- a/src/generate/sample.ts +++ b/src/generate/sample.ts @@ -49,7 +49,8 @@ export function sampleFromSchema(doc: OpenApiDoc, schema: any, path = '$', depth const alt = schema.oneOf ?? schema.anyOf; if (Array.isArray(alt)) { if (schema.discriminator) return { ok: false, reason: `${path}: polymorphic body with discriminator, choose the variant explicitly` }; - return sampleFromSchema(doc, alt[0], `${path}(variant 0)`, depth + 1); + // The first variant is used; the others are not silently dropped: the source names how many stay uncovered. + return sampleFromSchema(doc, alt[0], `${path}(variant 0 of ${alt.length})`, depth + 1); } const type = Array.isArray(schema.type) ? schema.type.find((t: string) => t !== 'null') : schema.type ?? (schema.properties ? 'object' : undefined); @@ -80,7 +81,20 @@ export function sampleFromSchema(doc: OpenApiDoc, schema: any, path = '$', depth const min = schema.minItems ?? 0; if (!min) return { ok: true, value: [], sources: [`${path}: empty array (no minItems)`] }; const r = sampleFromSchema(doc, schema.items, `${path}[]`, depth + 1); - return r.ok ? { ok: true, value: Array.from({ length: min }, () => r.value), sources: r.sources } : r; + if (!r.ok) return r; + if (!schema.uniqueItems || min < 2) return { ok: true, value: Array.from({ length: min }, () => r.value), sources: r.sources }; + // uniqueItems: distinct elements, derived only where it cannot break the item's own constraints. + const item = schema.items?.$ref ? resolvePointer(doc, schema.items.$ref.slice(1)).node : schema.items; + const values: unknown[] = []; + if (Array.isArray(item?.enum) && item.enum.length >= min) values.push(...item.enum.slice(0, min)); + else if (typeof r.value === 'string' && !item?.pattern && !item?.format && !item?.enum && (item?.maxLength ?? Infinity) >= String(r.value).length + 3) { + for (let i = 0; i < min; i++) values.push(i ? `${r.value}-${i}` : r.value); + } else if (typeof r.value === 'number' && !item?.enum) { + const step = typeof item?.multipleOf === 'number' ? item.multipleOf : 1; + for (let i = 0; i < min; i++) values.push((r.value as number) + i * step); + if (typeof item?.maximum === 'number' && (values[min - 1] as number) > item.maximum) return { ok: false, reason: `${path}: ${min} unique items do not fit under maximum ${item.maximum}` }; + } else return { ok: false, reason: `${path}: cannot derive ${min} distinct items (uniqueItems)` }; + return { ok: true, value: values, sources: [...r.sources, `${path}: ${min} distinct items (uniqueItems)`] }; } case 'string': { if (schema.format && FORMAT_VALUES[schema.format] !== undefined) return { ok: true, value: FORMAT_VALUES[schema.format], sources: [`${path}: format ${schema.format}`] }; @@ -93,10 +107,17 @@ export function sampleFromSchema(doc: OpenApiDoc, schema: any, path = '$', depth } case 'integer': case 'number': { - const lo = schema.minimum ?? (schema.exclusiveMinimum !== undefined ? Number(schema.exclusiveMinimum) + 1 : 1); - const hi = schema.maximum ?? Infinity; - if (lo > hi) return { ok: false, reason: `${path}: minimum > maximum` }; - return { ok: true, value: type === 'integer' ? Math.ceil(lo) : lo, sources: [`${path}: minimal number`] }; + // 3.1: exclusiveMinimum is a number; 3.0: a boolean that makes the minimum itself invalid. + const bounds = [ + ...(typeof schema.minimum === 'number' ? [schema.minimum + (schema.exclusiveMinimum === true ? 1 : 0)] : []), + ...(typeof schema.exclusiveMinimum === 'number' ? [schema.exclusiveMinimum + 1] : []), + ]; + let lo = bounds.length ? Math.max(...bounds) : 1; + if (type === 'integer') lo = Math.ceil(lo); + if (typeof schema.multipleOf === 'number' && schema.multipleOf > 0) lo = Math.ceil(lo / schema.multipleOf - 1e-9) * schema.multipleOf; + const hi = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum - Number.EPSILON : schema.exclusiveMaximum === true ? schema.maximum - Number.EPSILON : schema.maximum ?? Infinity; + if (lo > hi) return { ok: false, reason: `${path}: no ${type} satisfies the bounds${schema.multipleOf ? ` and multipleOf ${schema.multipleOf}` : ''}` }; + return { ok: true, value: lo, sources: [`${path}: minimal ${type}${schema.multipleOf ? ` (multiple of ${schema.multipleOf})` : ''}`] }; } case 'boolean': return { ok: true, value: false, sources: [`${path}: boolean false`] }; diff --git a/src/generate/templates.ts b/src/generate/templates.ts index bd7aaa6..3ca0eb3 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -3,6 +3,10 @@ import type { CrudChain } from './graph.js'; import type { NegCase } from './negative.js'; import { apiCall, type ApiRef } from './api-objects.js'; import type { SuiteCaseIds } from '../cases/assign.js'; +import { requiredRequest, type ParamRequest } from './param-cases.js'; +import type { ErrorPlan } from './error-cases.js'; +import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/dsl.js'; +import { boundaryValues } from './boundaries.js'; /** Payloads and assumptions for one confirmed resource chain. */ export interface ChainPlan { @@ -54,18 +58,35 @@ function expectSuccess(op: Operation, v = 'res') { } function requiredQuery(op: Operation): Record { - return Object.fromEntries(op.params.filter((p) => p.in === 'query' && p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); + return requiredRequest(op).params; } -/** Safe query variations: only values explicitly allowed by the schema. */ +/** + * Request options with the operation's required query / header / cookie parameters (documented values) merged in. + * `inner` is an options literal such as "{ data: c.data }"; its own params / headers win. + */ +export function optionsWith(op: Operation, inner?: string): string | undefined { + const req = requiredRequest(op); + const body = inner ? inner.trim().replace(/^\{\s*/, '').replace(/\s*\}$/, '') : ''; + const fields: string[] = []; + if (Object.keys(req.params).length && !/\bparams:/.test(body)) fields.push(`params: ${JSON.stringify(req.params)}`); + if (Object.keys(req.headers).length && !/\bheaders:/.test(body)) fields.push(`headers: ${JSON.stringify(req.headers)}`); + if (body) fields.push(body); + return fields.length ? `{ ${fields.join(', ')} }` : 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) => { - const schema = p.schema ?? {}; - const values = Array.isArray(schema.enum) ? schema.enum : []; - return values.filter((v): v is string | number | boolean => - typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' - ).slice(0, 5).map((value) => ({ name: p.name, value })); + const schema: any = p.schema ?? {}; + const values: unknown[] = Array.isArray(schema.enum) ? [...schema.enum] : []; + // Boundary-valid values: the documented limits themselves must be accepted. + if (!values.length) values.push(...boundaryValues(schema)); + 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); } @@ -198,11 +219,15 @@ export interface SuiteInput { positive: boolean; // a successful call can be sent safely validation: string[]; // documented validation rejections: 400 / 422 / 4XX bodyCases: NegCase[]; - queryCases: NegCase[]; + paramCases: NegCase[]; notFound?: { idExpr: string; param: string }; unauthorized: boolean; /** Stable case IDs of this operation's tests (Playwright annotation caseId, pytest marker api_case_id). */ ids?: SuiteCaseIds; + /** Documented error responses with a safe trigger (stage 6). */ + errors?: ErrorPlan; + /** Reviewed business scenarios whose primary step is this operation (stage 8). */ + business?: ResolvedScenario[]; } export type Role = 'create' | 'read' | 'update' | 'delete'; @@ -214,10 +239,12 @@ export function roleOf(op: Operation, plan?: ChainPlan): Role | undefined { } /** Multi-request scenarios whose primary operation is `op` (the action under test, never the setup step). */ -export function scenarioCases(s: Pick): { createRead: boolean; updateRead: boolean; deleteGone: boolean } { +export function scenarioCases(s: Pick): { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict: boolean; deleteTwice: boolean } { const role = roleOf(s.op, s.plan); const read = s.plan?.chain.read; return { + deleteTwice: s.positive && role === 'delete' && s.op.responses.some((r) => r.status === '404'), + conflict: s.positive && role === 'create' && !!s.errors?.conflict, createRead: s.positive && role === 'create' && !!read, updateRead: s.positive && role === 'update' && !!read && s.plan!.updatePayload !== undefined, deleteGone: s.positive && role === 'delete' && !!read && read.responses.some((r) => r.status === '404'), @@ -228,10 +255,11 @@ export function scenarioCases(s: Pick): export function suiteCounts(s: SuiteInput): Record { const extra = (s.notFound ? 1 : 0) + (s.unauthorized ? 1 : 0); const sc = scenarioCases(s); + const e = s.errors; return { - functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0), - contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.queryCases.length, - scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0), + functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0) + (e?.invalidCredentials ? 1 : 0) + (e?.methodNotAllowed ? 1 : 0) + (e?.preconditionFailed && s.plan ? 1 : 0), + contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length + (e?.unsupportedMediaType && s.plan ? 1 : 0), + scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0) + (sc.conflict ? 1 : 0) + (sc.deleteTwice ? 1 : 0) + (s.business?.length ?? 0), }; } @@ -260,10 +288,9 @@ function positiveTest(s: SuiteInput, title: string, assert: (indent: string) => const chain = plan?.chain; const role = roleOf(op, plan); const ref = refs.get(op)!; - const call = (idVar?: string, options?: string) => apiCall(ref, 'api', pathArgs(op, ref, chain?.param, idVar), options); + const call = (idVar?: string, options?: string) => apiCall(ref, 'api', pathArgs(op, ref, chain?.param, idVar), optionsWith(op, options)); if (!role) { - const query = requiredQuery(op); - const opts = Object.keys(query).length ? `{ params: ${JSON.stringify(query)} }` : undefined; + const opts = optionsWith(op); const fx = apiFixture(op); return [ ` test(${q(title)}, ${POS}, async ({ ${fx} }) => {`, @@ -275,7 +302,8 @@ function positiveTest(s: SuiteInput, title: string, assert: (indent: string) => if (role === 'create') { return [ ` test(${q(title)}, ${POS}, async ({ api }) => {`, - ` const res = await ${call('id', hasFill(plan) ? '{ data: await resource.newCreatePayload(api) }' : '{ data: resource.newCreatePayload() }')};`, + ` const payload = ${hasFill(plan) ? 'await resource.newCreatePayload(api)' : 'resource.newCreatePayload()'};`, + ` const res = await ${call('id', '{ data: payload }')};`, ` try {`, ...assert(' '), ` } finally {`, @@ -314,11 +342,11 @@ function notFoundCall(s: SuiteInput, fx: string): string[] { const ref = refs.get(op)!; const chain = plan?.chain; const body = plan?.updatePayload !== undefined && chain?.update === op ? `{ data: resource.newUpdatePayload() }` : undefined; - return [` const missingId = String(${s.notFound!.idExpr});`, ` const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param ?? s.notFound!.param, 'missingId'), body)};`]; + return [` const missingId = String(${s.notFound!.idExpr});`, ` const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param ?? s.notFound!.param, 'missingId'), optionsWith(op, body))};`]; } const anonymousCall = (s: SuiteInput) => { const ref = s.refs.get(s.op)!; - return ` const res = await ${apiCall(ref, 'publicApi', pathArgs(s.op, ref, s.plan?.chain.param, "'unused'"))};`; + return ` const res = await ${apiCall(ref, 'publicApi', pathArgs(s.op, ref, s.plan?.chain.param, "'unused'"), optionsWith(s.op))};`; }; const notFoundNeedsHelpers = (s: SuiteInput) => !!s.notFound && s.plan?.updatePayload !== undefined && s.plan.chain.update === s.op; @@ -328,8 +356,9 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { const chain = plan?.chain; const role = roleOf(op, plan); const fx = chain ? 'api' : apiFixture(op); - const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s); - const names = ['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized ? ['expectStatus'] : [])]; + const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan); + const errorStatus = !!(s.errors?.invalidCredentials || s.errors?.methodNotAllowed || s.errors?.preconditionFailed); + const names = ['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : [])]; const L = suiteHeader('functional', s, meta, ['Checks the behavior of the endpoint: status and result. The response schema is checked in contract.spec.ts.']); L.push(...imports(s, names, usesHelpers), '', `test.describe('${op.key} · functional', { tag: '@functional' }, () => {`); @@ -344,7 +373,11 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { L.push( ...positiveTest(s, titles[role ?? 'none'], (i) => { const a = [`${i}${expectSuccess(op)}`]; - if (role === 'create') a.push(`${i}const id = readPointer(await res.json().catch(() => undefined), ${q(chain!.idPointer)});`, `${i}expect(String(id ?? ''), 'identifier at $response.body#${chain!.idPointer}').not.toBe('');`); + if (role === 'create') { + a.push(`${i}const created = await res.json().catch(() => undefined);`, `${i}const id = readPointer(created, ${q(chain!.idPointer)});`, `${i}expect(String(id ?? ''), 'identifier at $response.body#${chain!.idPointer}').not.toBe('');`); + // Fields a reviewed deps file says the create response returns as sent. + for (const field of chain!.echoes ?? []) a.push(`${i}expect(readPointer(created, ${q('/' + field.replace(/~/g, '~0').replace(/\//g, '~1'))}), ${q(`${field} returned as sent`)}).toEqual((payload as Record)[${q(field)}]);`); + } if (role === 'read') a.push(`${i}expect(String(readPointer(await res.json().catch(() => undefined), ${q(chain!.idPointer)})), 'same resource').toBe(id);`); return a; }, s.ids?.functional.success), @@ -354,16 +387,16 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { if (s.positive && !plan && op.method === 'get') { const ref = s.refs.get(op)!; const base = requiredQuery(op); - for (const variant of queryVariants(op)) { + queryVariants(op).forEach((variant, n) => { const params = { ...base, [variant.name]: variant.value }; L.push( - ` test(${q(`accepts documented ${variant.name}=${String(variant.value)}`)}, ${testOptions('positive', s.ids?.functional.success)}, async ({ ${fx} }) => {`, - ` const res = await ${apiCall(ref, fx, pathArgs(op, ref), `{ params: ${JSON.stringify(params)} }`)};`, + ` 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)}`, ` });`, '', ); - } + }); } if (s.notFound) { L.push(` test('returns documented 404 for an id that does not exist', ${testOptions('negative', s.ids?.functional.notFound)}, async ({ ${fx} }) => {`, ...notFoundCall(s, fx), ` expectStatus(res, ['404'], '${op.method}', ${q(op.path)});`, ` });`, ''); @@ -372,9 +405,109 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { // publicApi sends no credentials at all (not even the project's static token). L.push(` test('returns documented 401 without credentials', ${testOptions('negative', s.ids?.functional.unauthorized)}, async ({ publicApi }) => {`, anonymousCall(s), ` expectStatus(res, ['401'], '${op.method}', ${q(op.path)});`, ` });`, ''); } + L.push(...errorTests(s)); return close(L); } +/** A reviewed business scenario: its steps in order, saved values, expected statuses; cleanup steps in finally. */ +function businessTest(s: SuiteInput, sc: ResolvedScenario, id?: string): string[] { + const L: string[] = []; + const pol = sc.polarity; + L.push(` test(${q(sc.title)}, ${testOptions(pol, id)}, async ({ api }) => {`, ` const vars: Record = {};`); + const callOf = (st: ResolvedStep, v: string, indent: string) => { + const ref = s.refs.get(st.op)!; + const req = requiredRequest(st.op); + const args = ref.pathParams.map((name) => { + const given = st.params?.[name]; + if (given !== undefined) return `String(fillVars(${JSON.stringify(given)}, vars))`; + return q(String(st.op.params.find((x) => x.in === 'path' && x.name === name)?.knownValue)); + }); + const query = Object.fromEntries(Object.entries(st.params ?? {}).filter(([k]) => st.op.params.some((x) => x.in === 'query' && x.name === k))); + const opts = [ + Object.keys(query).length || Object.keys(req.params).length ? `params: { ...${JSON.stringify(req.params)}, ...fillVars(${JSON.stringify(query)}, vars) }` : '', + Object.keys(req.headers).length ? `headers: ${JSON.stringify(req.headers)}` : '', + st.body !== undefined ? `data: fillVars(${JSON.stringify(st.body)}, vars)` : '', + ].filter(Boolean); + return `${indent}const ${v} = await ${apiCall(ref, 'api', args, opts.length ? `{ ${opts.join(', ')} }` : undefined)};`; + }; + const main = sc.steps.filter((st) => st.phase !== 'cleanup'); + const cleanup = sc.steps.filter((st) => st.phase === 'cleanup'); + L.push(` try {`); + main.forEach((st, j) => { + L.push(` // ${st.phase}${st.name ? ` ${st.name}` : ''}: ${st.op.key}`, callOf(st, `res${j}`, ' ')); + if (st.expect) L.push(` expectStatus(res${j}, [${q(String(st.expect))}], '${st.op.method}', ${q(st.op.path)});`); + if (Object.keys(st.save ?? {}).length) { + L.push(` const body${j} = await res${j}.json().catch(() => undefined);`); + for (const [name, ptr] of Object.entries(st.save ?? {})) L.push(` vars[${q(name)}] = readPointer(body${j}, ${q(ptr)});`); + } + }); + L.push(` } finally {`); + cleanup.forEach((st, j) => { + const needs = varsIn([st.params, st.body]); + const guard = needs.length ? needs.map((v) => `vars[${q(v)}] !== undefined`).join(' && ') : 'true'; + L.push( + ` if (${guard}) {`, + callOf(st, `clean${j}`, ' ').replace(/;$/, '.catch(() => undefined);'), + ` if (!clean${j} || (!clean${j}.ok() && clean${j}.status() !== 404)) reportCleanupFailure(${q(st.op.key)}, String(${needs.length ? `vars[${q(needs[0])}]` : "''"}), clean${j} ? clean${j}.status() : 'no response');`, + ` }`, + ); + }); + L.push(` }`, ` });`, ''); + return L; +} + +/** Documented error responses with a safe trigger (stage 6): invalid credentials, 405, 412. */ +function errorTests(s: SuiteInput): string[] { + const { op, plan } = s; + const e = s.errors; + if (!e) return []; + const ref = s.refs.get(op)!; + const req = requiredRequest(op); + const L: string[] = []; + if (e.invalidCredentials) { + const params = { ...req.params, ...e.invalidCredentials.params }; + const headers = { ...req.headers, ...e.invalidCredentials.headers }; + const opts = [Object.keys(params).length ? `params: ${JSON.stringify(params)}` : '', `headers: ${JSON.stringify(headers)}`].filter(Boolean).join(', '); + // publicApi carries no credentials of its own: only the invalid one is sent. + L.push( + ` test('returns documented 401 for invalid credentials', ${testOptions('negative', s.ids?.functional.invalidCredentials)}, async ({ publicApi }) => {`, + ` const res = await ${apiCall(ref, 'publicApi', pathArgs(op, ref, plan?.chain.param, "'unused'"), `{ ${opts} }`)};`, + ` expectStatus(res, ['401'], '${op.method}', ${q(op.path)});`, + ` });`, + '', + ); + } + if (e.methodNotAllowed) { + const path = op.path.replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(String(op.params.find((p) => p.in === 'path' && p.name === name)?.knownValue ?? 'unused'))); + // GET is the only method that is safe to send to a route the spec does not define. + L.push( + ` test('answers documented 405 to a method the path does not define (GET)', ${testOptions('negative', s.ids?.functional.methodNotAllowed)}, async ({ request }) => {`, + ` const res = await request.get(${q(path.replace(/^\//, ''))});`, + ` expectStatus(res, ['405'], '${op.method}', ${q(op.path)});`, + ` });`, + '', + ); + } + if (e.preconditionFailed && plan) { + const headers = { ...req.headers, [e.preconditionFailed.header]: e.preconditionFailed.value }; + const data = plan.chain.update === op ? ', data: resource.newUpdatePayload()' : ''; + const params = Object.keys(req.params).length ? `params: ${JSON.stringify(req.params)}, ` : ''; + L.push( + ` test('returns documented 412 when ${e.preconditionFailed.header} does not match', ${testOptions('negative', s.ids?.functional.preconditionFailed)}, async ({ api }) => {`, + ` const { id } = await resource.create(api);`, + ` try {`, + ` const res = await ${apiCall(ref, 'api', pathArgs(op, ref, plan.chain.param, 'id'), `{ ${params}headers: ${JSON.stringify(headers)}${data} }`)};`, + ` expectStatus(res, ['412'], '${op.method}', ${q(op.path)});`, + ` } finally {`, + ` await resource.remove(api, id);`, + ` }`, + ` });`, + '', + ); + } + return L; +} + const caseField = (id?: string) => (id ? `caseId: ${q(id)}, ` : ''); /** A data-driven test: the case ID comes from the row when every row has one. */ const loopOptions = (ids?: string[]) => (ids?.length && ids.every(Boolean) ? `{ tag: '@negative', annotation: { type: 'caseId', description: c.caseId } }` : NEG); @@ -387,14 +520,15 @@ export function renderContract(s: SuiteInput, meta: Meta): string { const ref = s.refs.get(op)!; const isCreate = chain?.create === op; const needsExisting = !!chain && chain.create !== op && op.params.some((p) => p.in === 'path' && p.name === chain.param); - const invalid = s.bodyCases.length + s.queryCases.length > 0; - const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || (s.bodyCases.length > 0 && !!chain && (isCreate || needsExisting)); + const wrongMedia = !!(s.errors?.unsupportedMediaType && chain); + const invalid = s.bodyCases.length + s.paramCases.length > 0 || wrongMedia; + 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 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 (invalid) L.push('', `const rejection = ${JSON.stringify(s.validation)}; // documented in the spec`); + if (s.bodyCases.length + s.paramCases.length > 0) L.push('', `const rejection = ${JSON.stringify(s.validation)}; // documented in the spec`); L.push('', `test.describe('${op.key} · contract', { tag: '@contract' }, () => {`); const contract = (i: string, v = 'res') => [`${i}await expectContract(${v}, '${op.method}', ${q(op.path)});`]; @@ -402,7 +536,7 @@ export function renderContract(s: SuiteInput, meta: Meta): string { if (s.notFound) L.push(` test('response for a missing id matches the documented contract', ${testOptions('positive', s.ids?.contract.notFound)}, async ({ ${fx} }) => {`, ...notFoundCall(s, fx), ...contract(' '), ` });`, ''); if (s.unauthorized) L.push(` test('response without credentials matches the documented contract', ${testOptions('positive', s.ids?.contract.unauthorized)}, async ({ publicApi }) => {`, anonymousCall(s), ...contract(' '), ` });`, ''); - const send = (indent: string, options: string) => `${indent}const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param, 'id'), options)};`; + const send = (indent: string, options: string) => `${indent}const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param, 'id'), optionsWith(op, options))};`; if (s.bodyCases.length) { L.push(` const invalidBodies = [`); s.bodyCases.forEach((c, n) => L.push(` { title: ${q(c.title)}, source: ${q(c.source)}, ${caseField(s.ids?.contract.body[n])}data: ${JSON.stringify(c.data)} },`)); @@ -417,11 +551,32 @@ export function renderContract(s: SuiteInput, meta: Meta): string { } L.push(` });`, ` }`, ''); } - if (s.queryCases.length) { - L.push(` const invalidQueries = [`); - s.queryCases.forEach((c, n) => L.push(` { title: ${q(c.title)}, source: ${q(c.source)}, ${caseField(s.ids?.contract.query[n])}params: ${JSON.stringify(c.query)} },`)); - L.push(` ];`, '', ` for (const c of invalidQueries) {`, ` test(\`rejects invalid query: \${c.title}\`, ${loopOptions(s.ids?.contract.query)}, async ({ ${fx} }) => {`); - L.push(` const res = await ${apiCall(ref, fx, pathArgs(op, ref), '{ params: c.params }')};`, ` await expectRejected(res, rejection, '${op.method}', ${q(op.path)});`, ` });`, ` }`, ''); + 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 }[] = [`); + 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(', '); + L.push(` { title: ${q(c.title)}, source: ${q(c.source)}, ${caseField(s.ids?.contract.params[n])}${fields} },`); + }); + const args = ref.pathParams.map((name) => { + const known = op.params.find((x) => x.in === 'path' && x.name === name)?.knownValue; + 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)});`, ` });`, ` }`, ''); + } + if (wrongMedia) { + // 415: the documented body, but declared as text/plain. Anything the API wrongly creates is removed. + const req = requiredRequest(op); + const headers = JSON.stringify({ ...req.headers, 'content-type': 'text/plain' }); + const params = Object.keys(req.params).length ? `params: ${JSON.stringify(req.params)}, ` : ''; + const payload = isCreate ? (hasFill(plan) ? 'await resource.newCreatePayload(api)' : 'resource.newCreatePayload()') : 'resource.newUpdatePayload()'; + const opts = `{ ${params}headers: ${headers}, data: JSON.stringify(${payload}) }`; + L.push(` test('rejects a body sent as text/plain with documented 415', ${testOptions('negative', s.ids?.contract.unsupportedMediaType)}, async ({ api }) => {`); + if (isCreate) L.push(` const res = await ${apiCall(ref, 'api', pathArgs(op, ref), opts)};`, ` await resource.removeIfCreated(api, res);`, ` await expectRejected(res, ['415'], '${op.method}', ${q(op.path)});`); + else L.push(` const { id } = await resource.create(api);`, ` try {`, ` const res = await ${apiCall(ref, 'api', pathArgs(op, ref, chain!.param, 'id'), opts)};`, ` await expectRejected(res, ['415'], '${op.method}', ${q(op.path)});`, ` } finally {`, ` await resource.remove(api, id);`, ` }`); + L.push(` });`, ''); } return close(L); } @@ -429,17 +584,60 @@ export function renderContract(s: SuiteInput, meta: Meta): string { /** scenarios.spec.ts: multi-request flows whose primary (action under test) is this operation. */ export function renderScenarios(s: SuiteInput, meta: Meta): string { const { op, refs, plan } = s; - const chain = plan!.chain; - const r = chain.read!; + // CRUD flows need the confirmed chain; reviewed business scenarios (--scenarios) do not. + const chain = plan?.chain as CrudChain; + const r = chain?.read as Operation; + const business = s.business ?? []; const sc = scenarioCases(s); const call = (o: Operation, options?: string) => { const ref = refs.get(o)!; return apiCall(ref, 'api', pathArgs(o, ref, chain.param, 'id'), options); }; - const extra = ['Each scenario: setup (create) → action (this operation) → assertion (read) → cleanup (delete).']; + const extra = plan ? ['Each scenario: setup (create) → action (this operation) → assertion (read) → cleanup (delete).'] : []; + if (business.length) extra.push('Business scenarios come from the reviewed scenarios file: steps, expected statuses and cleanup as written there.'); if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = suiteHeader('scenario', s, meta, extra); - L.push(...imports(s, ['expect', ...(sc.createRead ? ['readPointer'] : [])], true, false), '', `test.describe('${op.key} · scenarios', { tag: '@scenario' }, () => {`); + const names = ['expect', ...(sc.createRead || business.length ? ['readPointer'] : []), ...(sc.conflict || sc.deleteTwice || business.length ? ['expectStatus'] : []), ...(business.length ? ['fillVars', 'reportCleanupFailure'] : [])]; + L.push(...imports(s, names, !!plan, false), '', `test.describe('${op.key} · scenarios', { tag: '@scenario' }, () => {`); + if (sc.deleteTwice) { + // A repeated delete of the same resource gets the documented 404. + L.push( + ` test('deleting the same resource again gets the documented 404', ${testOptions('negative', s.ids?.scenario.deleteTwice)}, async ({ api }) => {`, + ` const { id } = await resource.create(api);`, + ` try {`, + ` const first = await ${call(op, optionsWith(op))};`, + ` ${expectSuccess(op, 'first')}`, + ` const res = await ${call(op, optionsWith(op))};`, + ` expectStatus(res, ['404'], '${op.method}', ${q(op.path)});`, + ` } finally {`, + ` await resource.remove(api, id);`, + ` }`, + ` });`, + '', + ); + } + if (sc.conflict) { + // 409 on the fields a reviewed deps file names: the same payload twice. Both records are removed. + const fields = s.errors!.conflict!.fields; + const payload = hasFill(plan) ? 'await resource.newCreatePayload(api)' : 'resource.newCreatePayload()'; + L.push( + ` test(${q(`a second create with the same ${fields.join(', ')} gets the documented 409`)}, ${testOptions('negative', s.ids?.scenario.conflict)}, async ({ api }) => {`, + ` const payload = ${payload};`, + ` const first = await resource.create(api, payload);`, + ` try {`, + ` const res = await ${call(op, optionsWith(op, '{ data: payload }'))};`, + ` try {`, + ` expectStatus(res, ['409'], '${op.method}', ${q(op.path)});`, + ` } finally {`, + ` await resource.removeIfCreated(api, res);`, + ` }`, + ` } finally {`, + ` await resource.remove(api, first.id);`, + ` }`, + ` });`, + '', + ); + } if (sc.createRead) { L.push( ` test('the created resource can be retrieved by ${r.operationId ?? r.key}', ${testOptions('positive', s.ids?.scenario.createRead)}, async ({ api }) => {`, @@ -491,6 +689,7 @@ export function renderScenarios(s: SuiteInput, meta: Meta): string { '', ); } + L.push(...business.flatMap((sc2, n) => businessTest(s, sc2, s.ids?.scenario.business[n]))); return close(L); } @@ -504,7 +703,7 @@ function close(L: string[]): string { export const CONTRACT_ASSERT = `// Generated by api-test-agent. Bridges Playwright responses to the OpenAPI contract. import { appendFileSync } from 'node:fs'; -import { expect, type APIResponse } from '@playwright/test'; +import { expect, test, type APIResponse } from '@playwright/test'; import { ContractValidator } from './contract.js'; import { spec } from './openapi.snapshot.js'; @@ -520,24 +719,28 @@ export function reportCleanupFailure(operation: string, id: string, status: numb else console.warn(\`cleanup failed: \${operation} \${id} → \${status} (test data left on the target)\`); } -async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown }> { +async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown; rawText: string }> { const contentType = res.headers()['content-type'] ?? null; - const text = await res.text(); - let body: unknown = text; + const rawText = await res.text(); + let body: unknown = rawText; if (contentType?.includes('json')) { try { - body = text.length ? JSON.parse(text) : null; + body = rawText.length ? JSON.parse(rawText) : null; } catch { body = undefined; } } - return { contentType, body }; + return { contentType, body, rawText }; } -/** Validates status, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. */ +/** + * Validates status, headers, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. + * What could not be checked (e.g. a media type without a schema) is added to the test report as a note. + */ export async function expectContract(res: APIResponse, method: string, path: string): Promise { - const { contentType, body } = await readBody(res); - const r = validator.validateResponse({ method, path, status: res.status(), contentType, body }); + const { contentType, body, rawText } = await readBody(res); + const r = validator.validateResponse({ method, path, status: res.status(), contentType, body, rawText, headers: res.headers() }); + for (const note of r.notes ?? []) test.info().annotations.push({ type: 'contract-note', description: note }); expect(r.ok, \`CONTRACT_MISMATCH \${method.toUpperCase()} \${path} (\${r.kind}): \${r.errors.join('; ')}\`).toBe(true); return body; } @@ -555,6 +758,21 @@ export async function expectRejected(res: APIResponse, documented: string[], met return expectContract(res, method, path); } +/** Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text. */ +export function fillVars(value: T, vars: Record): T { + const sub = (v: any): any => { + if (typeof v === 'string') { + const whole = v.match(/^\\{([A-Za-z_]\\w*)\\}$/); + if (whole) return vars[whole[1]]; + return v.replace(/\\{([A-Za-z_]\\w*)\\}/g, (_: string, k: string) => String(vars[k])); + } + if (Array.isArray(v)) return v.map(sub); + if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, sub(x)])); + return v; + }; + return sub(value); +} + export function readPointer(body: unknown, pointer: string): unknown { return pointer .split('/') diff --git a/src/report/report.ts b/src/report/report.ts index 7d74c59..c0a1a96 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 }[]; + /** After a run: every physical test has its own case ID registered in cases.json. */ + caseIdCheck?: { tests: number; missing: string[]; duplicates: string[]; unregistered: string[] }; }; } diff --git a/src/scenarios/dsl.ts b/src/scenarios/dsl.ts new file mode 100644 index 0000000..8ac3990 --- /dev/null +++ b/src/scenarios/dsl.ts @@ -0,0 +1,133 @@ +import type { Operation } from '../types.js'; +import type { CoverageGap } from '../generate/body-cases.js'; + +/** + * Reviewed business scenarios (docs/SUPPORT_MATRIX.md, stage 8). Business flows are never guessed from paths: + * they come from this file, written and reviewed by a human, validated strictly against the spec. + * JSON Schema: schemas/scenarios.schema.json. + */ + +export type Phase = 'setup' | 'action' | 'assertion' | 'cleanup'; + +export interface ScenarioStepDef { + name?: string; + operationId: string; + phase: Phase; + /** Path and query parameters by name. Strings may use "{var}" for values saved by earlier steps. */ + params?: Record; + /** JSON request body; "{var}" strings are replaced by saved values. */ + body?: unknown; + /** The documented status this step must get ("201", "4XX"...). Optional for cleanup steps. */ + expect?: string; + /** Values to keep for later steps: variable → JSON pointer into the response body. */ + save?: Record; +} + +export interface ScenarioDef { + /** External stable ID: the scenarioUid comes from it (never from the title). */ + id: string; + title: string; + polarity: 'positive' | 'negative'; + /** The step under test: its name or operationId. Must be an action step. */ + primary: string; + steps: ScenarioStepDef[]; +} + +export interface ScenarioFile { + scenarios: ScenarioDef[]; +} + +export interface ResolvedStep extends ScenarioStepDef { + op: Operation; +} + +export interface ResolvedScenario extends Omit { + steps: ResolvedStep[]; + primaryOp: Operation; +} + +const PHASES: Phase[] = ['setup', 'action', 'assertion', 'cleanup']; +const VAR = /\{([A-Za-z_][\w]*)\}/g; +const ID = /^[a-z0-9][a-z0-9._-]*$/; + +/** Variables a value refers to ("{cartId}" anywhere inside strings). */ +export function varsIn(value: unknown): string[] { + if (typeof value === 'string') return [...value.matchAll(VAR)].map((m) => m[1]); + if (Array.isArray(value)) return value.flatMap(varsIn); + if (value && typeof value === 'object') return Object.values(value).flatMap(varsIn); + return []; +} + +const documented = (op: Operation, status: string) => { + const s = status.toUpperCase(); + return op.responses.some((r) => r.status.toUpperCase() === s || (/^\dXX$/.test(r.status.toUpperCase()) && r.status[0] === s[0]) || r.status === 'default'); +}; + +/** Strict validation; every problem is an error with a pointer into the file. */ +export function validateScenarios(file: unknown, ops: Operation[]): { errors: { pointer: string; reason: string }[]; scenarios: ResolvedScenario[] } { + const errors: { pointer: string; reason: string }[] = []; + const err = (pointer: string, reason: string) => errors.push({ pointer, reason }); + const out: ResolvedScenario[] = []; + const f = file as ScenarioFile; + if (!f || typeof f !== 'object' || !Array.isArray(f.scenarios)) { + err('', 'a scenarios file is { "scenarios": [ … ] }'); + return { errors, scenarios: out }; + } + const byId = new Map(ops.filter((o) => o.operationId).map((o) => [o.operationId!, o])); + const ids = new Set(); + f.scenarios.forEach((sc, i) => { + const p = `/scenarios/${i}`; + const before = errors.length; + for (const k of Object.keys(sc ?? {})) if (!['id', 'title', 'polarity', 'primary', 'steps'].includes(k)) err(`${p}/${k}`, `unknown field "${k}"`); + if (typeof sc?.id !== 'string' || !ID.test(sc.id)) err(`${p}/id`, 'id is a stable external ID: lowercase letters, digits, ".", "_", "-"'); + else if (ids.has(sc.id)) err(`${p}/id`, `duplicate id "${sc.id}" (DUPLICATE_EXTERNAL_SCENARIO_ID)`); + else ids.add(sc.id); + if (typeof sc?.title !== 'string' || !sc.title.trim()) err(`${p}/title`, 'title is required'); + if (sc?.polarity !== 'positive' && sc?.polarity !== 'negative') err(`${p}/polarity`, 'polarity is "positive" or "negative"'); + const steps = Array.isArray(sc?.steps) ? sc.steps : []; + if (steps.length < 2) err(`${p}/steps`, 'a scenario has at least two steps'); + const saved = new Set(); + const resolved: ResolvedStep[] = []; + let seenCleanup = false; + steps.forEach((st, j) => { + const sp = `${p}/steps/${j}`; + for (const k of Object.keys(st ?? {})) if (!['name', 'operationId', 'phase', 'params', 'body', 'expect', 'save'].includes(k)) err(`${sp}/${k}`, `unknown field "${k}"`); + const op = byId.get(st?.operationId); + if (!op) { + err(`${sp}/operationId`, `operation "${st?.operationId}" is not in the spec`); + return; + } + if (!PHASES.includes(st.phase)) err(`${sp}/phase`, `phase is one of ${PHASES.join(', ')}`); + if (st.phase === 'cleanup') seenCleanup = true; + else if (seenCleanup) err(`${sp}/phase`, 'cleanup steps come last'); + if (st.expect === undefined && st.phase !== 'cleanup') err(`${sp}/expect`, 'every step but cleanup names its expected status'); + if (st.expect !== undefined && !documented(op, String(st.expect))) err(`${sp}/expect`, `${st.expect} is not documented for ${op.key}`); + for (const v of varsIn([st.params, st.body])) if (!saved.has(v)) err(sp, `"{${v}}" is not saved by an earlier step`); + for (const name of op.params.filter((x) => x.in === 'path').map((x) => x.name)) { + if (!(name in (st.params ?? {})) && op.params.find((x) => x.name === name)?.knownValue === undefined) err(`${sp}/params`, `path parameter "${name}" has no value`); + } + for (const name of Object.keys(st.params ?? {})) if (!op.params.some((x) => x.name === name && (x.in === 'path' || x.in === 'query'))) err(`${sp}/params/${name}`, `${op.key} has no path or query parameter "${name}"`); + if (st.body !== undefined && !op.hasRequestBody) err(`${sp}/body`, `${op.key} has no request body`); + for (const [v, ptr] of Object.entries(st.save ?? {})) { + if (typeof ptr !== 'string' || !(ptr === '' || ptr.startsWith('/'))) err(`${sp}/save/${v}`, 'save values are JSON pointers such as "/id"'); + saved.add(v); + } + resolved.push({ ...st, op }); + }); + // Data a scenario creates must be removed: any non-safe setup step needs a cleanup step. + const writes = resolved.filter((s) => s.phase !== 'cleanup' && !['get', 'head', 'options'].includes(s.op.method)); + if (writes.length && !resolved.some((s) => s.phase === 'cleanup')) err(`${p}/steps`, 'the scenario writes data but has no cleanup step (MISSING_CLEANUP)'); + const primary = resolved.find((s) => s.name === sc?.primary) ?? resolved.find((s) => s.op.operationId === sc?.primary); + if (!primary) err(`${p}/primary`, `primary "${sc?.primary}" is not a step name or operationId of this scenario`); + else if (primary.phase !== 'action') err(`${p}/primary`, 'the primary step is the action under test (phase "action")'); + if (errors.length === before && primary) out.push({ ...sc, steps: resolved, primaryOp: primary.op }); + }); + return { errors, scenarios: out }; +} + +/** Coverage note for operations without any scenario: business flows need the reviewed file. */ +export const NO_SCENARIO_FILE: CoverageGap = { + code: 'UNCONFIRMED_BUSINESS_RULE', + location: 'lifecycle', + reason: 'business flows (state transitions, parent → child, idempotency, polling) need a reviewed scenarios file (--scenarios)', +}; diff --git a/src/spec/catalog.ts b/src/spec/catalog.ts index 0bad6d7..c5979eb 100644 --- a/src/spec/catalog.ts +++ b/src/spec/catalog.ts @@ -47,6 +47,8 @@ export function buildCatalog(doc: OpenApiDoc): Operation[] { knownValue: knownValueWithSource(p, schema).value, knownSource: knownValueWithSource(p, schema).source, schema, + ...(p.style ? { style: p.style } : {}), + ...(typeof p.explode === 'boolean' ? { explode: p.explode } : {}), }; }); diff --git a/src/types.ts b/src/types.ts index 4c61bf8..8928673 100644 --- a/src/types.ts +++ b/src/types.ts @@ -15,6 +15,9 @@ export interface ParamInfo { /** Where knownValue came from: an illustrative example, or a value the schema defines (default/enum/const). */ knownSource?: 'example' | 'default' | 'enum' | 'const'; schema?: Record; + /** Serialization as documented (form, simple, spaceDelimited, …); defaults follow OpenAPI. */ + style?: string; + explode?: boolean; } export interface ResponseInfo { diff --git a/tests/api/_support/cases.json b/tests/api/_support/cases.json index 3f0fcb1..e0d6ee9 100644 --- a/tests/api/_support/cases.json +++ b/tests/api/_support/cases.json @@ -1,5 +1,5 @@ { - "caseRuleVocabularyVersion": 1, + "caseRuleVocabularyVersion": 2, "cases": { "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:maximum": { "location": "request.query#/limit", @@ -40,6 +40,20 @@ "subjectUid": "op_4PIO72ZI3SIY", "suiteType": "functional" }, + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/100:accepted-value": { + "location": "request.query#/limit/100", + "polarity": "positive", + "rule": "accepted-value", + "subjectUid": "op_4PIO72ZI3SIY", + "suiteType": "functional" + }, + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/1:accepted-value": { + "location": "request.query#/limit/1", + "polarity": "positive", + "rule": "accepted-value", + "subjectUid": "op_4PIO72ZI3SIY", + "suiteType": "functional" + }, "ata:op_7P2UH7UKQRHC:contract:positive:response.body#:schema": { "covers": [ "contract:positive:response.content-type#/application~1json:documented", @@ -90,6 +104,17 @@ "op_UPN7JLUXYUZ7" ], "rule": "schema", + "status": "retired", + "subjectUid": "op_EDRRXKOK26ZL", + "suiteType": "contract" + }, + "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/204:documented": { + "location": "response.status#/204", + "polarity": "positive", + "relatedOperationUids": [ + "op_UPN7JLUXYUZ7" + ], + "rule": "documented", "subjectUid": "op_EDRRXKOK26ZL", "suiteType": "contract" }, @@ -163,6 +188,13 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable": { + "location": "request.body#/name", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required": { "location": "request.body#/name", "polarity": "negative", @@ -184,6 +216,13 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:nullable": { + "location": "request.body#/price", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required": { "location": "request.body#/price", "polarity": "negative", @@ -198,6 +237,34 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:maxLength": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "maxLength", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:minLength": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "minLength", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:nullable": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:type": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "type", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems": { "location": "request.body#/tags", "polarity": "negative", @@ -205,6 +272,13 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:nullable": { + "location": "request.body#/tags", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:type": { "location": "request.body#/tags", "polarity": "negative", @@ -279,6 +353,13 @@ "subjectUid": "op_WRZHS7HTMVON", "suiteType": "contract" }, + "ata:op_WRZHS7HTMVON:functional:negative:request.security:invalid-credentials": { + "location": "request.security", + "polarity": "negative", + "rule": "invalid-credentials", + "subjectUid": "op_WRZHS7HTMVON", + "suiteType": "functional" + }, "ata:op_WRZHS7HTMVON:functional:negative:request.security:unauthorized": { "location": "request.security", "polarity": "negative", @@ -307,6 +388,13 @@ "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:nullable": { + "location": "request.body#/name", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_Z4MCICNBZN3S", + "suiteType": "contract" + }, "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:type": { "location": "request.body#/name", "polarity": "negative", @@ -321,6 +409,13 @@ "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:nullable": { + "location": "request.body#/price", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_Z4MCICNBZN3S", + "suiteType": "contract" + }, "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:type": { "location": "request.body#/price", "polarity": "negative", @@ -332,6 +427,7 @@ "location": "request.body#/tags", "polarity": "negative", "rule": "maxItems", + "status": "retired", "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, @@ -339,6 +435,7 @@ "location": "request.body#/tags", "polarity": "negative", "rule": "type", + "status": "retired", "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, @@ -407,6 +504,17 @@ "subjectUid": "scn_4EG5AXFZY2YS", "suiteType": "scenario" }, + "ata:scn_6I3KELJAMGYP:scenario:positive:lifecycle:business-rule": { + "location": "lifecycle", + "polarity": "positive", + "relatedOperationUids": [ + "op_EDRRXKOK26ZL", + "op_UPN7JLUXYUZ7" + ], + "rule": "business-rule", + "subjectUid": "scn_6I3KELJAMGYP", + "suiteType": "scenario" + }, "ata:scn_7MN4FYBHZCZQ:scenario:positive:lifecycle:crud": { "location": "lifecycle", "polarity": "positive", @@ -429,6 +537,27 @@ "rule": "crud", "subjectUid": "scn_I6MIGZS3ULNR", "suiteType": "scenario" + }, + "ata:scn_V2OYCQUW2VKW:scenario:negative:lifecycle:business-rule": { + "location": "lifecycle", + "polarity": "negative", + "relatedOperationUids": [ + "op_UPN7JLUXYUZ7" + ], + "rule": "business-rule", + "subjectUid": "scn_V2OYCQUW2VKW", + "suiteType": "scenario" + }, + "ata:scn_VQLGIE5JMTBU:scenario:negative:lifecycle:business-rule": { + "location": "lifecycle", + "polarity": "negative", + "relatedOperationUids": [ + "op_EDRRXKOK26ZL", + "op_UPN7JLUXYUZ7" + ], + "rule": "business-rule", + "subjectUid": "scn_VQLGIE5JMTBU", + "suiteType": "scenario" } }, "externalIdAliases": {}, @@ -526,6 +655,25 @@ } ] }, + "scn_6I3KELJAMGYP": { + "externalId": "items.read-created", + "primaryOperationUid": "op_7P2UH7UKQRHC", + "scenarioType": "business", + "steps": [ + { + "operationUid": "op_UPN7JLUXYUZ7", + "phase": "setup" + }, + { + "operationUid": "op_7P2UH7UKQRHC", + "phase": "action" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "cleanup" + } + ] + }, "scn_7MN4FYBHZCZQ": { "primaryOperationUid": "op_UPN7JLUXYUZ7", "roles": { @@ -577,6 +725,53 @@ "phase": "cleanup" } ] + }, + "scn_V2OYCQUW2VKW": { + "primaryOperationUid": "op_EDRRXKOK26ZL", + "roles": { + "create": "op_UPN7JLUXYUZ7", + "read": null, + "update": null, + "delete": "op_EDRRXKOK26ZL" + }, + "scenarioType": "crud", + "steps": [ + { + "operationUid": "op_UPN7JLUXYUZ7", + "phase": "setup" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "action" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "assertion" + } + ] + }, + "scn_VQLGIE5JMTBU": { + "externalId": "items.gone-after-delete", + "primaryOperationUid": "op_7P2UH7UKQRHC", + "scenarioType": "business", + "steps": [ + { + "operationUid": "op_UPN7JLUXYUZ7", + "phase": "setup" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "setup" + }, + { + "operationUid": "op_7P2UH7UKQRHC", + "phase": "action" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "cleanup" + } + ] } }, "schemaVersion": 1 diff --git a/tests/api/_support/contract-assert.ts b/tests/api/_support/contract-assert.ts index 0e4122a..2d1da78 100644 --- a/tests/api/_support/contract-assert.ts +++ b/tests/api/_support/contract-assert.ts @@ -1,6 +1,6 @@ // Generated by api-test-agent. Bridges Playwright responses to the OpenAPI contract. import { appendFileSync } from 'node:fs'; -import { expect, type APIResponse } from '@playwright/test'; +import { expect, test, type APIResponse } from '@playwright/test'; import { ContractValidator } from './contract.js'; import { spec } from './openapi.snapshot.js'; @@ -16,24 +16,28 @@ export function reportCleanupFailure(operation: string, id: string, status: numb else console.warn(`cleanup failed: ${operation} ${id} → ${status} (test data left on the target)`); } -async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown }> { +async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown; rawText: string }> { const contentType = res.headers()['content-type'] ?? null; - const text = await res.text(); - let body: unknown = text; + const rawText = await res.text(); + let body: unknown = rawText; if (contentType?.includes('json')) { try { - body = text.length ? JSON.parse(text) : null; + body = rawText.length ? JSON.parse(rawText) : null; } catch { body = undefined; } } - return { contentType, body }; + return { contentType, body, rawText }; } -/** Validates status, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. */ +/** + * Validates status, headers, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. + * What could not be checked (e.g. a media type without a schema) is added to the test report as a note. + */ export async function expectContract(res: APIResponse, method: string, path: string): Promise { - const { contentType, body } = await readBody(res); - const r = validator.validateResponse({ method, path, status: res.status(), contentType, body }); + const { contentType, body, rawText } = await readBody(res); + const r = validator.validateResponse({ method, path, status: res.status(), contentType, body, rawText, headers: res.headers() }); + for (const note of r.notes ?? []) test.info().annotations.push({ type: 'contract-note', description: note }); expect(r.ok, `CONTRACT_MISMATCH ${method.toUpperCase()} ${path} (${r.kind}): ${r.errors.join('; ')}`).toBe(true); return body; } @@ -51,6 +55,21 @@ export async function expectRejected(res: APIResponse, documented: string[], met return expectContract(res, method, path); } +/** Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text. */ +export function fillVars(value: T, vars: Record): T { + const sub = (v: any): any => { + if (typeof v === 'string') { + const whole = v.match(/^\{([A-Za-z_]\w*)\}$/); + if (whole) return vars[whole[1]]; + return v.replace(/\{([A-Za-z_]\w*)\}/g, (_: string, k: string) => String(vars[k])); + } + if (Array.isArray(v)) return v.map(sub); + if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, sub(x)])); + return v; + }; + return sub(value); +} + export function readPointer(body: unknown, pointer: string): unknown { return pointer .split('/') diff --git a/tests/api/_support/contract.ts b/tests/api/_support/contract.ts index c74357c..9d5da94 100644 --- a/tests/api/_support/contract.ts +++ b/tests/api/_support/contract.ts @@ -4,6 +4,7 @@ * This file is deliberately self-contained (no imports from the agent): `generate` * copies it verbatim into tests/generated/_support/ so generated tests run without * the agent installed. Keep it dependency-light: ajv + ajv-formats only. + * src/contract/contract.py is its Python twin: keep the rules identical. */ import { Ajv, type ValidateFunction } from 'ajv'; import { Ajv2020 } from 'ajv/dist/2020.js'; @@ -11,7 +12,7 @@ import addFormatsModule from 'ajv-formats'; const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; -export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body'; +export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body' | 'empty-body' | 'unexpected-body' | 'header'; export interface ContractResult { ok: boolean; @@ -20,9 +21,26 @@ export interface ContractResult { kind?: ContractProblemKind; errors: string[]; matchedStatus?: string; + /** What was not checked and why (e.g. a media type without a supported schema). Never a failure. */ + notes?: string[]; +} + +export interface ResponseInput { + method: string; + path: string; + status: number; + contentType?: string | null; + /** Parsed JSON for JSON media types, the text otherwise; undefined when JSON could not be parsed. */ + body: unknown; + /** The raw response text: decides "empty" and "unexpected body". */ + rawText?: string; + /** Response headers (any case). */ + headers?: Record; } const DOC_ID = 'openapi.json'; +/** Statuses that never carry a body (RFC 9110). */ +const NO_BODY_STATUS = new Set([204, 205, 304]); export class ContractValidator { private readonly ajv: Ajv; @@ -31,14 +49,33 @@ export class ContractValidator { constructor(doc: any) { const is31 = /^3\.[12]\./.test(String(doc.openapi ?? '')); // 3.1 and 3.2: JSON Schema 2020-12 - this.doc = is31 ? structuredClone(doc) : nullableToJsonSchema(structuredClone(doc)); + const copy = structuredClone(doc); + // Responses only: a writeOnly property is never sent back, so it is never required in a response. + dropWriteOnlyFromRequired(copy); + this.doc = is31 ? copy : nullableToJsonSchema(copy); const opts = { strict: false, allErrors: true, validateSchema: false } as const; this.ajv = (is31 ? new Ajv2020(opts) : new Ajv(opts)) as Ajv; addFormats(this.ajv); + // writeOnly properties must not appear in a response. + this.ajv.removeKeyword('writeOnly'); // ajv knows it as an annotation; redefine it as a check + this.ajv.addKeyword({ keyword: 'writeOnly', schemaType: 'boolean', validate: (writeOnly: boolean) => !writeOnly, errors: false }); this.ajv.addSchema(this.doc, DOC_ID); } - validateResponse(input: { method: string; path: string; status: number; contentType?: string | null; body: unknown }): ContractResult { + private compile(pointer: string): ValidateFunction { + let validate = this.cache.get(pointer); + if (!validate) { + validate = this.ajv.compile({ $ref: `${DOC_ID}#${pointer}` }); + this.cache.set(pointer, validate); + } + return validate; + } + + private messages(validate: ValidateFunction, prefix = ''): string[] { + return (validate.errors ?? []).map((e) => `${prefix}${e.instancePath || '(root)'} ${e.keyword === 'writeOnly' ? 'is writeOnly and must not appear in a response' : e.message}`); + } + + validateResponse(input: ResponseInput): ContractResult { const opPtr = `/paths/${esc(input.path)}/${input.method.toLowerCase()}`; const responses = resolve(this.doc, `${opPtr}/responses`).node ?? {}; const code = String(input.status); @@ -52,11 +89,33 @@ export class ContractValidator { }; } const resp = resolve(this.doc, `${opPtr}/responses/${esc(matched)}`); + const notes: string[] = []; + + // Response headers: required ones present, every documented one matching its schema. + const headerErrors = this.checkHeaders(resp.node?.headers ?? {}, `${resp.pointer}/headers`, input.headers); + if (headerErrors.length) return { ok: false, bodyChecked: false, kind: 'header', matchedStatus: matched, errors: headerErrors }; + + // Without the raw text, the parsed body stands for it (JSON null is the text "null", not an empty body). + const raw = input.rawText ?? (typeof input.body === 'string' ? input.body : input.body === undefined ? '' : JSON.stringify(input.body)); const content = resp.node?.content; - if (!content || !Object.keys(content).length) return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const head = input.method.toLowerCase() === 'head'; + if (!content || !Object.keys(content).length || NO_BODY_STATUS.has(input.status) || head) { + // No body is documented (or the status / method has none): one that arrives anyway breaks the contract. + if (raw.trim().length && !head) { + const why = NO_BODY_STATUS.has(input.status) ? `status ${code} has no body` : `no content is documented for ${matched}`; + return { ok: false, bodyChecked: true, kind: 'unexpected-body', matchedStatus: matched, errors: [`A body was returned but ${why} (${raw.length} bytes)`] }; + } + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, ...(notes.length ? { notes } : {}) }; + } const actual = (input.contentType ?? '').split(';')[0].trim().toLowerCase(); const mediaKey = pickMedia(Object.keys(content), actual); + // A declared but undocumented Content-Type is the more precise problem; an empty body comes next. + if (!raw.trim().length && (!actual || mediaKey)) { + const hasSchema = Object.values(content).some((m) => m?.schema); + if (hasSchema) return { ok: false, bodyChecked: true, kind: 'empty-body', matchedStatus: matched, errors: [`The body is empty but ${matched} documents ${Object.keys(content).join(', ')}`] }; + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + } if (!mediaKey) { return { ok: false, @@ -66,28 +125,72 @@ export class ContractValidator { errors: [`Content-Type "${actual || 'none'}" is not documented for ${matched} (documented: ${Object.keys(content).join(', ')})`], }; } - if (!content[mediaKey]?.schema || !mediaKey.includes('json')) { - return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; + if (!content[mediaKey]?.schema) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: no schema documented, body not checked`] }; + } + if (baseMedia(mediaKey).startsWith('text/')) { + // Text bodies with a schema: the text is the (string) instance. + const validate = this.compile(schemaPtr); + const ok = validate(raw) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } + if (!baseMedia(mediaKey).includes('json')) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: media type not supported by the validator, body not checked`] }; } if (input.body === undefined) { return { ok: false, bodyChecked: true, kind: 'unparseable-body', matchedStatus: matched, errors: ['Body is not valid JSON'] }; } + const validate = this.compile(schemaPtr); + const ok = validate(input.body) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } - const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; - let validate = this.cache.get(schemaPtr); - if (!validate) { - validate = this.ajv.compile({ $ref: `${DOC_ID}#${schemaPtr}` }); - this.cache.set(schemaPtr, validate); + private checkHeaders(defs: Record, pointer: string, actual?: Record): string[] { + const errors: string[] = []; + const got = Object.fromEntries(Object.entries(actual ?? {}).map(([k, v]) => [k.toLowerCase(), v])); + for (const [name, raw] of Object.entries(defs)) { + if (name.toLowerCase() === 'content-type') continue; // OpenAPI: ignored, the media type decides + const def = raw?.$ref ? resolve(this.doc, raw.$ref.slice(1)).node : raw; + const value = got[name.toLowerCase()]; + if (value === undefined) { + if (def?.required) errors.push(`Required response header "${name}" is missing`); + continue; + } + if (!def?.schema || actual === undefined) continue; + const validate = this.compile(`${pointer}/${esc(name)}/schema`); + if (!(validate(headerValue(def.schema, value, this.doc)) as boolean)) errors.push(...this.messages(validate, `header "${name}" `)); } - const ok = validate(input.body) as boolean; - return { - ok, - bodyChecked: true, - kind: ok ? undefined : 'schema', - matchedStatus: matched, - errors: ok ? [] : (validate.errors ?? []).map((e) => `${e.instancePath || '(root)'} ${e.message}`), - }; + return errors; + } +} + +/** A header value as its schema expects it: numbers, booleans and comma-separated arrays (style: simple). */ +function headerValue(schemaRaw: any, value: string, doc: any): unknown { + const schema = schemaRaw?.$ref ? resolve(doc, schemaRaw.$ref.slice(1)).node : schemaRaw; + const types: string[] = schema?.type === undefined ? [] : Array.isArray(schema.type) ? schema.type : [schema.type]; + const scalar = (v: string, t: string[]) => { + if ((t.includes('integer') || t.includes('number')) && v.trim() !== '' && !Number.isNaN(Number(v))) return Number(v); + if (t.includes('boolean') && (v === 'true' || v === 'false')) return v === 'true'; + return v; + }; + if (types.includes('array')) { + const items = schema.items?.$ref ? resolve(doc, schema.items.$ref.slice(1)).node : schema.items; + const it: string[] = items?.type === undefined ? [] : Array.isArray(items.type) ? items.type : [items.type]; + return value.split(',').map((v) => scalar(v.trim(), it)); + } + return scalar(value, types); +} + +/** Removes writeOnly properties from every `required` list (they are never part of a response). */ +function dropWriteOnlyFromRequired(node: any, seen = new Set()): void { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node)) return node.forEach((n) => dropWriteOnlyFromRequired(n, seen)); + if (Array.isArray(node.required) && node.properties && typeof node.properties === 'object') { + node.required = node.required.filter((name: string) => node.properties[name]?.writeOnly !== true); } + for (const v of Object.values(node)) dropWriteOnlyFromRequired(v, seen); } /** Media types are compared without parameters: "application/json; v=1.0" documents "application/json". */ diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index 5100f7e..fb8272f 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -1,5 +1,5 @@ { - "caseRegistryHash": "37bb92bb8ccf1d6d2643ea93e47adf3d78bf2df717b5c0f8bf6923f42ab643c1", + "caseRegistryHash": "8755eefa57796e2434f5acfd81f1d9dc5235dadac364c53a5928c95ea4e9604f", "files": { "_support/api/generated/AdminApiBase.ts": { "ownership": "generated", @@ -39,11 +39,11 @@ }, "_support/contract-assert.ts": { "ownership": "generated", - "sha256": "fbbd168c9255903b3c1499dd88f007806846b2e14e3c42e7b01e17361ba60d78" + "sha256": "3209352f79c89cb749fe9a640802f2dbf0429fa9d3b9f9faf375f307c87d0bf4" }, "_support/contract.ts": { "ownership": "generated", - "sha256": "8593fa68484c84f12c84803c30ef474dc1718750ef102647014c7e99e0b166aa" + "sha256": "e3984cc678d6fa6afb72a849e65f103f1b7c42a6dcedcf2074719396714ae7a7" }, "_support/fixtures.ts": { "ownership": "generated", @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "d76615ab812db149bbc2fa0f3c6c54fcd33dd32425f30a112183076446a41a2c" + "sha256": "c8e6f04b65d4ea77613ad771f2dfcf820450ae83bb19be1c3870d174bd1d2f1f" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -85,7 +85,7 @@ }, "items/delete-by-id/contract.spec.ts": { "caseIds": [ - "ata:op_EDRRXKOK26ZL:contract:positive:response.body#:schema", + "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/204:documented", "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/404:documented" ], "operationUids": [ @@ -93,7 +93,7 @@ "op_UPN7JLUXYUZ7" ], "ownership": "generated", - "sha256": "8fe5d6a0c20e08c655890970e0e5fbe2ba95433a08c265830d32dc644898382b", + "sha256": "36d18c0e4bb64b7b82cf35fed29edea67c5c62ccd54354f608485b3187f23457", "suiteType": "contract" }, "items/delete-by-id/functional.spec.ts": { @@ -111,6 +111,7 @@ }, "items/delete-by-id/scenarios.spec.ts": { "caseIds": [ + "ata:scn_V2OYCQUW2VKW:scenario:negative:lifecycle:business-rule", "ata:scn_4EG5AXFZY2YS:scenario:positive:lifecycle:crud" ], "operationUids": [ @@ -119,7 +120,7 @@ "op_7P2UH7UKQRHC" ], "ownership": "generated", - "sha256": "8174a9a3169561d39f2447242bb94b64ee05dbac34f71b0e7f212fe6836ad41c", + "sha256": "420d713c48f68e70aaeaaeaaa42b8055df861e3efa31382fe849dad6b41e9d01", "suiteType": "scenario" }, "items/get-by-id/contract.spec.ts": { @@ -150,6 +151,20 @@ "sha256": "2896edace4ecdb2a4980d912b9f3115ad1612169d902d2ea609947bd200b6af0", "suiteType": "functional" }, + "items/get-by-id/scenarios.spec.ts": { + "caseIds": [ + "ata:scn_6I3KELJAMGYP:scenario:positive:lifecycle:business-rule", + "ata:scn_VQLGIE5JMTBU:scenario:negative:lifecycle:business-rule" + ], + "operationUids": [ + "op_7P2UH7UKQRHC", + "op_UPN7JLUXYUZ7", + "op_EDRRXKOK26ZL" + ], + "ownership": "generated", + "sha256": "e236e4cd315de6dc77e56cded24124d057372b1021c70f3d30caa7c0f3e835de", + "suiteType": "scenario" + }, "items/get/contract.spec.ts": { "caseIds": [ "ata:op_4PIO72ZI3SIY:contract:positive:response.body#:schema", @@ -161,33 +176,35 @@ "op_4PIO72ZI3SIY" ], "ownership": "generated", - "sha256": "19cb5063a2ea8c0448d9edb782404e52f9bc249144628963b1a3616ef388e402", + "sha256": "8f23c22db292e30e950f567f4c3a4f3a2264bb8acef45c9537d78a2d2d4bb236", "suiteType": "contract" }, "items/get/functional.spec.ts": { "caseIds": [ - "ata:op_4PIO72ZI3SIY:functional:positive:operation:documented-success" + "ata:op_4PIO72ZI3SIY:functional:positive:operation:documented-success", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/1:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/100:accepted-value" ], "operationUids": [ "op_4PIO72ZI3SIY" ], "ownership": "generated", - "sha256": "107a7657f2b7af3b2f0393ad86507cc5645d16e0d09812b30afedb849edf7d99", + "sha256": "5e1cb6b000284b6bfcf733bea1a1d3a451fc435107ebf490279a09b14ec190ff", "suiteType": "functional" }, "items/patch-by-id/contract.spec.ts": { "caseIds": [ "ata:op_Z4MCICNBZN3S:contract:positive:response.body#:schema", "ata:op_Z4MCICNBZN3S:contract:positive:response.status#/404:documented", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:type", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:nullable", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:minLength", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:maxLength", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:type", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:minimum", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:type", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:maxItems", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties" + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:nullable", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:minimum" ], "operationUids": [ "op_Z4MCICNBZN3S", @@ -195,7 +212,7 @@ "op_EDRRXKOK26ZL" ], "ownership": "generated", - "sha256": "8c0b79701cc998ccd4afd0f16c274536cb7fad84af02ef5fbe2189c35bdf4a5b", + "sha256": "1f353d4c44630a9cc9556190625ad61b71aeee5b3215d3159d7f097ca61758cd", "suiteType": "contract" }, "items/patch-by-id/functional.spec.ts": { @@ -231,21 +248,28 @@ "ata:op_UPN7JLUXYUZ7:contract:positive:response.body#:schema", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:minLength", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:maxLength", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:nullable", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:minimum", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:nullable", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems", - "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties" + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:nullable", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:minLength", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:maxLength" ], "operationUids": [ "op_UPN7JLUXYUZ7", "op_EDRRXKOK26ZL" ], "ownership": "generated", - "sha256": "373f0a7807196e97caf331181e6cbac8867e14ade0e9a1074f63eb1359b9967b", + "sha256": "55aa00d7008175ecca10ec2966419c00b4b988eb7e32daec3dc6d6942c68e719", "suiteType": "contract" }, "items/post/functional.spec.ts": { @@ -257,7 +281,7 @@ "op_EDRRXKOK26ZL" ], "ownership": "generated", - "sha256": "e1ceb3800a680333b4a45c29980c36d1245b705c8da20fb3dc3de0ae2fef5def", + "sha256": "12e7382980e8ed311af492b7662241d72acf59e4c321ee91266899029447b9b0", "suiteType": "functional" }, "items/post/scenarios.spec.ts": { @@ -288,13 +312,14 @@ "me/get/functional.spec.ts": { "caseIds": [ "ata:op_WRZHS7HTMVON:functional:positive:operation:documented-success", - "ata:op_WRZHS7HTMVON:functional:negative:request.security:unauthorized" + "ata:op_WRZHS7HTMVON:functional:negative:request.security:unauthorized", + "ata:op_WRZHS7HTMVON:functional:negative:request.security:invalid-credentials" ], "operationUids": [ "op_WRZHS7HTMVON" ], "ownership": "generated", - "sha256": "7889879405c221505474de9f4e3048b77dc1be70ab2b1399ade88fd629ce018d", + "sha256": "0078147e5f0ab275165ebf21e15f534439352c5af45fe5d3a82596070546326b", "suiteType": "functional" }, "reports/get-by-id/contract.spec.ts": { @@ -346,7 +371,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "8ee4d7f0ebae3dc6c359ad03e9879676cc689ac7", + "revision": "91b54559edf4b02cafec7503f06277ea1ce7a21f", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index 66b37b0..0324d6d 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "8ee4d7f0ebae3dc6c359ad03e9879676cc689ac7", + "capturedRevision": "91b54559edf4b02cafec7503f06277ea1ce7a21f", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/api/items/delete-by-id/contract.spec.ts b/tests/api/items/delete-by-id/contract.spec.ts index b6334c1..3bbd892 100644 --- a/tests/api/items/delete-by-id/contract.spec.ts +++ b/tests/api/items/delete-by-id/contract.spec.ts @@ -11,7 +11,7 @@ import { expectContract } from '../../_support/contract-assert.js'; import * as resource from '../../_support/items.resource.js'; test.describe('DELETE /items/{itemId} · contract', { tag: '@contract' }, () => { - test('success response matches the documented contract', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_EDRRXKOK26ZL:contract:positive:response.body#:schema' } }, async ({ api }) => { + test('success response matches the documented contract', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_EDRRXKOK26ZL:contract:positive:response.status#/204:documented' } }, async ({ api }) => { const { id } = await resource.create(api); try { const res = await api.items.deleteItem(id); diff --git a/tests/api/items/delete-by-id/scenarios.spec.ts b/tests/api/items/delete-by-id/scenarios.spec.ts index 96a3863..a5550d6 100644 --- a/tests/api/items/delete-by-id/scenarios.spec.ts +++ b/tests/api/items/delete-by-id/scenarios.spec.ts @@ -5,9 +5,22 @@ // Each scenario: setup (create) → action (this operation) → assertion (read) → cleanup (delete). // Polarity is a tag: run one side with --grep @positive or --grep @negative. import { test, expect } from '../../_support/fixtures.js'; +import { expectStatus } from '../../_support/contract-assert.js'; import * as resource from '../../_support/items.resource.js'; test.describe('DELETE /items/{itemId} · scenarios', { tag: '@scenario' }, () => { + test('deleting the same resource again gets the documented 404', { tag: '@negative', annotation: { type: 'caseId', description: 'ata:scn_V2OYCQUW2VKW:scenario:negative:lifecycle:business-rule' } }, async ({ api }) => { + const { id } = await resource.create(api); + try { + const first = await api.items.deleteItem(id); + expect(first.status(), 'documented success status of deleteItem').toBe(204); + const res = await api.items.deleteItem(id); + expectStatus(res, ['404'], 'delete', '/items/{itemId}'); + } finally { + await resource.remove(api, id); + } + }); + test('the deleted resource is no longer returned by getItem', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:scn_4EG5AXFZY2YS:scenario:positive:lifecycle:crud' } }, async ({ api }) => { const { id } = await resource.create(api); try { diff --git a/tests/api/items/get-by-id/scenarios.spec.ts b/tests/api/items/get-by-id/scenarios.spec.ts new file mode 100644 index 0000000..cef1559 --- /dev/null +++ b/tests/api/items/get-by-id/scenarios.spec.ts @@ -0,0 +1,53 @@ +// GET /items/{itemId} · scenario cases. Generated by api-test-agent 0.1.3. +// Spec: demo-api/openapi.yaml (hash d7b3b546ce170690). Regenerated on spec change: put hand-written cases in separate files. +// Review before merging; never edit assertions just to make a test pass. +// Preconditions and cleanup: OpenAPI links on createItem (GetItem, UpdateItem, DeleteItem) +// Each scenario: setup (create) → action (this operation) → assertion (read) → cleanup (delete). +// Business scenarios come from the reviewed scenarios file: steps, expected statuses and cleanup as written there. +// Polarity is a tag: run one side with --grep @positive or --grep @negative. +import { test, expect } from '../../_support/fixtures.js'; +import { readPointer, expectStatus, fillVars, reportCleanupFailure } from '../../_support/contract-assert.js'; +import * as resource from '../../_support/items.resource.js'; + +test.describe('GET /items/{itemId} · scenarios', { tag: '@scenario' }, () => { + test('an item that was just created can be read by its id', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:scn_6I3KELJAMGYP:scenario:positive:lifecycle:business-rule' } }, async ({ api }) => { + const vars: Record = {}; + try { + // setup create: POST /items + const res0 = await api.items.createItem({ data: fillVars({"name":"Scenario item","price":5,"tags":["scenario"]}, vars) }); + expectStatus(res0, ['201'], 'post', '/items'); + const body0 = await res0.json().catch(() => undefined); + vars['itemId'] = readPointer(body0, '/id'); + // action read: GET /items/{itemId} + const res1 = await api.items.getItem(String(fillVars("{itemId}", vars))); + expectStatus(res1, ['200'], 'get', '/items/{itemId}'); + } finally { + if (vars['itemId'] !== undefined) { + const clean0 = await api.items.deleteItem(String(fillVars("{itemId}", vars))).catch(() => undefined); + if (!clean0 || (!clean0.ok() && clean0.status() !== 404)) reportCleanupFailure('DELETE /items/{itemId}', String(vars['itemId']), clean0 ? clean0.status() : 'no response'); + } + } + }); + + test('an item that was deleted cannot be read any more', { tag: '@negative', annotation: { type: 'caseId', description: 'ata:scn_VQLGIE5JMTBU:scenario:negative:lifecycle:business-rule' } }, async ({ api }) => { + const vars: Record = {}; + try { + // setup create: POST /items + const res0 = await api.items.createItem({ data: fillVars({"name":"Scenario item","price":5}, vars) }); + expectStatus(res0, ['201'], 'post', '/items'); + const body0 = await res0.json().catch(() => undefined); + vars['itemId'] = readPointer(body0, '/id'); + // setup delete: DELETE /items/{itemId} + const res1 = await api.items.deleteItem(String(fillVars("{itemId}", vars))); + expectStatus(res1, ['204'], 'delete', '/items/{itemId}'); + // action read: GET /items/{itemId} + const res2 = await api.items.getItem(String(fillVars("{itemId}", vars))); + expectStatus(res2, ['404'], 'get', '/items/{itemId}'); + } finally { + if (vars['itemId'] !== undefined) { + const clean0 = await api.items.deleteItem(String(fillVars("{itemId}", vars))).catch(() => undefined); + if (!clean0 || (!clean0.ok() && clean0.status() !== 404)) reportCleanupFailure('DELETE /items/{itemId}', String(vars['itemId']), clean0 ? clean0.status() : 'no response'); + } + } + }); +}); diff --git a/tests/api/items/get/contract.spec.ts b/tests/api/items/get/contract.spec.ts index 3928eee..85af71c 100644 --- a/tests/api/items/get/contract.spec.ts +++ b/tests/api/items/get/contract.spec.ts @@ -16,15 +16,15 @@ test.describe('GET /items · contract', { tag: '@contract' }, () => { await expectContract(res, 'get', '/items'); }); - const invalidQueries = [ - { title: 'query "limit" is not a number', source: 'query.limit.type', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:type', params: {"limit":"abc"} }, + const invalidParameters: { title: string; source: string; caseId?: string; params?: Record | string; headers?: Record; path?: Record }[] = [ + { title: 'query "limit" has wrong type (integer expected)', source: 'query.limit.type', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:type', params: {"limit":"not-a-number"} }, { title: 'query "limit" below minimum 1', source: 'query.limit.minimum', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:minimum', params: {"limit":0} }, { title: 'query "limit" above maximum 100', source: 'query.limit.maximum', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:maximum', params: {"limit":101} }, ]; - for (const c of invalidQueries) { - test(`rejects invalid query: ${c.title}`, { tag: '@negative', annotation: { type: 'caseId', description: c.caseId } }, async ({ publicApi }) => { - const res = await publicApi.items.listItems({ params: c.params }); + for (const c of invalidParameters) { + test(`rejects invalid parameter: ${c.title}`, { tag: '@negative', annotation: { type: 'caseId', description: c.caseId } }, async ({ publicApi }) => { + const res = await publicApi.items.listItems({ params: c.params, headers: c.headers }); await expectRejected(res, rejection, 'get', '/items'); }); } diff --git a/tests/api/items/get/functional.spec.ts b/tests/api/items/get/functional.spec.ts index f9ff2ea..506750a 100644 --- a/tests/api/items/get/functional.spec.ts +++ b/tests/api/items/get/functional.spec.ts @@ -11,4 +11,14 @@ test.describe('GET /items · functional', { tag: '@functional' }, () => { const res = await publicApi.items.listItems(); expect(res.status(), 'documented success status of listItems').toBe(200); }); + + test('accepts documented limit=1', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/1:accepted-value' } }, async ({ publicApi }) => { + const res = await publicApi.items.listItems({ params: {"limit":1} }); + expect(res.status(), 'documented success status of listItems').toBe(200); + }); + + test('accepts documented limit=100', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/100:accepted-value' } }, async ({ publicApi }) => { + const res = await publicApi.items.listItems({ params: {"limit":100} }); + expect(res.status(), 'documented success status of listItems').toBe(200); + }); }); diff --git a/tests/api/items/patch-by-id/contract.spec.ts b/tests/api/items/patch-by-id/contract.spec.ts index 80db385..9c425cd 100644 --- a/tests/api/items/patch-by-id/contract.spec.ts +++ b/tests/api/items/patch-by-id/contract.spec.ts @@ -30,15 +30,15 @@ test.describe('PATCH /items/{itemId} · contract', { tag: '@contract' }, () => { }); const invalidBodies = [ + { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemPatch.additionalProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard v2","price":99.5,"__unexpected_field__":"api-agent"} }, + { title: '"(body)" has fewer than minProperties 1', source: 'ItemPatch.minProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties', data: {} }, { title: '"name" has wrong type (string expected)', source: 'ItemPatch.name.type', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:type', data: {"name":12345,"price":99.5} }, + { title: '"name" is null (not nullable)', source: 'ItemPatch.name.nullable', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:nullable', data: {"name":null,"price":99.5} }, { title: '"name" shorter than minLength 1', source: 'ItemPatch.name.minLength', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:minLength', data: {"name":"","price":99.5} }, { title: '"name" longer than maxLength 100', source: 'ItemPatch.name.maxLength', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:maxLength', data: {"name":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","price":99.5} }, { title: '"price" has wrong type (number expected)', source: 'ItemPatch.price.type', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:type', data: {"name":"Mechanical keyboard v2","price":"not-a-number"} }, + { title: '"price" is null (not nullable)', source: 'ItemPatch.price.nullable', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:nullable', data: {"name":"Mechanical keyboard v2","price":null} }, { title: '"price" below minimum 0', source: 'ItemPatch.price.minimum', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:minimum', data: {"name":"Mechanical keyboard v2","price":-1} }, - { title: '"tags" has wrong type (array expected)', source: 'ItemPatch.tags.type', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:type', data: {"name":"Mechanical keyboard v2","price":99.5,"tags":"not-an-array"} }, - { title: '"tags" has more than maxItems 10', source: 'ItemPatch.tags.maxItems', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:maxItems', data: {"name":"Mechanical keyboard v2","price":99.5,"tags":["x","x","x","x","x","x","x","x","x","x","x"]} }, - { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemPatch.additionalProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard v2","price":99.5,"unexpectedField":"api-agent"} }, - { title: 'empty object (minProperties 1)', source: 'ItemPatch.minProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties', data: {} }, ]; for (const c of invalidBodies) { diff --git a/tests/api/items/post/contract.spec.ts b/tests/api/items/post/contract.spec.ts index ce6c540..902c529 100644 --- a/tests/api/items/post/contract.spec.ts +++ b/tests/api/items/post/contract.spec.ts @@ -13,7 +13,8 @@ const rejection = ["400"]; // documented in the spec test.describe('POST /items · contract', { tag: '@contract' }, () => { test('success response matches the documented contract', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_UPN7JLUXYUZ7:contract:positive:response.body#:schema' } }, async ({ api }) => { - const res = await api.items.createItem({ data: resource.newCreatePayload() }); + const payload = resource.newCreatePayload(); + const res = await api.items.createItem({ data: payload }); try { await expectContract(res, 'post', '/items'); } finally { @@ -22,16 +23,23 @@ test.describe('POST /items · contract', { tag: '@contract' }, () => { }); const invalidBodies = [ - { title: 'missing required field "name"', source: 'ItemInput.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required', data: {"price":89.9,"tags":["hardware"]} }, - { title: 'missing required field "price"', source: 'ItemInput.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required', data: {"name":"Mechanical keyboard","tags":["hardware"]} }, + { title: 'missing required field "name"', source: 'ItemInput.name.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required', data: {"price":89.9,"tags":["hardware"]} }, + { title: 'missing required field "price"', source: 'ItemInput.price.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required', data: {"name":"Mechanical keyboard","tags":["hardware"]} }, + { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemInput.additionalProperties', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard","price":89.9,"tags":["hardware"],"__unexpected_field__":"api-agent"} }, { title: '"name" has wrong type (string expected)', source: 'ItemInput.name.type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:type', data: {"name":12345,"price":89.9,"tags":["hardware"]} }, + { title: '"name" is null (not nullable)', source: 'ItemInput.name.nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable', data: {"name":null,"price":89.9,"tags":["hardware"]} }, { title: '"name" shorter than minLength 1', source: 'ItemInput.name.minLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:minLength', data: {"name":"","price":89.9,"tags":["hardware"]} }, { title: '"name" longer than maxLength 100', source: 'ItemInput.name.maxLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:maxLength', data: {"name":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","price":89.9,"tags":["hardware"]} }, { title: '"price" has wrong type (number expected)', source: 'ItemInput.price.type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:type', data: {"name":"Mechanical keyboard","price":"not-a-number","tags":["hardware"]} }, + { title: '"price" is null (not nullable)', source: 'ItemInput.price.nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:nullable', data: {"name":"Mechanical keyboard","price":null,"tags":["hardware"]} }, { title: '"price" below minimum 0', source: 'ItemInput.price.minimum', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:minimum', data: {"name":"Mechanical keyboard","price":-1,"tags":["hardware"]} }, { title: '"tags" has wrong type (array expected)', source: 'ItemInput.tags.type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:type', data: {"name":"Mechanical keyboard","price":89.9,"tags":"not-an-array"} }, - { title: '"tags" has more than maxItems 10', source: 'ItemInput.tags.maxItems', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems', data: {"name":"Mechanical keyboard","price":89.9,"tags":["x","x","x","x","x","x","x","x","x","x","x"]} }, - { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemInput.additionalProperties', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard","price":89.9,"tags":["hardware"],"unexpectedField":"api-agent"} }, + { title: '"tags" is null (not nullable)', source: 'ItemInput.tags.nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:nullable', data: {"name":"Mechanical keyboard","price":89.9,"tags":null} }, + { title: '"tags" has more than maxItems 10', source: 'ItemInput.tags.maxItems', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems', data: {"name":"Mechanical keyboard","price":89.9,"tags":["hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware"]} }, + { title: '"tags[]" has wrong type (string expected)', source: 'ItemInput.tags[].type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:type', data: {"name":"Mechanical keyboard","price":89.9,"tags":[12345]} }, + { title: '"tags[]" is null (not nullable)', source: 'ItemInput.tags[].nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:nullable', data: {"name":"Mechanical keyboard","price":89.9,"tags":[null]} }, + { title: '"tags[]" shorter than minLength 1', source: 'ItemInput.tags[].minLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:minLength', data: {"name":"Mechanical keyboard","price":89.9,"tags":[""]} }, + { title: '"tags[]" longer than maxLength 30', source: 'ItemInput.tags[].maxLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:maxLength', data: {"name":"Mechanical keyboard","price":89.9,"tags":["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"]} }, ]; for (const c of invalidBodies) { diff --git a/tests/api/items/post/functional.spec.ts b/tests/api/items/post/functional.spec.ts index 66a6f56..c7cdb82 100644 --- a/tests/api/items/post/functional.spec.ts +++ b/tests/api/items/post/functional.spec.ts @@ -10,10 +10,12 @@ import * as resource from '../../_support/items.resource.js'; test.describe('POST /items · functional', { tag: '@functional' }, () => { test('creates a resource from the documented example payload', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_UPN7JLUXYUZ7:functional:positive:operation:documented-success' } }, async ({ api }) => { - const res = await api.items.createItem({ data: resource.newCreatePayload() }); + const payload = resource.newCreatePayload(); + const res = await api.items.createItem({ data: payload }); try { expect(res.status(), 'documented success status of createItem').toBe(201); - const id = readPointer(await res.json().catch(() => undefined), '/id'); + const created = await res.json().catch(() => undefined); + const id = readPointer(created, '/id'); expect(String(id ?? ''), 'identifier at $response.body#/id').not.toBe(''); } finally { await resource.removeIfCreated(api, res); diff --git a/tests/api/me/get/functional.spec.ts b/tests/api/me/get/functional.spec.ts index 36dca0a..7928cbc 100644 --- a/tests/api/me/get/functional.spec.ts +++ b/tests/api/me/get/functional.spec.ts @@ -16,4 +16,9 @@ test.describe('GET /me · functional', { tag: '@functional' }, () => { const res = await publicApi.me.getMe(); expectStatus(res, ['401'], 'get', '/me'); }); + + test('returns documented 401 for invalid credentials', { tag: '@negative', annotation: { type: 'caseId', description: 'ata:op_WRZHS7HTMVON:functional:negative:request.security:invalid-credentials' } }, async ({ publicApi }) => { + const res = await publicApi.me.getMe({ headers: {"Authorization":"Bearer api-agent-invalid-token"} }); + expectStatus(res, ['401'], 'get', '/me'); + }); }); diff --git a/tests/fixtures/coverage/kitchen-sink.deps.json b/tests/fixtures/coverage/kitchen-sink.deps.json new file mode 100644 index 0000000..e28e8f3 --- /dev/null +++ b/tests/fixtures/coverage/kitchen-sink.deps.json @@ -0,0 +1,14 @@ +{ + "scenarios": [ + { + "create": "createOrder", + "idFrom": "/id", + "param": "orderId", + "read": "getOrder", + "update": "updateOrder", + "delete": "deleteOrder", + "conflictOn": ["customer"], + "echoes": ["total", "status"] + } + ] +} diff --git a/tests/fixtures/coverage/kitchen-sink.expected-gaps.json b/tests/fixtures/coverage/kitchen-sink.expected-gaps.json new file mode 100644 index 0000000..0ed1f7a --- /dev/null +++ b/tests/fixtures/coverage/kitchen-sink.expected-gaps.json @@ -0,0 +1,9 @@ +{ + "CANNOT_ISOLATE_RULE": 6, + "MISSING_CLEANUP": 1, + "UNCONFIRMED_BUSINESS_RULE": 1, + "UNCOVERED_VARIANT": 2, + "UNREACHABLE_RESPONSE_STATUS": 1, + "UNSAFE_LIVE_CHECK": 1, + "UNSUPPORTED_SCHEMA_KEYWORD": 1 +} diff --git a/tests/fixtures/coverage/kitchen-sink.yaml b/tests/fixtures/coverage/kitchen-sink.yaml new file mode 100644 index 0000000..03864a3 --- /dev/null +++ b/tests/fixtures/coverage/kitchen-sink.yaml @@ -0,0 +1,161 @@ +# Synthetic spec covering as many schema keywords and parameter types as possible (docs/SUPPORT_MATRIX.md). +# Every example is valid, so the sampled payload is valid and each negative case breaks exactly one rule. +openapi: 3.1.0 +info: + title: Kitchen sink + version: '1.0' +security: + - bearer: [] +paths: + /orders: + get: + operationId: listOrders + parameters: + - { name: status, in: query, schema: { type: string, enum: [new, paid] } } + - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 50, multipleOf: 1 } } + - { name: code, in: query, schema: { type: string, pattern: '^[A-Z]{3}$' } } + - { name: since, in: query, schema: { type: string, format: date } } + - { name: tags, in: query, style: form, explode: false, schema: { type: array, items: { type: string }, maxItems: 3, example: [a, b] } } + - { name: ids, in: query, schema: { type: array, items: { type: integer }, uniqueItems: true, example: [1, 2] } } + - { name: X-Request-Id, in: header, required: true, schema: { type: string, format: uuid, example: 00000000-0000-4000-8000-000000000001 } } + - { name: session, in: cookie, schema: { type: string, minLength: 8 } } + responses: + '200': + description: ok + headers: + X-Total-Count: { required: true, schema: { type: integer, minimum: 0 } } + content: + application/json: + schema: { type: array, items: { $ref: '#/components/schemas/Order' } } + '400': { description: invalid } + '401': { description: no or invalid token } + '403': { description: not allowed } + '429': { description: slow down } + post: + operationId: createOrder + requestBody: + required: true + content: + application/json: + schema: { $ref: '#/components/schemas/OrderInput' } + responses: + '201': + description: created + content: + application/json: + schema: { $ref: '#/components/schemas/Order' } + links: + GetOrder: { operationId: getOrder, parameters: { orderId: '$response.body#/id' } } + DeleteOrder: { operationId: deleteOrder, parameters: { orderId: '$response.body#/id' } } + UpdateOrder: { operationId: updateOrder, parameters: { orderId: '$response.body#/id' } } + '400': { description: invalid } + '409': { description: duplicate } + '415': { description: unsupported media type } + /orders/{orderId}: + parameters: + - { name: orderId, in: path, required: true, schema: { type: string, format: uuid } } + get: + operationId: getOrder + responses: + '200': + description: ok + content: + application/json: + schema: { $ref: '#/components/schemas/Order' } + '400': { description: invalid id } + '404': { description: missing } + put: + operationId: updateOrder + parameters: + - { name: If-Match, in: header, schema: { type: string } } + requestBody: + required: true + content: + application/json: + schema: { $ref: '#/components/schemas/OrderInput' } + responses: + '200': + description: updated + content: + application/json: + schema: { $ref: '#/components/schemas/Order' } + '404': { description: missing } + '412': { description: etag mismatch } + '415': { description: unsupported media type } + '418': { description: teapot } + delete: + operationId: deleteOrder + responses: + '204': { description: deleted } + '404': { description: missing } + /orders/{orderId}/cancel: + parameters: + - { name: orderId, in: path, required: true, schema: { type: string, format: uuid, example: 00000000-0000-4000-8000-000000000009 } } + post: + operationId: cancelOrder + responses: + '202': { description: accepted } + '405': { description: method not allowed } +components: + securitySchemes: + bearer: { type: http, scheme: bearer } + schemas: + OrderInput: + type: object + additionalProperties: false + required: [customer, items, total] + properties: + customer: + type: object + required: [name, email] + properties: + name: { type: string, minLength: 2, maxLength: 40, example: Ada } + email: { type: string, format: email, example: ada@example.com } + code: { type: string, pattern: '^[A-Z]{3}$', example: ABC } + address: + type: object + maxProperties: 3 + properties: + city: { type: string, maxLength: 20 } + zip: { type: string } + example: { city: Paris, zip: '75001' } + items: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + type: object + required: [sku, qty] + properties: + sku: { type: string } + qty: { type: integer, minimum: 1, maximum: 10 } + price: { type: number, exclusiveMinimum: 0, exclusiveMaximum: 1000, multipleOf: 0.5 } + example: [{ sku: SKU-1, qty: 2, price: 9.5 }] + total: { type: number, minimum: 0, example: 19 } + status: { type: string, enum: [new, paid], example: new } + priority: { type: integer, enum: [1, 2, 3], example: 1 } + gift: { type: boolean, enum: [false], example: false } + kind: { const: order, example: order } + note: { type: string, example: hi } + comment: { type: [string, 'null'], example: null } + tags: { type: array, items: { type: string, maxLength: 5 }, maxItems: 2, example: [a] } + meta: + type: object + minProperties: 1 + properties: + a: { type: string } + b: { type: string } + example: { a: x, b: y } + payment: + oneOf: + - { type: object, required: [card], properties: { card: { type: string } } } + - { type: object, required: [iban], properties: { iban: { type: string } } } + example: { card: '4111' } + Order: + allOf: + - $ref: '#/components/schemas/OrderInput' + - type: object + required: [id] + properties: + id: { type: string, format: uuid, readOnly: true } diff --git a/tests/unit/body-cases.test.ts b/tests/unit/body-cases.test.ts new file mode 100644 index 0000000..bcfd428 --- /dev/null +++ b/tests/unit/body-cases.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from 'vitest'; +import { readFile, mkdtemp } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import * as addFormatsModule from 'ajv-formats'; +import { parse } from 'yaml'; +import { bodyCasesDetailed } from '../../src/generate/body-cases.js'; +import { sampleFromSchema } from '../../src/generate/sample.js'; +import { generate, findPython } from '../../src/generate/generate.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { loadSpec } from '../../src/spec/loader.js'; +import { ARRAY, bodyPointer, parseCaseId } from '../../src/cases/ids.js'; +import { operationUid } from '../../src/change/normalize.js'; + +const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; +const doc = parse(await readFile('tests/fixtures/coverage/kitchen-sink.yaml', 'utf8')); +const schemaRef = { $ref: '#/components/schemas/OrderInput' }; +const sample = sampleFromSchema(doc, schemaRef); +if (!sample.ok) throw new Error(sample.reason); +const base = sample.value as Record; + +const ajv = new Ajv2020({ allErrors: true, strict: false }); +addFormats(ajv); +ajv.addSchema({ ...doc, $id: 'doc' }); +const validate = ajv.compile({ $ref: 'doc#/components/schemas/OrderInput' }); + +/** The instance path ajv reports for a rule at a case path (array elements are index 0). */ +const instancePath = (path: (string | typeof ARRAY)[]) => path.map((p) => '/' + (p === ARRAY ? '0' : String(p).replace(/~/g, '~0').replace(/\//g, '~1'))).join(''); + +describe('stage 3: recursive request-body cases', () => { + const r = bodyCasesDetailed(doc, schemaRef, base, 'OrderInput', 500); + + it('the sampled base payload is valid', () => { + expect(validate(base), JSON.stringify(validate.errors)).toBe(true); + }); + + it('every case breaks exactly one rule: one ajv error, the expected keyword, at the expected place', () => { + expect(r.cases.length).toBeGreaterThan(30); + for (const c of r.cases) { + const t = c.target as { in: 'body'; path: (string | typeof ARRAY)[]; rule: string }; + expect(validate(c.data), `${c.title} should be invalid`).toBe(false); + const errors = validate.errors ?? []; + expect(errors.length, `${c.title}: ${JSON.stringify(errors)}`).toBe(1); + const e = errors[0]; + const keyword = t.rule === 'nullable' ? 'type' : t.rule; + expect(e.keyword, c.title).toBe(keyword); + if (t.rule === 'required') { + expect(e.instancePath, c.title).toBe(instancePath(t.path.slice(0, -1))); + expect(e.params.missingProperty, c.title).toBe(t.path[t.path.length - 1]); + } else expect(e.instancePath, c.title).toBe(instancePath(t.path)); + } + }); + + it('covers nested objects, array items and every supported keyword', () => { + const got = new Set(r.cases.map((c) => `${bodyPointer((c.target as any).path)}:${c.target!.rule}`)); + for (const want of [ + '/customer:type', '/customer/name:required', '/customer/name:minLength', '/customer/name:maxLength', '/customer/name:nullable', + '/customer/email:format', '/customer/code:pattern', '/customer/address:maxProperties', '/customer/address/city:maxLength', + '/items:minItems', '/items:uniqueItems', '/items/*/sku:required', '/items/*/qty:minimum', '/items/*/qty:maximum', + '/items/*/price:exclusiveMinimum', '/items/*/price:exclusiveMaximum', '/items/*/price:multipleOf', + '/total:minimum', '/status:enum', '/priority:enum', '/gift:enum', '/kind:const', '/tags/*:maxLength', '/tags:maxItems', + '/meta:minProperties', ':additionalProperties', + ]) expect(got, want).toContain(want); + expect(got).not.toContain('/comment:nullable'); // null is allowed there + }); + + it('cannot-isolate and unsupported rules are coverage gaps with code and exact location', () => { + const gaps = r.gaps.map((g) => `${g.code} ${g.location} ${g.rule ?? ''}`.trim()); + expect(gaps).toContain('UNSUPPORTED_SCHEMA_KEYWORD request.body#/payment oneOf'); + expect(gaps).toContain('CANNOT_ISOLATE_RULE request.body#/items maxItems'); // repeating would break uniqueItems + expect(gaps).toContain('CANNOT_ISOLATE_RULE request.body#/status type'); // the enum case covers it + }); + + it('the case limit is reported, not silent', () => { + const limited = bodyCasesDetailed(doc, schemaRef, base, 'OrderInput', 5); + expect(limited.cases).toHaveLength(5); + expect(limited.potential).toBe(r.cases.length); + expect(limited.dropped).toHaveLength(r.cases.length - 5); + expect(limited.gaps.filter((g) => g.code === 'CASE_LIMIT_REACHED')).toHaveLength(r.cases.length - 5); + }); + + it('generated suites: nested pointers in case IDs, same cases in TypeScript and Python, gaps in coverage', async () => { + const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); + const ops = buildCatalog(spec.doc); + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-ks-')); + const res = await generate(spec, ops, { outDir: dir, version: 'test', lang, maxCases: 500 }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')) }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const uid = operationUid('POST', '/orders'); + expect(ts.reg.cases[`ata:${uid}:contract:negative:request.body#/items/*/price:multipleOf`]).toBeDefined(); + expect(ts.reg.cases[`ata:${uid}:contract:negative:request.body#/customer/address/city:maxLength`]).toBeDefined(); + for (const id of Object.keys(ts.reg.cases)) expect(parseCaseId(id).ok, id).toBe(true); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + const cov = ts.res.coverage.find((c) => c.operation === 'POST /orders')!; + expect(cov.bodyCases).toEqual({ potential: r.cases.length, generated: r.cases.length, dropped: 0 }); + expect(cov.gaps.some((g) => g.code === 'UNSUPPORTED_SCHEMA_KEYWORD' && g.location === 'request.body#/payment')).toBe(true); + const pyFile = join(py.dir, 'orders/post/test_contract.py'); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', pyFile], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); +}); diff --git a/tests/unit/cases.test.ts b/tests/unit/cases.test.ts index 16b0546..6062de0 100644 --- a/tests/unit/cases.test.ts +++ b/tests/unit/cases.test.ts @@ -8,7 +8,7 @@ import { stringify, parse } from 'yaml'; import { loadSpec } from '../../src/spec/loader.js'; import { buildCatalog } from '../../src/spec/catalog.js'; import { generate, findPython } from '../../src/generate/generate.js'; -import { ARRAY, bodyPointer, encodeSegment, parseCaseId, scenarioUid } from '../../src/cases/ids.js'; +import { ARRAY, CASE_RULE_VOCABULARY_VERSION, bodyPointer, encodeSegment, parseCaseId, scenarioUid } from '../../src/cases/ids.js'; import { canonicalJson } from '../../src/cases/registry.js'; import { validateManifest, validateRegistry } from '../../src/cases/validate.js'; import { normalizeSpec, operationUid } from '../../src/change/normalize.js'; @@ -69,7 +69,7 @@ describe('generated suites carry case IDs', () => { expect((text.match(/ test\(/g) ?? []).length, f).toBe((text.match(/annotation: \{ type: 'caseId'/g) ?? []).length); } const reg = await registry(); - expect(reg.caseRuleVocabularyVersion).toBe(1); + expect(reg.caseRuleVocabularyVersion).toBe(CASE_RULE_VOCABULARY_VERSION); expect(reg.operations[uid]).toEqual({ method: 'GET', path: '/items/{itemId}', normalizedPath: '/items/{}', operationId: 'getItem' }); const covers = reg.cases[`ata:${operationUid('POST', '/items')}:contract:positive:response.body#:schema`].covers; expect(covers).toEqual(['contract:positive:response.content-type#/application~1json:documented', 'contract:positive:response.status#/201:documented']); @@ -156,7 +156,7 @@ describe('registry validate', () => { reg.operations.op_AAAAAAAAAAAA = { method: 'GET', path: '/gone', normalizedPath: '/gone', status: 'retired' }; const codes = run(reg).errors.map((e) => e.code); for (const c of ['CASE_ENTRY_MISMATCH', 'CASE_SUBJECT_NOT_FOUND', 'INVALID_SCENARIO', 'DUPLICATE_API_TEST_AGENT_ID', 'ALIAS_CYCLE', 'INVALID_TOMBSTONE']) expect(codes, c).toContain(c); - expect(run({ ...(await base()), caseRuleVocabularyVersion: 2 }).blocked.map((x) => x.code)).toEqual(['UNSUPPORTED_CASE_RULE_VOCABULARY']); + expect(run({ ...(await base()), caseRuleVocabularyVersion: CASE_RULE_VOCABULARY_VERSION + 1 }).blocked.map((x) => x.code)).toEqual(['UNSUPPORTED_CASE_RULE_VOCABULARY']); }); it('with a spec: missing operations, unknown fields and parameters, wildcards on non-arrays, rules that do not fit', async () => { diff --git a/tests/unit/core.test.ts b/tests/unit/core.test.ts index b875555..cdad314 100644 --- a/tests/unit/core.test.ts +++ b/tests/unit/core.test.ts @@ -127,7 +127,8 @@ describe('safety helpers', () => { }); import { operationFolder } from '../../src/generate/templates.js'; -import { bodyCases, documentedRejections, queryCases } from '../../src/generate/negative.js'; +import { bodyCases, documentedRejections } from '../../src/generate/negative.js'; +import { paramCasesDetailed } from '../../src/generate/param-cases.js'; describe('test layout', () => { it('puts each operation in /[-by-id]', () => { @@ -150,7 +151,8 @@ describe('negative cases', () => { }); it('derives query cases from parameter bounds', () => { - expect(queryCases(op('GET /items')).map((c) => c.query)).toEqual([{ limit: 'abc' }, { limit: 0 }, { limit: 101 }]); + 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 }]); }); it('breaks exclusive bounds, minItems and query minLength, one rule per case', () => { @@ -172,9 +174,9 @@ describe('negative cases', () => { { name: 'q', in: 'query', required: false, schema: { type: 'string', minLength: 3 } }, ], } as any; - const q = queryCases(search); - expect(q.find((c) => c.source === 'query.page.exclusiveMinimum')?.query).toEqual({ page: 0 }); - expect(q.find((c) => c.source === 'query.q.minLength')?.query).toEqual({ q: 'xx' }); + const q = paramCasesDetailed(demo.doc, search, { allowPath: true, allowOthers: true }).cases; + expect(q.find((c) => c.source === 'query.page.exclusiveMinimum')?.request?.params).toEqual({ page: 0 }); + expect(q.find((c) => c.source === 'query.q.minLength')?.request?.params).toEqual({ q: 'xx' }); }); it('only uses rejections the spec documents', () => { @@ -394,7 +396,7 @@ describe('unique values for operations that document 409', () => { expect(helper).toContain('POST /items documents 409 (conflict): name get a unique suffix'); expect(helper).toContain('export const newCreatePayload = () => unique(createPayload, {"name":100});'); expect(helper).toContain('data: unknown = newCreatePayload()'); - expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('{ data: resource.newCreatePayload() }'); + expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('const payload = resource.newCreatePayload();'); const scenario = await readFileP(joinP(dir, 'items/patch-by-id/scenarios.spec.ts'), 'utf8'); expect(scenario).toMatch(/const payload = resource\.newUpdatePayload\(\);[\s\S]*toMatchObject\(payload\);/); @@ -402,7 +404,7 @@ describe('unique values for operations that document 409', () => { await generate({ ...demo, doc: d } as any, buildCatalog(d), { outDir: py, version: 'test', lang: 'python' }); const pyHelper = await readFileP(joinP(py, '_support/items_resource.py'), 'utf8'); expect(pyHelper).toContain('UNIQUE_CREATE = {\n "name": 100,\n}'); - expect(await readFileP(joinP(py, 'items/post/test_functional.py'), 'utf8')).toContain('json=items.new_create_payload()'); + expect(await readFileP(joinP(py, 'items/post/test_functional.py'), 'utf8')).toContain('payload = items.new_create_payload()'); }); }); @@ -488,7 +490,7 @@ describe('deps "fill": values from existing data', () => { expect(helper).toContain("payload['name'] = readPointer(await source0.json(), '/status');"); expect(helper).toContain('unique(createPayload, {})'); // name is filled, not suffixed, despite the documented 409 expect(helper).toContain('data ??= await newCreatePayload(api);'); - expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('{ data: await resource.newCreatePayload(api) }'); + expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('const payload = await resource.newCreatePayload(api);'); const py = await mkdtemp(joinP(tmpdir(), 'ata-fill-py-')); await generate(spec, buildCatalog(d), { outDir: py, version: 'test', lang: 'python', deps: deps({ name: { from: 'getHealth', pointer: '/status' } }) }); diff --git a/tests/unit/coverage-report.test.ts b/tests/unit/coverage-report.test.ts new file mode 100644 index 0000000..ef3965c --- /dev/null +++ b/tests/unit/coverage-report.test.ts @@ -0,0 +1,63 @@ +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 { GAP_CODES, positiveCode, summarize } from '../../src/generate/coverage.js'; +import { validateScenarios } from '../../src/scenarios/dsl.js'; + +/** Stage 10 (docs/SUPPORT_MATRIX.md): coverage reporting with machine codes. */ + +async function run(file: string, deps?: string, scenarios?: string) { + const spec = await loadSpec(file); + const ops = buildCatalog(spec.doc); + const sc = scenarios ? validateScenarios(JSON.parse(await readFile(scenarios, 'utf8')), ops).scenarios : undefined; + return generate(spec, ops, { outDir: await mkdtemp(join(tmpdir(), 'ata-cov-')), version: 'test', deps: deps ? JSON.parse(await readFile(deps, 'utf8')) : undefined, maxCases: 500, scenarios: sc }); +} + +describe('stage 10: coverage report', () => { + it('every gap and every empty suite has a known machine code', async () => { + const r = await run('tests/fixtures/coverage/kitchen-sink.yaml', 'tests/fixtures/coverage/kitchen-sink.deps.json'); + for (const c of r.coverage) { + for (const g of c.gaps) expect(GAP_CODES, `${c.operation} ${g.location}`).toContain(g.code); + for (const s of Object.values(c.suites)) if (s.missingCode) expect(GAP_CODES).toContain(s.missingCode); + for (const u of c.uncheckedStatuses) expect(GAP_CODES).toContain(u.code); + if (c.positiveBlocked) expect(c.positiveBlockedCode).not.toBeNull(); + } + }); + + it('the synthetic fixture has exactly the expected gaps (a new or vanished gap fails)', async () => { + const r = await run('tests/fixtures/coverage/kitchen-sink.yaml', 'tests/fixtures/coverage/kitchen-sink.deps.json'); + expect(summarize(r.coverage)).toEqual(JSON.parse(await readFile('tests/fixtures/coverage/kitchen-sink.expected-gaps.json', 'utf8'))); + }); + + it('the demo API has exactly the expected gaps', async () => { + const r = await run('demo-api/openapi.yaml', undefined, 'demo-api/scenarios.json'); + expect(summarize(r.coverage)).toEqual(JSON.parse(await readFile('demo-api/expected-gaps.json', 'utf8'))); + }); + + it('reports unchecked statuses, request media types and security alternatives', async () => { + const r = await run('tests/fixtures/coverage/kitchen-sink.yaml', 'tests/fixtures/coverage/kitchen-sink.deps.json'); + const list = r.coverage.find((c) => c.operation === 'GET /orders')!; + expect(list.uncheckedStatuses).toEqual([ + { status: '403', code: 'UNCONFIRMED_BUSINESS_RULE' }, + { status: '429', code: 'UNSAFE_LIVE_CHECK' }, + ]); + const update = r.coverage.find((c) => c.operation === 'PUT /orders/{orderId}')!; + expect(update.uncheckedStatuses).toEqual([{ status: '418', code: 'UNREACHABLE_RESPONSE_STATUS' }]); + const multi = { ...buildCatalog((await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml')).doc)[0], requestContentTypes: ['application/json', 'multipart/form-data'], security: [['bearer'], ['apiKey']] } as any; + const { uncheckedRequest } = await import('../../src/generate/coverage.js'); + expect(uncheckedRequest(multi)).toEqual({ contentTypes: ['multipart/form-data'], securityAlternatives: [['apiKey']] }); + }); + + it('positive-blocked reasons map to codes', () => { + expect(positiveCode('POST /x changes data and has no confirmed precondition/cleanup (no OpenAPI links or deps file).')).toBe('MISSING_CLEANUP'); + expect(positiveCode('Path "id" would come from a spec example, not from a real record')).toBe('MISSING_RESOURCE_SOURCE'); + expect(positiveCode('No example-backed payload for PUT /x')).toBe('MISSING_VALID_SAMPLE'); + expect(positiveCode('GET /logout ends the session shared by the other tests')).toBe('UNSAFE_LIVE_CHECK'); + expect(positiveCode('Operation is deprecated.')).toBe('DEPRECATED_OPERATION'); + expect(positiveCode(undefined)).toBeNull(); + }); +}); diff --git a/tests/unit/coverage.test.ts b/tests/unit/coverage.test.ts new file mode 100644 index 0000000..1335d5f --- /dev/null +++ b/tests/unit/coverage.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { parse, stringify } from 'yaml'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { checkCaseIds, findPython, generate } from '../../src/generate/generate.js'; +import { parseCaseId } from '../../src/cases/ids.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { canonicalJson } from '../../src/cases/registry.js'; +import { normalizeSpec, operationUid } from '../../src/change/normalize.js'; + +/** + * Coverage completeness (docs/SUPPORT_MATRIX.md): one physical test → one stable case ID, + * the same cases in TypeScript and Python. + */ + +const demo = await loadSpec('demo-api/openapi.yaml'); + +async function gen(doc: any, lang: 'typescript' | 'python' = 'typescript') { + const dir = await mkdtemp(join(tmpdir(), 'ata-cov-')); + const r = await generate({ ...demo, doc } as any, buildCatalog(doc), { outDir: dir, version: 'test', lang }); + const read = (f: string) => readFile(join(dir, f), 'utf8'); + return { dir, r, read, registry: async () => JSON.parse(await read('_support/cases.json')) }; +} + +/** Case IDs written into a generated file: annotations / caseId fields (TS) or api_case_id markers (Python). */ +const idsIn = (text: string) => [...text.matchAll(/(?:description: |caseId: )'([^']+)'|api_case_id\("([^"]+)"\)/g)].map((m) => m[1] ?? m[2]).filter((x) => x !== 'c.caseId'); + +describe('stage 2: one case ID per physical test', () => { + const withSort = () => { + const d = parse(stringify(demo.doc)); + d.paths['/items'].get.parameters.push({ name: 'sort', in: 'query', required: false, schema: { type: 'string', enum: ['asc', 'desc', 'asc'] } }); + d.paths['/items'].get.parameters.push({ name: 'flag', in: 'query', required: false, schema: { enum: [true, 'true', 1] } }); + return d; + }; + + it('each documented query value is its own test with its own accepted-value case ID (duplicates as strings dropped)', async () => { + const { read, registry } = await gen(withSort()); + const text = await read('items/get/functional.spec.ts'); + const uid = operationUid('GET', '/items'); + for (const v of ['asc', 'desc', 'true', '1']) { + const loc = v === 'asc' || v === 'desc' ? `request.query#/sort/${v}` : `request.query#/flag/${v}`; + expect(text).toContain(`'ata:${uid}:functional:positive:${loc}:accepted-value'`); + } + expect(text.match(/accepts documented flag=/g)).toHaveLength(2); // true and "true" are one value + const ids = idsIn(text); + expect(new Set(ids).size).toBe(ids.length); + const reg = await registry(); + for (const id of ids) expect(reg.cases[id], id).toBeDefined(); + expect(validateRegistry(await read('_support/cases.json'), normalizeSpec(stringify(withSort()), 'x')).errors).toEqual([]); + }); + + it('Python renders the same values, each pytest.param with its own case ID', async () => { + const ts = await gen(withSort()); + const py = await gen(withSort(), 'python'); + 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):'); + 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); + }); + + it('TypeScript and Python register the same cases for the demo API', async () => { + const ts = await gen(demo.doc); + const py = await gen(demo.doc, 'python'); + expect(Object.keys((await py.registry()).cases).sort()).toEqual(Object.keys((await ts.registry()).cases).sort()); + }); + + it('accepted-value: a value the spec does not document is an invalid location', () => { + const d = withSort(); + const uid = operationUid('GET', '/items'); + const id = `ata:${uid}:functional:positive:request.query#/sort/random:accepted-value`; + const parsed = parseCaseId(id); + expect(parsed.ok).toBe(true); + const reg = { schemaVersion: 1, caseRuleVocabularyVersion: 2, operations: { [uid]: { method: 'GET', path: '/items', normalizedPath: '/items' } }, cases: { [id]: (parsed as any).parts }, scenarios: {}, externalIdAliases: {}, externalScenarioIdAliases: {} }; + expect(validateRegistry(canonicalJson(reg), normalizeSpec(stringify(d), 'x')).errors.map((e) => e.code)).toEqual(['INVALID_CASE_LOCATION']); + expect(parseCaseId(`ata:${uid}:functional:positive:request.query#/sort:accepted-value`).ok).toBe(false); // needs a value + expect(parseCaseId(`ata:${uid}:contract:negative:request.query#/sort/asc:enum`).ok).toBe(false); // constraint rules: one segment + }); + + it('a case the generator no longer produces becomes a tombstone; producing it again reactivates it', async () => { + const { dir } = await gen(withSort()); + const uid = operationUid('GET', '/items'); + const id = `ata:${uid}:functional:positive:request.query#/sort/desc:accepted-value`; + const without = withSort(); + without.paths['/items'].get.parameters.find((p: any) => p.name === 'sort').schema.enum = ['asc']; + await generate({ ...demo, doc: without } as any, buildCatalog(without), { outDir: dir, version: 'test' }); + const reg1 = JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')); + expect(reg1.cases[id].status).toBe('retired'); + await generate({ ...demo, doc: withSort() } as any, buildCatalog(withSort()), { outDir: dir, version: 'test' }); + const reg2 = JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')); + expect(reg2.cases[id].status).toBeUndefined(); + }); + + it('checkCaseIds reports tests without an ID, shared IDs and unregistered IDs', () => { + const r = checkCaseIds( + [ + { test: 'a', caseId: 'x' }, + { test: 'b', caseId: 'x' }, + { test: 'c', caseId: null }, + { test: 'd', caseId: 'y' }, + ], + new Set(['x']), + ); + expect(r).toEqual({ tests: 4, missing: ['c'], duplicates: ['x'], unregistered: ['y'] }); + }); +}); diff --git a/tests/unit/error-cases.test.ts b/tests/unit/error-cases.test.ts new file mode 100644 index 0000000..6b0cd1e --- /dev/null +++ b/tests/unit/error-cases.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { errorPlan } from '../../src/generate/error-cases.js'; +import { operationUid, normalizeSpec } from '../../src/change/normalize.js'; +import { validateRegistry } from '../../src/cases/validate.js'; + +/** Stage 6 (docs/SUPPORT_MATRIX.md): documented error responses. */ + +const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); +const ops = buildCatalog(spec.doc); +const op = (key: string) => ops.find((o) => o.key === key)!; +const deps = { scenarios: [{ create: 'createOrder', idFrom: '/id', param: 'orderId', read: 'getOrder', update: 'updateOrder', delete: 'deleteOrder', conflictOn: ['customer'] }] }; + +describe('stage 6: documented error responses', () => { + it('plans only safe triggers; the rest are gaps with codes', () => { + const list = errorPlan({ doc: spec.doc, op: op('GET /orders'), ops, reachable: true, hasUpdatePayload: false, firstWith405: false }); + expect(list.invalidCredentials).toEqual({ headers: { Authorization: 'Bearer api-agent-invalid-token' }, params: {} }); + expect(list.gaps.map((g) => `${g.code} ${g.location}`)).toEqual(['UNCONFIRMED_BUSINESS_RULE response.status#/403', 'UNSAFE_LIVE_CHECK response.status#/429']); + + const cancel = errorPlan({ doc: spec.doc, op: op('POST /orders/{orderId}/cancel'), ops, reachable: false, hasUpdatePayload: false, firstWith405: true }); + expect(cancel.methodNotAllowed).toEqual({ method: 'get' }); // the path defines no GET + + const create = errorPlan({ doc: spec.doc, op: op('POST /orders'), ops, reachable: true, hasUpdatePayload: false, firstWith405: false, role: 'create' }); + expect(create.unsupportedMediaType).toBe(true); + expect(create.conflict).toBeUndefined(); // no conflictOn in a reviewed deps file + expect(create.gaps).toContainEqual(expect.objectContaining({ code: 'UNCONFIRMED_BUSINESS_RULE', location: 'response.status#/409' })); + + const update = errorPlan({ doc: spec.doc, op: op('PUT /orders/{orderId}'), ops, reachable: true, hasUpdatePayload: true, firstWith405: false, role: 'update' }); + expect(update.preconditionFailed).toEqual({ header: 'If-Match', value: '"api-agent-no-such-etag"' }); + expect(update.gaps).toContainEqual(expect.objectContaining({ code: 'UNREACHABLE_RESPONSE_STATUS', location: 'response.status#/418' })); + }); + + it('405 is never sent as an unsafe method: a path with GET gets a gap', () => { + const del = { ...op('DELETE /orders/{orderId}'), responses: [...op('DELETE /orders/{orderId}').responses, { status: '405', contentTypes: [], hasSchema: false }] }; + const r = errorPlan({ doc: spec.doc, op: del, ops, reachable: true, hasUpdatePayload: false, firstWith405: true }); + expect(r.methodNotAllowed).toBeUndefined(); + expect(r.gaps).toContainEqual(expect.objectContaining({ code: 'UNSAFE_LIVE_CHECK', location: 'response.status#/405' })); + }); + + it('generated suites: the same error cases in TypeScript and Python, each with its own ID; cleanup in finally', async () => { + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-err-')); + const res = await generate(spec, ops, { outDir: dir, version: 'test', lang, deps }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const list = operationUid('GET', '/orders'); + const put = operationUid('PUT', '/orders/{}'); + const post = operationUid('POST', '/orders'); + const cancel = operationUid('POST', '/orders/{}/cancel'); + for (const id of [ + `ata:${list}:functional:negative:request.security:invalid-credentials`, + `ata:${cancel}:functional:negative:operation:method-not-allowed`, + `ata:${put}:functional:negative:request.header#/if-match:precondition-failed`, + `ata:${post}:contract:negative:request.content-type:content-type`, + `ata:${put}:contract:negative:request.content-type:content-type`, + ]) expect(ts.reg.cases[id], id).toBeDefined(); + const conflict = Object.entries(ts.reg.cases).find(([, c]) => c.rule === 'business-rule' && c.polarity === 'negative' && ts.reg.scenarios[c.subjectUid]?.scenarioType === 'business'); + expect(conflict, 'conflict scenario').toBeDefined(); + expect(ts.reg.scenarios[conflict![1].subjectUid]).toMatchObject({ scenarioType: 'business', primaryOperationUid: post }); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + expect(validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('tests/fixtures/coverage/kitchen-sink.yaml', 'utf8'), 'ks')).errors).toEqual([]); + + const scenario = await ts.read('orders/post/scenarios.spec.ts'); + expect(scenario).toMatch(/const first = await resource\.create\(api, payload\);[\s\S]*expectStatus\(res, \['409'\][\s\S]*finally \{\s*await resource\.removeIfCreated\(api, res\);[\s\S]*finally \{\s*await resource\.remove\(api, first\.id\);/); + expect(await ts.read('orders/get/functional.spec.ts')).toContain(`"Authorization":"Bearer api-agent-invalid-token"`); + const cancelFile = await ts.read('orders-cancel/post/functional.spec.ts'); + expect(cancelFile).toContain(`await request.get('orders/00000000-0000-4000-8000-000000000009/cancel')`); + expect(cancelFile).toContain(`expectStatus(res, ['405']`); + expect(cancelFile).not.toMatch(/request\.(post|put|patch|delete)\(/); // never an unsafe method + const cov = ts.res.coverage.find((c) => c.operation === 'GET /orders')!; + expect(cov.gaps.map((g) => g.code)).toEqual(expect.arrayContaining(['UNCONFIRMED_BUSINESS_RULE', 'UNSAFE_LIVE_CHECK'])); + + const pyFiles = py.res.files.filter((f) => f.endsWith('.py')); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', ...pyFiles], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + expect(await py.read('orders/post/test_scenarios.py')).toContain('def test_second_create_with_the_same_fields_conflicts(api, orders):'); + }); +}); diff --git a/tests/unit/functional-variants.test.ts b/tests/unit/functional-variants.test.ts new file mode 100644 index 0000000..9e8e5d8 --- /dev/null +++ b/tests/unit/functional-variants.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { boundaryValues } from '../../src/generate/boundaries.js'; +import { sampleFromSchema } from '../../src/generate/sample.js'; +import { operationUid } from '../../src/change/normalize.js'; + +/** Stage 7 (docs/SUPPORT_MATRIX.md): functional assertions and valid-data variants. */ + +const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); +const ops = buildCatalog(spec.doc); +const deps = JSON.parse(await readFile('tests/fixtures/coverage/kitchen-sink.deps.json', 'utf8')); + +describe('stage 7: valid limits, sampler fixes, confirmed functional assertions', () => { + it('boundary-valid values respect exclusive bounds, multipleOf and lengths', () => { + expect(boundaryValues({ type: 'integer', minimum: 1, maximum: 50 })).toEqual([1, 50]); + expect(boundaryValues({ type: 'integer', exclusiveMinimum: 0, exclusiveMaximum: 10 })).toEqual([1, 9]); + expect(boundaryValues({ type: 'number', minimum: 0.5, maximum: 10, multipleOf: 0.5 })).toEqual([0.5, 10]); + expect(boundaryValues({ type: 'integer', minimum: 1, maximum: 10, multipleOf: 4 })).toEqual([]); // no limit is itself a multiple + expect(boundaryValues({ type: 'string', minLength: 2, maxLength: 5 })).toEqual(['xx', 'xxxxx']); + expect(boundaryValues({ type: 'string', minLength: 2, pattern: '^a+$' })).toEqual([]); // never break a pattern + expect(boundaryValues({ type: 'string', maxLength: 500 })).toEqual([]); // too long for a readable case ID + }); + + it('sampler: multipleOf, exclusive bounds (3.0 and 3.1), distinct items for uniqueItems', () => { + const s = (schema: any) => (sampleFromSchema({}, schema) as any).value; + expect(s({ type: 'number', minimum: 1, multipleOf: 0.75 })).toBe(1.5); + expect(s({ type: 'integer', minimum: 3, exclusiveMinimum: true })).toBe(4); + expect(s({ type: 'integer', minimum: 1, exclusiveMinimum: 5 })).toBe(6); + expect(s({ type: 'array', minItems: 3, uniqueItems: true, items: { type: 'string' } })).toEqual(['api-agent', 'api-agent-1', 'api-agent-2']); + expect(s({ type: 'array', minItems: 2, uniqueItems: true, items: { type: 'integer', minimum: 5 } })).toEqual([5, 6]); + expect(sampleFromSchema({}, { type: 'array', minItems: 3, uniqueItems: true, items: { type: 'boolean' } }).ok).toBe(false); + expect((sampleFromSchema({}, { type: 'integer', minimum: 1, maximum: 3, multipleOf: 5 }) as any).ok).toBe(false); + }); + + it('generated: one accepted-value test per limit, echoes from the deps file, the uncovered oneOf variant as a gap; TS and Python agree', async () => { + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-fv-')); + const res = await generate(spec, ops, { outDir: dir, version: 'test', lang, deps, maxCases: 500 }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const list = operationUid('GET', '/orders'); + for (const v of ['1', '50']) expect(ts.reg.cases[`ata:${list}:functional:positive:request.query#/limit/${v}:accepted-value`], v).toBeDefined(); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + + const create = await ts.read('orders/post/functional.spec.ts'); + expect(create).toContain(`expect(readPointer(created, '/total'), 'total returned as sent').toEqual((payload as Record)['total']);`); + expect(create).toContain(`expect(readPointer(created, '/status'), 'status returned as sent')`); + expect(await py.read('orders/post/test_functional.py')).toContain(`assert read_pointer(res.json(), "/total") == payload["total"], "total returned as sent"`); + + const cov = ts.res.coverage.find((c) => c.operation === 'POST /orders')!; + expect(cov.gaps).toContainEqual(expect.objectContaining({ code: 'UNCOVERED_VARIANT', location: 'request.body#/payment' })); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', ...py.res.files.filter((f) => f.endsWith('.py'))], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); +}); diff --git a/tests/unit/param-cases.test.ts b/tests/unit/param-cases.test.ts new file mode 100644 index 0000000..6333094 --- /dev/null +++ b/tests/unit/param-cases.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import * as addFormatsModule from 'ajv-formats'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { paramCasesDetailed, requiredRequest } from '../../src/generate/param-cases.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { operationUid } from '../../src/change/normalize.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { normalizeSpec } from '../../src/change/normalize.js'; +import type { ParamInfo } from '../../src/types.js'; + +/** Stage 4 (docs/SUPPORT_MATRIX.md): query, header, cookie and path parameter cases. */ + +const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; +const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); +const ops = buildCatalog(spec.doc); +const op = (key: string) => ops.find((o) => o.key === key)!; +const ajv = new Ajv2020({ allErrors: true, strict: false, coerceTypes: true }); +addFormats(ajv); + +/** The value each parameter has in a case's request (query object or string, headers, Cookie, path). */ +function valueOf(p: ParamInfo, req: { params?: any; headers?: Record; path?: Record }): unknown { + if (p.in === 'path') return req.path?.[p.name] ?? p.knownValue; + if (p.in === 'header') return Object.entries(req.headers ?? {}).find(([k]) => k.toLowerCase() === p.name.toLowerCase())?.[1]; + if (p.in === 'cookie') return (req.headers?.Cookie ?? '').split('; ').find((c) => c.startsWith(`${p.name}=`))?.slice(p.name.length + 1); + if (typeof req.params === 'string') { + const all = new URLSearchParams(req.params).getAll(p.name); + if (!all.length) return undefined; + // form + explode: false → one comma-separated value + return (p.schema as any)?.type === 'array' ? (p.explode === false ? all[0].split(',') : all) : all[0]; + } + const v = req.params?.[p.name]; + return (p.schema as any)?.type === 'array' && v !== undefined && !Array.isArray(v) ? [v] : v; +} +const valid = (p: ParamInfo, v: unknown) => (v === undefined ? !p.required : ajv.validate(p.schema ?? {}, Array.isArray(v) ? v.map((x) => (/^-?\d+$/.test(String(x)) ? Number(x) : x)) : /^-?\d+(\.\d+)?$/.test(String(v)) && ['integer', 'number'].includes((p.schema as any)?.type) ? Number(v) : v)); + +describe('stage 4: parameter cases', () => { + const list = op('GET /orders'); + const r = paramCasesDetailed(spec.doc, list, { allowPath: true, allowOthers: true }); + + it('every request is valid except the one parameter under test, which breaks its rule', () => { + expect(r.cases.length).toBeGreaterThan(10); + for (const c of r.cases) { + const t = c.target as { in: string; field: string; rule: string }; + for (const p of list.params) { + const v = valueOf(p, c.request!); + const isTarget = p.in === t.in && p.name === t.field; + if (isTarget) expect(valid(p, v), `${c.title}: ${p.name}=${JSON.stringify(v)} should break ${t.rule}`).toBe(false); + else expect(valid(p, v), `${c.title}: ${p.in} ${p.name}=${JSON.stringify(v)} should stay valid`).toBe(true); + } + } + }); + + it('covers query, header and cookie rules; arrays use the documented style', () => { + const got = new Set(r.cases.map((c) => `${(c.target as any).in}.${(c.target as any).field}:${c.target!.rule}`)); + for (const want of ['query.status:enum', 'query.limit:type', 'query.limit:minimum', 'query.limit:maximum', 'query.code:pattern', 'query.since:format', 'query.tags:maxItems', 'query.ids:uniqueItems', 'header.X-Request-Id:required', 'header.X-Request-Id:format', 'cookie.session:minLength']) { + expect(got, want).toContain(want); + } + const tags = r.cases.find((c) => c.source === 'query.tags.maxItems')!; + expect(tags.request!.params).toBe('tags=a,b,a,b'); // form, explode: false + const ids = r.cases.find((c) => c.source === 'query.ids.uniqueItems')!; + expect(ids.request!.params).toBe('ids=1&ids=1'); // form, explode: true (default) + expect(r.cases.find((c) => c.source === 'header.X-Request-Id.required')!.request!.headers).toBeUndefined(); + expect(r.cases.find((c) => c.source === 'cookie.session.minLength')!.request!.headers).toMatchObject({ Cookie: 'session=xxxxxxx' }); + }); + + it('every case carries the required header with its documented value, except the case that removes it', () => { + expect(requiredRequest(list).headers).toEqual({ 'X-Request-Id': '00000000-0000-4000-8000-000000000001' }); + for (const c of r.cases.filter((x) => x.source !== 'header.X-Request-Id.required' && !x.source.startsWith('header.'))) expect(c.request!.headers?.['X-Request-Id'], c.title).toBe('00000000-0000-4000-8000-000000000001'); + }); + + it('path parameters: invalid format only; an out-of-range id on a write operation is a gap, not a request', () => { + const get = paramCasesDetailed(spec.doc, op('GET /orders/{orderId}'), { allowPath: true, allowOthers: false }); + expect(get.cases.map((c) => [c.source, c.request!.path])).toEqual([['path.orderId.format', { orderId: 'not-a-uuid' }]]); + const numeric = { ...op('DELETE /orders/{orderId}'), params: [{ name: 'orderId', in: 'path', required: true, schema: { type: 'integer', minimum: 1, maximum: 999 }, knownValue: 5 }] } as any; + const del = paramCasesDetailed(spec.doc, numeric, { allowPath: true, allowOthers: true }); + expect(del.cases.map((c) => c.source)).toEqual(['path.orderId.type']); + expect(del.gaps.filter((g) => g.code === 'UNSAFE_LIVE_CHECK').map((g) => g.rule)).toEqual(['minimum', 'maximum']); + }); + + it('a required parameter without a documented value: no cases, a gap', () => { + const missing = { ...list, params: [...list.params, { name: 'tenant', in: 'header', required: true, schema: { type: 'string' } }] } as any; + const m = paramCasesDetailed(spec.doc, missing, { allowPath: true, allowOthers: true }); + expect(m.cases).toEqual([]); + expect(m.gaps).toEqual([expect.objectContaining({ code: 'MISSING_VALID_SAMPLE', location: 'request.header#/tenant' })]); + }); + + it('generated suites: TypeScript and Python carry the same parameter cases; positive calls send the required header', async () => { + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-pc-')); + await generate(spec, ops, { outDir: dir, version: 'test', lang }); + return { dir, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const uid = operationUid('GET', '/orders'); + for (const loc of ['request.header#/x-request-id:required', 'request.cookie#/session:minLength', 'request.query#/tags:maxItems']) expect(ts.reg.cases[`ata:${uid}:contract:negative:${loc}`], loc).toBeDefined(); + expect(ts.reg.cases[`ata:${operationUid('GET', '/orders/{}')}:contract:negative:request.path#/orderId:format`]).toBeDefined(); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + expect(validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('tests/fixtures/coverage/kitchen-sink.yaml', 'utf8'), 'ks')).errors).toEqual([]); + const tsList = await ts.read('orders/get/functional.spec.ts'); + expect(tsList).toContain(`headers: {"X-Request-Id":"00000000-0000-4000-8000-000000000001"}`); + const pyContract = await py.read('orders/get/test_contract.py'); + expect(pyContract).toContain('def test_rejects_invalid_parameter(api, contract, parts):'); + expect(await py.read('orders/get/test_functional.py')).toContain('headers={'); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', join(py.dir, 'orders/get/test_contract.py'), join(py.dir, 'orders/get_by_id/test_contract.py')], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); +}); diff --git a/tests/unit/scenarios.test.ts b/tests/unit/scenarios.test.ts new file mode 100644 index 0000000..03cfbce --- /dev/null +++ b/tests/unit/scenarios.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { Ajv } from 'ajv'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { validateScenarios } from '../../src/scenarios/dsl.js'; +import { scenarioUid } from '../../src/cases/ids.js'; +import { operationUid } from '../../src/change/normalize.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { normalizeSpec } from '../../src/change/normalize.js'; + +/** Stage 8 (docs/SUPPORT_MATRIX.md): CRUD flows and reviewed business scenarios. */ + +const demo = await loadSpec('demo-api/openapi.yaml'); +const ops = buildCatalog(demo.doc); +const file = JSON.parse(await readFile('demo-api/scenarios.json', 'utf8')); +const schema = JSON.parse(await readFile('schemas/scenarios.schema.json', 'utf8')); + +describe('stage 8: scenario model', () => { + it('the demo scenarios file matches its JSON Schema and the spec', () => { + expect(new Ajv({ allErrors: true }).validate(schema, file)).toBe(true); + const r = validateScenarios(file, ops); + expect(r.errors).toEqual([]); + expect(r.scenarios.map((s) => s.primaryOp.key)).toEqual(['GET /items/{itemId}', 'GET /items/{itemId}']); + }); + + it('strict validation: unknown operation, undefined variable, undocumented status, no cleanup, primary not an action', () => { + const bad = structuredClone(file); + const s0 = bad.scenarios[0]; + s0.steps[1].params.itemId = '{nope}'; + s0.steps[1].expect = '418'; + s0.steps.pop(); // no cleanup although the scenario creates data + s0.primary = 'create'; + bad.scenarios[1].steps[0].operationId = 'noSuchOp'; + bad.scenarios[1].id = 'items.read-created'; // duplicate external ID + const errors = validateScenarios(bad, ops).errors.map((e) => `${e.pointer}: ${e.reason}`); + for (const want of ['"{nope}" is not saved', '418 is not documented', 'no cleanup step', 'phase "action"', 'operation "noSuchOp" is not in the spec', 'duplicate id']) { + expect(errors.some((e) => e.includes(want)), want).toBe(true); + } + }); + + it('generated: one test per scenario in the primary operation folder, ID from the external ID, cleanup in finally; TS and Python agree', async () => { + const scenarios = validateScenarios(file, ops).scenarios; + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-scn-')); + const res = await generate(demo, ops, { outDir: dir, version: 'test', lang, scenarios }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const steps = scenarios[0].steps.map((st) => ({ operationUid: operationUid(st.op.method, st.op.path.replace(/\{[^}]*\}/g, '{}')), phase: st.phase })); + const uid = scenarioUid('business', steps, 'items.read-created'); + expect(ts.reg.cases[`ata:${uid}:scenario:positive:lifecycle:business-rule`]).toBeDefined(); + expect(ts.reg.scenarios[uid]).toMatchObject({ scenarioType: 'business', externalId: 'items.read-created', primaryOperationUid: operationUid('GET', '/items/{}') }); + // The title is not part of the identity. + const renamed = structuredClone(scenarios); + renamed[0].title = 'another title'; + expect(scenarioUid('business', steps, renamed[0].id)).toBe(uid); + + const text = await ts.read('items/get-by-id/scenarios.spec.ts'); + expect(text).toMatch(/an item that was just created can be read by its id[\s\S]*vars\['itemId'\] = readPointer\(body0, '\/id'\);[\s\S]*\} finally \{[\s\S]*reportCleanupFailure\('DELETE \/items\/\{itemId\}'/); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + expect(validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('demo-api/openapi.yaml', 'utf8'), 'demo')).errors).toEqual([]); + expect(await py.read('items/get_by_id/test_scenarios.py')).toContain('def test_items_read_created(api):'); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', ...py.res.files.filter((f) => f.endsWith('.py'))], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); + + it('CRUD: a repeated delete gets the documented 404', async () => { + const dir = await mkdtemp(join(tmpdir(), 'ata-del-')); + await generate(demo, ops, { outDir: dir, version: 'test' }); + const text = await readFile(join(dir, 'items/delete-by-id/scenarios.spec.ts'), 'utf8'); + expect(text).toMatch(/deleting the same resource again gets the documented 404[\s\S]*expectStatus\(res, \['404'\]/); + }); +}); diff --git a/tests/unit/validator.test.ts b/tests/unit/validator.test.ts new file mode 100644 index 0000000..e580388 --- /dev/null +++ b/tests/unit/validator.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { ContractValidator, type ResponseInput } from '../../src/contract/validator.js'; +import { findPython } from '../../src/generate/generate.js'; + +/** Stage 5 (docs/SUPPORT_MATRIX.md): response contract rules, identical in validator.ts and contract.py. */ + +const doc = { + openapi: '3.1.0', + info: { title: 'v', version: '1' }, + paths: { + '/users': { + get: { + responses: { + '200': { + description: 'ok', + headers: { + 'X-Total-Count': { required: true, schema: { type: 'integer', minimum: 0 } }, + 'X-Flags': { schema: { type: 'array', items: { type: 'boolean' } } }, + 'Content-Type': { required: true, schema: { type: 'string' } }, + }, + content: { 'application/json': { schema: { $ref: '#/components/schemas/User' } } }, + }, + default: { description: 'error', content: { 'application/json': { schema: { type: 'object', required: ['message'], properties: { message: { type: 'string' } } } } } }, + }, + }, + delete: { responses: { '204': { description: 'gone' }, '4XX': { description: 'client error' } } }, + head: { responses: { '200': { description: 'ok', content: { 'application/json': { schema: { type: 'object' } } } } } }, + }, + '/text': { get: { responses: { '200': { description: 'ok', content: { 'text/plain': { schema: { type: 'string', pattern: '^OK' } } } } } } }, + '/xml': { get: { responses: { '200': { description: 'ok', content: { 'application/xml': { schema: { type: 'object' } } } } } } }, + '/free': { get: { responses: { '200': { description: 'ok', content: { 'application/json': {} } } } } }, + }, + components: { + schemas: { + User: { + type: 'object', + required: ['id', 'password'], + properties: { id: { type: 'string', format: 'uuid' }, password: { type: 'string', writeOnly: true }, nickname: { type: ['string', 'null'] } }, + }, + }, + }, +}; + +const user = { id: '00000000-0000-4000-8000-000000000001', nickname: null }; +const json = (body: unknown) => ({ contentType: 'application/json', body, rawText: JSON.stringify(body) }); +const okHeaders = { 'x-total-count': '3', 'content-type': 'application/json' }; + +/** [name, input, expected ok, expected kind] */ +const CASES: [string, ResponseInput, boolean, string | undefined][] = [ + ['valid body and headers', { method: 'get', path: '/users', status: 200, ...json(user), headers: okHeaders }, true, undefined], + ['writeOnly property not required in a response', { method: 'get', path: '/users', status: 200, ...json(user), headers: okHeaders }, true, undefined], + ['writeOnly property present in a response', { method: 'get', path: '/users', status: 200, ...json({ ...user, password: 'x' }), headers: okHeaders }, false, 'schema'], + ['format checked', { method: 'get', path: '/users', status: 200, ...json({ id: 'nope' }), headers: okHeaders }, false, 'schema'], + ['required response header missing', { method: 'get', path: '/users', status: 200, ...json(user), headers: { 'content-type': 'application/json' } }, false, 'header'], + ['header schema (integer, minimum)', { method: 'get', path: '/users', status: 200, ...json(user), headers: { ...okHeaders, 'x-total-count': '-1' } }, false, 'header'], + ['header array of booleans (style simple)', { method: 'get', path: '/users', status: 200, ...json(user), headers: { ...okHeaders, 'x-flags': 'true,false' } }, true, undefined], + ['header array with a bad item', { method: 'get', path: '/users', status: 200, ...json(user), headers: { ...okHeaders, 'x-flags': 'true,maybe' } }, false, 'header'], + ['default response matches its schema', { method: 'get', path: '/users', status: 503, ...json({ message: 'down' }) }, true, undefined], + ['default response breaks its schema', { method: 'get', path: '/users', status: 503, ...json({}) }, false, 'schema'], + ['empty body where a schema is documented', { method: 'get', path: '/users', status: 200, contentType: 'application/json', body: null, rawText: '', headers: okHeaders }, false, 'empty-body'], + ['204 without a body', { method: 'delete', path: '/users', status: 204, contentType: null, body: '', rawText: '' }, true, undefined], + ['204 with a body', { method: 'delete', path: '/users', status: 204, ...json({ deleted: true }) }, false, 'unexpected-body'], + ['4XX range without content, body returned', { method: 'delete', path: '/users', status: 409, ...json({ message: 'conflict' }) }, false, 'unexpected-body'], + ['HEAD: no body is expected', { method: 'head', path: '/users', status: 200, contentType: 'application/json', body: '', rawText: '' }, true, undefined], + ['text/plain matches its string schema', { method: 'get', path: '/text', status: 200, contentType: 'text/plain', body: 'OK fine', rawText: 'OK fine' }, true, undefined], + ['text/plain breaks its pattern', { method: 'get', path: '/text', status: 200, contentType: 'text/plain', body: 'bad', rawText: 'bad' }, false, 'schema'], + ['undocumented content type', { method: 'get', path: '/text', status: 200, contentType: 'application/json', body: {}, rawText: '{}' }, false, 'content-type'], + ['undocumented status', { method: 'get', path: '/text', status: 500, contentType: 'text/plain', body: 'x', rawText: 'x' }, false, 'undocumented-status'], + ['unparseable JSON', { method: 'get', path: '/users', status: 200, contentType: 'application/json', body: undefined, rawText: '{oops', headers: okHeaders }, false, 'unparseable-body'], + ['empty body with an undocumented Content-Type: the type is the problem', { method: 'get', path: '/users', status: 200, contentType: 'text/html', body: '', rawText: '', headers: okHeaders }, false, 'content-type'], + ['JSON null without raw text is a body, not an empty one', { method: 'get', path: '/users', status: 200, contentType: 'application/json', body: null, headers: okHeaders }, false, 'schema'], + ['xml: not checked, with a note', { method: 'get', path: '/xml', status: 200, contentType: 'application/xml', body: '', rawText: '' }, true, undefined], + ['json without a schema: not checked, with a note', { method: 'get', path: '/free', status: 200, ...json({ any: 1 }) }, true, undefined], +]; + +describe('stage 5: response contract', () => { + const v = new ContractValidator(doc); + + for (const [name, input, ok, kind] of CASES) { + it(`TypeScript: ${name}`, () => { + const r = v.validateResponse(input); + expect({ ok: r.ok, kind: r.kind }, r.errors.join('; ')).toEqual({ ok, kind }); + }); + } + + it('notes say what was not checked', () => { + expect(v.validateResponse(CASES.find((c) => c[0].startsWith('xml'))![1]).notes).toEqual(['200 application/xml: media type not supported by the validator, body not checked']); + expect(v.validateResponse(CASES.find((c) => c[0].startsWith('json without'))![1]).notes).toEqual(['200 application/json: no schema documented, body not checked']); + }); + + it('Python (contract.py) gives the same result for every case', async () => { + const python = findPython(); + if (spawnSync(python, ['-c', 'import jsonschema'], { encoding: 'utf8' }).status !== 0) return; // no jsonschema here: CI runs it + const dir = await mkdtemp(join(tmpdir(), 'ata-val-')); + await writeFile(join(dir, 'doc.json'), JSON.stringify(doc)); + await writeFile(join(dir, 'cases.json'), JSON.stringify(CASES.map(([name, i]) => ({ name, ...i, body: i.body === undefined ? '__UNPARSEABLE__' : i.body })))); + const script = ` +import json, sys +sys.path.insert(0, ${JSON.stringify(resolve('src/contract'))}) +import contract +v = contract.ContractValidator(json.load(open(${JSON.stringify(join(dir, 'doc.json'))}))) +out = [] +for c in json.load(open(${JSON.stringify(join(dir, 'cases.json'))})): + body = contract._UNPARSEABLE if c["body"] == "__UNPARSEABLE__" else c["body"] + ok, kind, errors = v.validate(c["method"], c["path"], c["status"], c.get("contentType"), body, c.get("rawText"), c.get("headers")) + out.append({"name": c["name"], "ok": ok, "kind": kind}) +print(json.dumps(out)) +`; + const r = spawnSync(python, ['-I', '-c', script], { encoding: 'utf8' }); + expect(r.status, r.stderr).toBe(0); + const py = JSON.parse(r.stdout); + expect(py).toEqual(CASES.map(([name, , ok, kind]) => ({ name, ok, kind: kind ?? null }))); + }); +});