diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6ad5135..539c5b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,9 @@ jobs: API_LOGIN_BODY: '{"username":"${API_USER}","password":"${API_PASSWORD}"}' API_USER: demo API_PASSWORD: demo-password + # Reviewed auth cases (demo-api/deps.json "auth"): fixed demo sessions, an expired one and a suspended account. + API_EXPIRED_TOKEN: demo-expired-token + API_FORBIDDEN_TOKEN: demo-suspended-token steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -50,6 +53,9 @@ jobs: console.log("kitchen sink cases:", ts.length, "TypeScript /", py.length, "Python"); if (JSON.stringify(ts) !== JSON.stringify(py)) process.exit(1); ' + # Quality gates: no lost active case, no unexplained gap (ci/coverage-baseline.*.json), parity, cleanup. + npx tsx scripts/coverage-summary.ts --spec tests/fixtures/coverage/kitchen-sink.yaml --coverage reports/ks/coverage-gaps.json --registry tests/api-ks/_support/cases.json --parity tests/api-ks-python/_support/cases.json --tests-dir tests/api-ks --baseline ci/coverage-baseline.kitchen-sink.json --out reports/coverage-summary-kitchen-sink.md + npx tsx scripts/coverage-summary.ts --spec tests/fixtures/coverage/kitchen-sink.yaml --coverage reports/ks-python/coverage-gaps.json --registry tests/api-ks-python/_support/cases.json --tests-dir tests/api-ks-python > /dev/null rm -rf tests/api-ks tests/api-ks-python - name: Start demo API @@ -122,16 +128,35 @@ jobs: npx tsx src/cli.ts registry validate tests/api-python/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null npx tsx src/cli.ts manifest validate --tests-dir tests/api-python - - name: Fault injection - the collection tests must catch every injected defect (TS and Python) + - name: Fault injection - the generated tests must catch every injected defect (TS and Python) # The demo API runs once per DEMO_FAULT (ignored filter, wrong sort, hidden record, duplicates, wrong field, - # overlapping pages) on its own port: clean without a fault, at least one failure with each. + # overlapping pages, a required optional field, an accepted expired token, an ignored suspension) on its own + # port: clean without a fault, at least one failure with each. run: | - npx tsx scripts/mutation-check.ts --lang typescript --port 3200 tests/api/items/get - npx tsx scripts/mutation-check.ts --lang python --port 3300 tests/api-python/items/get + npx tsx scripts/mutation-check.ts --lang typescript --port 3200 tests/api/items tests/api/me + npx tsx scripts/mutation-check.ts --lang python --port 3300 tests/api-python/items tests/api-python/me node -e ' for (const l of ["typescript", "python"]) { const r = require("./reports/mutation-" + l + ".json"); console.log(l, r.detected + "/" + r.injected); if (r.detected !== r.injected) process.exit(1); } ' + - name: Quality gates - coverage baseline, parity, cleanup, coverage summary (demo API) + # A lost active case ID or a gap the reviewed baseline does not list fails: update ci/coverage-baseline.demo.json + # in the PR that intends it (npx tsx scripts/coverage-summary.ts ... --write-baseline). + run: | + npx tsx scripts/coverage-summary.ts --spec demo-api/openapi.yaml --coverage reports/generate/coverage-gaps.json --registry tests/api/_support/cases.json --parity tests/api-python/_support/cases.json --tests-dir tests/api --baseline ci/coverage-baseline.demo.json --out reports/coverage-summary-demo.md + npx tsx scripts/coverage-summary.ts --spec demo-api/openapi.yaml --coverage reports/generate-python/coverage-gaps.json --registry tests/api-python/_support/cases.json --tests-dir tests/api-python > /dev/null + + - name: Coverage summary artifact + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage-summary + path: | + reports/coverage-summary-*.md + reports/coverage-summary-*.json + reports/mutation-*.json + if-no-files-found: ignore + - name: Maintenance - a spec change is regenerated, validated and summarized (no PR in CI) run: | sed 's/enum: \[name, -name, price, -price\]/enum: [name, -name, price]/' demo-api/openapi.yaml > reports/openapi.changed.yaml diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cc060f..2eb5976 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- **Coverage depth** (docs/SUPPORT_MATRIX.md): + - positive request-body variants for create / update of a confirmed chain: only the required fields, and every other `oneOf` / `anyOf` branch with a valid sample; each checked with ajv before a test is written, cleanup in `finally`; closes `UNCOVERED_VARIANT` where a branch can be sent; + - reviewed auth cases from a deps `auth` section (environment variable names only): 403 for the operations named (`auth.forbidden`), 401 with an expired credential (`auth.expired`); skipped with the reason when the variable is unset; mismatches with the spec are `INVALID_REVIEWED_CONFIG`; + - unchecked-status codes state the actual reason (`MISSING_CLEANUP` for an operation no request is sent to, the success call's blocking reason for its status) instead of `NO_DOCUMENTED_REJECTION` / `UNCONFIRMED_BUSINESS_RULE`; + - case ID vocabulary v4: `optional-omitted`, `variant`, `expired-credentials`; + - CI quality gates (`scripts/coverage-summary.ts`): reviewed baselines of active case IDs and exact gaps (`ci/coverage-baseline.*.json`), TypeScript / Python parity, guaranteed cleanup of write tests, a per-operation coverage summary as an artifact; + - demo API: a documented 403 on `GET /me` (suspended account), fixed expired / suspended sessions for the reviewed auth cases, and three more fault modes (`require-optional`, `accept-expired`, `ignore-suspension`); fault injection runs over `items` and `me`: 9/9 in TypeScript and Python (the previous generator: 7/9 on the same spec). - **Collection testing** (docs/SUPPORT_MATRIX.md, "Collections"): - reviewed deps `collection` mapping, checked strictly against the spec (`INVALID_REVIEWED_CONFIG` gap on a mismatch); - strategy A (create & verify): controlled datasets with a unique marker in an isolating filter, cleanup in `finally`; strategy C (read-only) with explicit skips; strategy recorded per list operation in `coverage-gaps.json`; diff --git a/README.md b/README.md index 66db03c..b2f4efe 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,8 @@ Coverage is reported, never implied. The full keyword-by-keyword table is in [do **Needs your confirmation (deps or scenarios file):** CRUD chains and cleanup, 409 conflicts (`conflictOn`), fields a create returns as sent (`echoes`), values taken from existing data (`fill`), collection semantics (`collection`: identifier, persisted fields and their comparison policy, filters, sorts, paging, uniqueness, eventual consistency), approved fixtures (`--fixtures`), and every other business flow (`--scenarios`): state transitions, parent → child, login / refresh. +**Also derived, with a confirmed chain:** positive body variants: only the required fields, and every other `oneOf` / `anyOf` branch, each validated before it is sent and cleaned up after. **With a reviewed deps `auth` section:** 403 for an account that must be refused and 401 with an expired credential (credentials from environment variables only). + **Never generated (reported as gaps):** 403 without a reviewed role setup, 429, a 405 that would need an unsafe method, oneOf / anyOf branches other than the one sent, rules that cannot be broken without breaking another, media types other than JSON / text, and anything the spec does not state. ## Collections, fixtures and maintenance diff --git a/ci/coverage-baseline.demo.json b/ci/coverage-baseline.demo.json new file mode 100644 index 0000000..0b61433 --- /dev/null +++ b/ci/coverage-baseline.demo.json @@ -0,0 +1,108 @@ +{ + "schemaVersion": 1, + "activeCaseIds": [ + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:maximum", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:minimum", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:type", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/offset:minimum", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/offset:type", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/sort:enum", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/tag:maxLength", + "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/tag:minLength", + "ata:op_4PIO72ZI3SIY:contract:positive:response.body#:schema", + "ata:op_4PIO72ZI3SIY:functional:positive:operation:collection-contains", + "ata:op_4PIO72ZI3SIY:functional:positive:operation:documented-success", + "ata:op_4PIO72ZI3SIY:functional:positive:operation:fixture", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/100:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/1:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/offset/0:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/offset:pagination", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/-name:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/-name:sort", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/-price:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/-price:sort", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/name:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/name:sort", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/price:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/sort/price:sort", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/tag/x:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/tag/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/tag:filter", + "ata:op_4PIO72ZI3SIY:functional:positive:response.body#/items/*/id:unique", + "ata:op_7P2UH7UKQRHC:contract:positive:response.body#:schema", + "ata:op_7P2UH7UKQRHC:contract:positive:response.status#/404:documented", + "ata:op_7P2UH7UKQRHC:functional:negative:request.path#/itemId:not-found", + "ata:op_7P2UH7UKQRHC:functional:positive:operation:documented-success", + "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/204:documented", + "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/404:documented", + "ata:op_EDRRXKOK26ZL:functional:negative:request.path#/itemId:not-found", + "ata:op_EDRRXKOK26ZL:functional:positive:operation:documented-success", + "ata:op_FXHMYSJVVHAU:contract:positive:response.status#/404:documented", + "ata:op_FXHMYSJVVHAU:functional:negative:request.path#/reportId:not-found", + "ata:op_OT5MMXZVBZK4:contract:positive:response.body#:schema", + "ata:op_OT5MMXZVBZK4:functional:positive:operation:documented-success", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:maxLength", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:minLength", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:minimum", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:nullable", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:maxLength", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:minLength", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:nullable", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:nullable", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties", + "ata:op_UPN7JLUXYUZ7:contract:positive:response.body#:schema", + "ata:op_UPN7JLUXYUZ7:functional:positive:operation:documented-success", + "ata:op_UPN7JLUXYUZ7:functional:positive:request.body#:optional-omitted", + "ata:op_VSDJU55WRH4A:contract:positive:response.body#:schema", + "ata:op_VSDJU55WRH4A:functional:positive:operation:documented-success", + "ata:op_WRZHS7HTMVON:contract:positive:response.body#:schema", + "ata:op_WRZHS7HTMVON:contract:positive:response.status#/401:documented", + "ata:op_WRZHS7HTMVON:functional:negative:request.security:expired-credentials", + "ata:op_WRZHS7HTMVON:functional:negative:request.security:forbidden", + "ata:op_WRZHS7HTMVON:functional:negative:request.security:invalid-credentials", + "ata:op_WRZHS7HTMVON:functional:negative:request.security:unauthorized", + "ata:op_WRZHS7HTMVON:functional:positive:operation:documented-success", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:maxLength", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:minLength", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:nullable", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:type", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:minimum", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:nullable", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:type", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties", + "ata:op_Z4MCICNBZN3S:contract:positive:response.body#:schema", + "ata:op_Z4MCICNBZN3S:contract:positive:response.status#/404:documented", + "ata:op_Z4MCICNBZN3S:functional:negative:request.path#/itemId:not-found", + "ata:op_Z4MCICNBZN3S:functional:positive:operation:documented-success", + "ata:op_Z4MCICNBZN3S:functional:positive:request.body#:optional-omitted", + "ata:scn_4EG5AXFZY2YS:scenario:positive:lifecycle:crud", + "ata:scn_6I3KELJAMGYP:scenario:positive:lifecycle:business-rule", + "ata:scn_7MN4FYBHZCZQ:scenario:positive:lifecycle:crud", + "ata:scn_I6MIGZS3ULNR:scenario:positive:lifecycle:crud", + "ata:scn_RKQFWGP26Y3B:scenario:positive:lifecycle:crud", + "ata:scn_V2OYCQUW2VKW:scenario:negative:lifecycle:business-rule", + "ata:scn_VQLGIE5JMTBU:scenario:negative:lifecycle:business-rule" + ], + "gaps": [ + "CANNOT_ISOLATE_RULE GET /items request.query#/sort type", + "MISSING_CLEANUP POST /admin/reset response.status#/204", + "MISSING_CLEANUP POST /admin/reset response.status#/401", + "MISSING_CLEANUP POST /admin/reset suite#/contract", + "MISSING_CLEANUP POST /admin/reset suite#/functional", + "MISSING_CLEANUP POST /auth/login response.status#/200", + "MISSING_CLEANUP POST /auth/login response.status#/401", + "MISSING_CLEANUP POST /auth/login suite#/contract", + "MISSING_CLEANUP POST /auth/login suite#/functional", + "MISSING_RESOURCE_SOURCE GET /reports/{reportId} response.status#/200", + "MISSING_RESPONSE_SCHEMA GET /reports/{reportId} response.content-type#/application~1json" + ] +} diff --git a/ci/coverage-baseline.kitchen-sink.json b/ci/coverage-baseline.kitchen-sink.json new file mode 100644 index 0000000..ca2fa98 --- /dev/null +++ b/ci/coverage-baseline.kitchen-sink.json @@ -0,0 +1,138 @@ +{ + "schemaVersion": 1, + "activeCaseIds": [ + "ata:op_5E2TKD5VMKQX:functional:negative:operation:method-not-allowed", + "ata:op_6QE4VMQAA7TQ:contract:negative:request.content-type:content-type", + "ata:op_6QE4VMQAA7TQ:contract:positive:response.body#:schema", + "ata:op_6QE4VMQAA7TQ:contract:positive:response.status#/404:documented", + "ata:op_6QE4VMQAA7TQ:functional:negative:request.header#/if-match:precondition-failed", + "ata:op_6QE4VMQAA7TQ:functional:negative:request.path#/orderId:not-found", + "ata:op_6QE4VMQAA7TQ:functional:positive:operation:documented-success", + "ata:op_6QE4VMQAA7TQ:functional:positive:request.body#/payment/@1:variant", + "ata:op_6QE4VMQAA7TQ:functional:positive:request.body#:optional-omitted", + "ata:op_CCK6QTLSKZEY:contract:negative:request.path#/orderId:format", + "ata:op_CCK6QTLSKZEY:contract:positive:response.body#:schema", + "ata:op_CCK6QTLSKZEY:contract:positive:response.status#/404:documented", + "ata:op_CCK6QTLSKZEY:functional:negative:request.path#/orderId:not-found", + "ata:op_CCK6QTLSKZEY:functional:positive:operation:documented-success", + "ata:op_LECSY56WEA24:contract:positive:response.status#/204:documented", + "ata:op_LECSY56WEA24:contract:positive:response.status#/404:documented", + "ata:op_LECSY56WEA24:functional:negative:request.path#/orderId:not-found", + "ata:op_LECSY56WEA24:functional:positive:operation:documented-success", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.cookie#/session:minLength", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.header#/x-request-id:format", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.header#/x-request-id:required", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/code:pattern", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/ids:uniqueItems", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit:maximum", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit:minimum", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/limit:type", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/since:format", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/status:enum", + "ata:op_MDAZRDJNDE6Z:contract:negative:request.query#/tags:maxItems", + "ata:op_MDAZRDJNDE6Z:contract:positive:response.body#:schema", + "ata:op_MDAZRDJNDE6Z:contract:positive:response.status#/401:documented", + "ata:op_MDAZRDJNDE6Z:functional:negative:request.security:expired-credentials", + "ata:op_MDAZRDJNDE6Z:functional:negative:request.security:forbidden", + "ata:op_MDAZRDJNDE6Z:functional:negative:request.security:invalid-credentials", + "ata:op_MDAZRDJNDE6Z:functional:negative:request.security:unauthorized", + "ata:op_MDAZRDJNDE6Z:functional:positive:operation:documented-success", + "ata:op_MDAZRDJNDE6Z:functional:positive:request.query#/limit/1:accepted-value", + "ata:op_MDAZRDJNDE6Z:functional:positive:request.query#/limit/50:accepted-value", + "ata:op_MDAZRDJNDE6Z:functional:positive:request.query#/status/new:accepted-value", + "ata:op_MDAZRDJNDE6Z:functional:positive:request.query#/status/paid:accepted-value", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/comment:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address/city:maxLength", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address/city:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address/city:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address/zip:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address/zip:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address:maxProperties", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/address:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/code:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/code:pattern", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/code:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/email:format", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/email:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/email:required", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/email:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/name:maxLength", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/name:minLength", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/name:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/name:required", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer/name:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer:required", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/customer:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/gift:enum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/price:exclusiveMaximum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/price:exclusiveMinimum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/price:multipleOf", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/price:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/price:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/qty:maximum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/qty:minimum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/qty:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/qty:required", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/qty:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/sku:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/sku:required", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*/sku:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items/*:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items:minItems", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items:required", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/items:uniqueItems", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/kind:const", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/meta/a:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/meta/a:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/meta/b:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/meta/b:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/meta:minProperties", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/meta:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/meta:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/note:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/note:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/priority:enum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/status:enum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/tags/*:maxLength", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/tags/*:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/tags/*:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/tags:maxItems", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/tags:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/tags:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/total:minimum", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/total:nullable", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/total:required", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#/total:type", + "ata:op_XZWXG7WBLMWO:contract:negative:request.body#:additionalProperties", + "ata:op_XZWXG7WBLMWO:contract:negative:request.content-type:content-type", + "ata:op_XZWXG7WBLMWO:contract:positive:response.body#:schema", + "ata:op_XZWXG7WBLMWO:functional:positive:operation:documented-success", + "ata:op_XZWXG7WBLMWO:functional:positive:request.body#/payment/@1:variant", + "ata:op_XZWXG7WBLMWO:functional:positive:request.body#:optional-omitted", + "ata:scn_2QNG3LESAX7N:scenario:positive:lifecycle:crud", + "ata:scn_6Z7FD7K3JGGF:scenario:positive:lifecycle:crud", + "ata:scn_AOPYUXTUW2T5:scenario:negative:lifecycle:business-rule", + "ata:scn_LPDPBP4Q6PV7:scenario:negative:lifecycle:business-rule", + "ata:scn_NM6FR7XP3CVY:scenario:positive:lifecycle:crud" + ], + "gaps": [ + "CANNOT_ISOLATE_RULE GET /orders request.query#/limit multipleOf", + "CANNOT_ISOLATE_RULE GET /orders request.query#/status type", + "CANNOT_ISOLATE_RULE POST /orders request.body#/gift type", + "CANNOT_ISOLATE_RULE POST /orders request.body#/items maxItems", + "CANNOT_ISOLATE_RULE POST /orders request.body#/priority type", + "CANNOT_ISOLATE_RULE POST /orders request.body#/status type", + "MISSING_CLEANUP POST /orders/{orderId}/cancel response.status#/202", + "MISSING_CLEANUP POST /orders/{orderId}/cancel suite#/contract", + "UNCONFIRMED_BUSINESS_RULE GET /orders operation", + "UNCONFIRMED_BUSINESS_RULE GET /orders/{orderId} suite#/scenario", + "UNREACHABLE_RESPONSE_STATUS PUT /orders/{orderId} response.status#/418", + "UNSAFE_LIVE_CHECK GET /orders response.status#/429", + "UNSUPPORTED_SCHEMA_KEYWORD POST /orders request.body#/payment oneOf" + ] +} diff --git a/demo-api/deps.json b/demo-api/deps.json index 58b0319..b25ee43 100644 --- a/demo-api/deps.json +++ b/demo-api/deps.json @@ -1,4 +1,15 @@ { + "auth": { + "forbidden": { + "credentialEnv": "API_FORBIDDEN_TOKEN", + "operations": [ + "getMe" + ] + }, + "expired": { + "credentialEnv": "API_EXPIRED_TOKEN" + } + }, "scenarios": [ { "create": "createItem", @@ -11,16 +22,54 @@ "operationId": "listItems", "items": "/items", "id": "/id", - "fields": { "/name": "exact", "/price": "tolerance:0.001", "/tags": "exact", "/createdAt": "ignore" }, - "unique": ["/id"], - "filters": [{ "param": "tag", "field": "/tags", "match": "contains" }], + "fields": { + "/name": "exact", + "/price": "tolerance:0.001", + "/tags": "exact", + "/createdAt": "ignore" + }, + "unique": [ + "/id" + ], + "filters": [ + { + "param": "tag", + "field": "/tags", + "match": "contains" + } + ], "sorts": [ - { "param": "sort", "value": "name", "field": "/name", "order": "asc" }, - { "param": "sort", "value": "-name", "field": "/name", "order": "desc" }, - { "param": "sort", "value": "price", "field": "/price", "order": "asc" }, - { "param": "sort", "value": "-price", "field": "/price", "order": "desc" } + { + "param": "sort", + "value": "name", + "field": "/name", + "order": "asc" + }, + { + "param": "sort", + "value": "-name", + "field": "/name", + "order": "desc" + }, + { + "param": "sort", + "value": "price", + "field": "/price", + "order": "asc" + }, + { + "param": "sort", + "value": "-price", + "field": "/price", + "order": "desc" + } ], - "page": { "style": "offset", "offsetParam": "offset", "limitParam": "limit", "maxPages": 20 }, + "page": { + "style": "offset", + "offsetParam": "offset", + "limitParam": "limit", + "maxPages": 20 + }, "deletedDisappears": true } } diff --git a/demo-api/openapi.yaml b/demo-api/openapi.yaml index 042983a..e89b9ad 100644 --- a/demo-api/openapi.yaml +++ b/demo-api/openapi.yaml @@ -266,6 +266,12 @@ paths: type: string '401': $ref: '#/components/responses/Unauthorized' + '403': + description: The account is suspended + content: + application/json: + schema: + $ref: '#/components/schemas/Error' /admin/reset: post: operationId: resetInventory diff --git a/demo-api/server.ts b/demo-api/server.ts index e90dff0..41b15a5 100644 --- a/demo-api/server.ts +++ b/demo-api/server.ts @@ -51,6 +51,8 @@ function validateItem(body: unknown, partial: boolean): string | Partial { const extra = Object.keys(b).filter((k) => !allowed.includes(k)); if (extra.length) return `Unknown fields: ${extra.join(', ')}`; if (partial && Object.keys(b).length === 0) return 'At least one field is required'; + // DEMO_FAULT=require-optional: a documented optional field is required (tags on create, name on update). + if (process.env.DEMO_FAULT === 'require-optional' && !(partial ? 'name' in b : 'tags' in b)) return partial ? 'name is required' : 'tags is required'; const out: Partial = {}; if ('name' in b || !partial) { if (typeof b.name !== 'string' || b.name.length < 1 || b.name.length > 100) return 'name must be a string of 1-100 characters'; @@ -166,6 +168,11 @@ const DEMO_PASSWORD = process.env.DEMO_PASSWORD ?? 'demo-password'; const TOKEN_TTL_SEC = Number(process.env.DEMO_TOKEN_TTL ?? 300); const sessions = new Map(); const accounts = new Map([[DEMO_USER, DEMO_PASSWORD]]); +// Fixed sessions for the reviewed auth cases (demo-api/deps.json "auth"): an expired token of the demo user, and a +// valid token of a suspended account, which /me must refuse with 403. +const SUSPENDED = new Set(['suspended']); +sessions.set('demo-expired-token', { username: DEMO_USER, expiresAt: 0 }); +sessions.set('demo-suspended-token', { username: 'suspended', expiresAt: Number.MAX_SAFE_INTEGER }); // Self-registration for API_TEST_ACCOUNT=new. Not in the spec on purpose: it is configured // through API_REGISTER / API_REGISTER_BODY, like on APIs whose spec omits it. @@ -195,7 +202,9 @@ route('/me', { GET: (req, res) => { const token = (req.headers.authorization ?? '').replace(/^Bearer\s+/i, ''); const s = sessions.get(token); - if (!s || s.expiresAt < Date.now()) return error(res, 401, 'Unauthorized'); + // DEMO_FAULT=accept-expired / ignore-suspension: the check is missing (the reviewed auth cases must notice). + if (!s || (s.expiresAt < Date.now() && process.env.DEMO_FAULT !== 'accept-expired')) return error(res, 401, 'Unauthorized'); + if (SUSPENDED.has(s.username) && process.env.DEMO_FAULT !== 'ignore-suspension') return error(res, 403, 'Account suspended'); send(res, 200, { username: s.username }); }, }); diff --git a/docs/OPENAPI_CHANGE_TRIGGER.md b/docs/OPENAPI_CHANGE_TRIGGER.md index cc0523b..61dbb46 100644 --- a/docs/OPENAPI_CHANGE_TRIGGER.md +++ b/docs/OPENAPI_CHANGE_TRIGGER.md @@ -291,6 +291,9 @@ v3 functional/positive: collection-contains, fixture operation filter, pagination request.query#/ sort request.query#// unique response.body#/* +v4 functional/positive: optional-omitted request.body# + variant request.body#/@ + functional/negative: expired-credentials request.security ``` This is the architecture's vocabulary. The generator may support only a subset, but it never creates unknown rules. `crud` is only for a general resource lifecycle; `business-rule` covers positive and negative business scenarios, including state transitions. A separate `state-transition` rule may come in a later vocabulary version if `business-rule` proves too broad. diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 510693f..a096e3e 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -34,6 +34,15 @@ Recursive from a valid payload; every case breaks exactly one rule (verified wit | `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 ✔ | +## Request body: positive variants (`functional.spec.ts`, `src/generate/variants.ts`) + +Create / update operations of a confirmed chain. Each variant is a valid payload (checked with ajv against the request schema before a test is written) that differs from the documented example in one documented way; the test expects the documented success status and a response that matches the contract, and removes what it created in `finally`. + +| Variant | State | How / gap | Stage | +|---|---|---|---| +| only the required fields (`optional-omitted`, `request.body#`) | ✅ | optional fields removed outer first, each removal kept only while the payload stays valid (`minProperties`, dependent rules); never inside `oneOf` / `anyOf` / conditional subtrees; deps `fill` fields stay; nothing removable although optional fields exist → `CANNOT_ISOLATE_RULE` | D ✔ | +| another `oneOf` / `anyOf` branch (`variant`, `request.body#/@`) | ✅ | every branch the example does not match, with a sample of that branch; no valid sample, or the payload is not valid with it → `UNCOVERED_VARIANT` with the reason | D ✔ | + ## 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. @@ -102,8 +111,8 @@ A case is generated only when the request that triggers the error is safe and th | 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) | +| 401 (expired token) | ✅ | deps `auth.expired.credentialEnv`: the variable holding an expired credential (never the value in the file); the same safe request as the invalid-credential case; skipped with the reason when the variable is unset; rule `expired-credentials` | D ✔ | +| 403 (scope / role) | ✅ | deps `auth.forbidden` (`credentialEnv` + the operations that must refuse that account): GET / HEAD with documented path values only; a write → `UNSAFE_LIVE_CHECK`, unknown path values → `MISSING_RESOURCE_SOURCE`, an operation named without a documented 403 → `INVALID_REVIEWED_CONFIG`; without the section `UNCONFIRMED_BUSINESS_RULE` | D ✔ | | 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 ✔ | @@ -174,7 +183,9 @@ Strategy per list operation (recorded in `coverage-gaps.json` → `collection.st Defect detection on a real API: Toolshop's deliberately defective build (`api-with-bugs.practicesoftwaretesting.com`) returns rental products for `by_brand=1` that its product list never shows. The read-only `by_brand` test fails on it (`by_brand=1 returns resources the unfiltered collection does not show: 27, 28, 29`) and passes on the regular build, in TypeScript and Python. `by_category=12` has the same defect but only rentals carry that category, so a read-only test cannot reach it. -Defect detection on the demo API (`scripts/mutation-check.ts`, TypeScript and Python identical): +Defect detection on the demo API (`scripts/mutation-check.ts`, TypeScript and Python identical). Beyond the list defects below, the suite must also catch `require-optional` (an optional field is required), `accept-expired` (an expired token is accepted) and `ignore-suspension` (a refused account gets 200): 9/9 in CI; the generator of the previous release caught 7/9 on the same spec (both auth defects missed, `require-optional` only by chance, through a reviewed business scenario). + + | Injected defect (`DEMO_FAULT`) | Previous generator (65 tests) | Collection tests | |---|---|---| @@ -201,7 +212,7 @@ Defect detection on the demo API (`scripts/mutation-check.ts`, TypeScript and Py |---|---|---|---| | `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) | +| `oneOf` / `anyOf` | ✅ | the example's branch in every test; each other branch with a valid sample in its own positive test (see "Request body: positive variants"); the rest `UNCOVERED_VARIANT` | D ✔ | | `discriminator` | 🟡 | blocked with an explicit reason | | | `pattern` | 🟡 | blocked without an example (explicit reason) | | | `multipleOf` | ✅ | the smallest multiple inside the bounds | 7 ✔ | @@ -224,6 +235,10 @@ Defect detection on the demo API (`scripts/mutation-check.ts`, TypeScript and Py | CI: TypeScript / Python parity | ✅ | the same active cases for the demo API and for the synthetic fixture | 9 ✔ | | CI: the synthetic fixture compiles | ✅ | `tests/fixtures/coverage/kitchen-sink.yaml` generated in both languages: `tsc`, `py_compile`, valid registry | 6 ✔ | | CI: expected coverage gaps | ✅ | demo API (`demo-api/expected-gaps.json`) in CI; the synthetic fixture in unit tests | 10 ✔ | +| CI: coverage baseline | ✅ | `ci/coverage-baseline.{demo,kitchen-sink}.json`: every active case ID and every gap (code + operation + location); a lost case or a gap the baseline does not list fails until the PR updates the baseline (`scripts/coverage-summary.ts --write-baseline`) | D ✔ | +| CI: cleanup of write tests | ✅ | every generated test that creates data removes it in `finally`, a fixture teardown, or `removeIfCreated` right after the request and before any assertion (`src/report/quality-gates.ts`), TypeScript and Python | D ✔ | +| CI: coverage summary | ✅ | per operation: suites, active case IDs, documented statuses checked, gaps with code and location; Markdown + JSON artifact `coverage-summary`, also in the job summary | D ✔ | +| unchecked-status codes | ✅ | the actual reason: a status of an operation no request is sent to has the success call's reason (e.g. `MISSING_CLEANUP`), an unchecked success status the reason the success call is blocked (e.g. `MISSING_RESOURCE_SOURCE`) | D ✔ | | CI: fault injection | ✅ | `scripts/mutation-check.ts`: the demo list suite must be clean without a fault and fail under each of 6 `DEMO_FAULT` modes, TypeScript and Python | C ✔ | | CI: maintenance | ✅ | `maintain` on a changed demo spec: regenerated, validated, the stale reviewed mapping reported | C ✔ | | README | ✅ | "What is covered, and what is not": spec-derived vs needs confirmation vs never generated | 10 ✔ | diff --git a/scripts/coverage-summary.ts b/scripts/coverage-summary.ts new file mode 100644 index 0000000..36941f2 --- /dev/null +++ b/scripts/coverage-summary.ts @@ -0,0 +1,151 @@ +/** + * Coverage summary and quality gates for a generated suite (docs/SUPPORT_MATRIX.md, "Reporting and CI"). + * + * npx tsx scripts/coverage-summary.ts --spec demo-api/openapi.yaml --coverage reports/generate/coverage-gaps.json \ + * --registry tests/api/_support/cases.json [--parity tests/api-python/_support/cases.json] \ + * [--tests-dir tests/api] [--out reports/coverage-summary.md] \ + * [--baseline ci/coverage-baseline.demo.json] [--write-baseline] + * + * Writes a Markdown table per operation (suites, active case IDs, checked / unchecked statuses, gaps with code and + * location) and a JSON next to it. Gates (exit 1, each failure listed): + * - an active case ID of the baseline is no longer active (coverage decreased) unless the baseline is updated; + * - a gap (code + operation + location) that the baseline does not list (unexplained new gap); + * - with --parity: TypeScript and Python active case IDs differ; + * - with --tests-dir: a write test without cleanup in `finally` (TypeScript) / fixture teardown or finally (Python). + * --write-baseline records the current state as the expected one (a reviewed change, committed with the PR). + */ +import { existsSync, readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { loadSpec } from '../src/spec/loader.js'; +import { buildCatalog } from '../src/spec/catalog.js'; +import { cleanupProblems, compareBaseline } from '../src/report/quality-gates.js'; + +const args = process.argv.slice(2); +const opt = (name: string) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); +const flag = (name: string) => args.includes(name); +const specFile = opt('--spec'); +const coverageFile = opt('--coverage'); +const registryFile = opt('--registry'); +if (!specFile || !coverageFile || !registryFile) { + console.error('usage: coverage-summary.ts --spec --coverage --registry [--parity ] [--tests-dir ] [--out ] [--baseline ] [--write-baseline]'); + process.exit(2); +} + +interface Gap { + code: string; + operation: string; + location: string; + rule?: string; + reason: string; +} + +const spec = await loadSpec(specFile); +const ops = buildCatalog(spec.doc); +const coverage = JSON.parse(readFileSync(coverageFile, 'utf8')); +const registry = JSON.parse(readFileSync(registryFile, 'utf8')); +const active = (reg: any) => Object.entries(reg.cases).filter(([, c]) => c.status !== 'retired').map(([id]) => id).sort(); +const activeIds = active(registry); + +// Case IDs per operation: its own cases (op_ subject) and scenarios whose primary operation it is. +const opKeyOfUid = new Map(Object.entries(registry.operations).map(([uid, o]) => [uid, `${o.method} ${o.path}`])); +const primaryOfScenario = new Map(Object.entries(registry.scenarios ?? {}).map(([uid, s]) => [uid, s.primaryOperationUid])); +const idsByOp = new Map(); +for (const id of activeIds) { + const subject = id.split(':')[1]; + const key = opKeyOfUid.get(subject.startsWith('scn_') ? primaryOfScenario.get(subject) : subject) ?? '(unknown)'; + idsByOp.set(key, [...(idsByOp.get(key) ?? []), id]); +} + +const gaps: Gap[] = []; +const rows: string[] = []; +const totals = { functional: 0, contract: 0, scenario: 0, cases: 0, documented: 0, checked: 0 }; +for (const c of coverage.operations) { + const op = ops.find((o) => o.key === c.operation); + const documented = (op?.responses ?? []).map((r) => r.status); + const unchecked = c.uncheckedStatuses as { status: string; code: string }[]; + const checked = documented.filter((s) => !unchecked.some((u) => u.status === s)); + for (const g of c.gaps) gaps.push({ code: g.code, operation: c.operation, location: g.location, ...(g.rule ? { rule: g.rule } : {}), reason: g.reason }); + for (const u of unchecked) gaps.push({ code: u.code, operation: c.operation, location: `response.status#/${u.status}`, reason: `documented ${u.status} is not exercised` }); + for (const [suite, s] of Object.entries(c.suites)) if (!s.generated && s.missingCode && !(suite === 'scenario' && s.missingCode === 'UNCONFIRMED_BUSINESS_RULE' && !c.lifecycle)) gaps.push({ code: s.missingCode, operation: c.operation, location: `suite#/${suite}`, reason: `${suite} suite: no cases` }); + const n = idsByOp.get(c.operation)?.length ?? 0; + totals.functional += c.counts.functional; + totals.contract += c.counts.contract; + totals.scenario += c.counts.scenario; + totals.cases += n; + totals.documented += documented.length; + totals.checked += checked.length; + const cell = (k: string) => (c.counts[k] ? String(c.counts[k]) : `— ${c.suites[k]?.missingCode ?? ''}`.trim()); + const gapCell = [...unchecked.map((u: any) => `${u.status}: ${u.code}`), ...c.gaps.map((g: any) => `${g.code} @ ${g.location}`)]; + rows.push(`| ${c.operation} | ${cell('functional')} | ${cell('contract')} | ${cell('scenario')} | ${n} | ${checked.join(', ') || '—'} | ${gapCell.length ? gapCell.join('
') : '—'} |`); +} + +const gapKey = (g: Gap) => `${g.code} ${g.operation} ${g.location}${g.rule ? ` ${g.rule}` : ''}`; +const byCode: Record = {}; +for (const g of gaps) byCode[g.code] = (byCode[g.code] ?? 0) + 1; + +// ---------------------------------------------------------------- gates +const failures: string[] = []; +let parity: { ok: boolean; onlyHere: string[]; onlyThere: string[] } | undefined; +const parityFile = opt('--parity'); +if (parityFile) { + const other = new Set(active(JSON.parse(readFileSync(parityFile, 'utf8')))); + const here = new Set(activeIds); + parity = { ok: true, onlyHere: activeIds.filter((id) => !other.has(id)), onlyThere: [...other].filter((id) => !here.has(id)) }; + parity.ok = !parity.onlyHere.length && !parity.onlyThere.length; + if (!parity.ok) failures.push(`TS/Python parity: ${parity.onlyHere.length} case(s) only in ${registryFile}, ${parity.onlyThere.length} only in ${parityFile}`); +} + +// Cleanup: every test that creates data must remove it in finally (TS) or through a fixture / finally (Python). +const cleanup: { file: string; problem: string }[] = []; +const testsDir = opt('--tests-dir'); +if (testsDir) { + const walk = (d: string): string[] => readdirSync(d).flatMap((n) => (statSync(join(d, n)).isDirectory() ? walk(join(d, n)) : [join(d, n)])); + for (const file of walk(testsDir).filter((f) => /\.spec\.ts$|[\\/]test_\w+\.py$/.test(f))) { + for (const p of cleanupProblems(readFileSync(file, 'utf8').replace(/\r\n/g, '\n'), file.endsWith('.ts') ? 'typescript' : 'python')) cleanup.push({ file, problem: `${p.problem}: ${p.test}` }); + } + for (const c of cleanup) failures.push(`cleanup: ${c.file}: ${c.problem}`); +} + +const baselineFile = opt('--baseline'); +const current = { schemaVersion: 1, activeCaseIds: activeIds, gaps: [...new Set(gaps.map(gapKey))].sort() }; +let baselineDiff: { lostCases: string[]; newCases: string[]; newGaps: string[]; closedGaps: string[] } | undefined; +if (baselineFile && flag('--write-baseline')) { + mkdirSync(dirname(baselineFile), { recursive: true }); + writeFileSync(baselineFile, JSON.stringify(current, null, 2) + '\n'); + console.log(`baseline written: ${baselineFile} (${activeIds.length} active cases, ${current.gaps.length} gaps)`); +} else if (baselineFile) { + if (!existsSync(baselineFile)) failures.push(`baseline ${baselineFile} is missing: create it with --write-baseline`); + else { + baselineDiff = compareBaseline(JSON.parse(readFileSync(baselineFile, 'utf8')), current); + for (const id of baselineDiff.lostCases) failures.push(`case no longer active (update the baseline if intended): ${id}`); + for (const g of baselineDiff.newGaps) failures.push(`unexplained new gap (update the baseline if intended): ${g}`); + } +} + +// ---------------------------------------------------------------- report +const md = [ + `## Coverage summary: ${spec.doc.info?.title ?? specFile}`, + '', + `Operations ${coverage.operations.length} · tests: functional ${totals.functional}, contract ${totals.contract}, scenarios ${totals.scenario} · active case IDs ${activeIds.length} · documented statuses checked ${totals.checked}/${totals.documented}`, + '', + '| Operation | functional | contract | scenarios | case IDs | statuses checked | not covered (code @ location) |', + '|---|---|---|---|---|---|---|', + ...rows, + '', + `**Gaps by code:** ${Object.entries(byCode).sort().map(([k, v]) => `${k} ${v}`).join(', ') || 'none'}`, + ...(parity ? ['', `**TS/Python parity:** ${parity.ok ? 'same active case IDs' : `DIFFERENT (${parity.onlyHere.length} / ${parity.onlyThere.length})`}`] : []), + ...(testsDir ? ['', `**Cleanup:** ${cleanup.length ? `${cleanup.length} write test(s) without cleanup in finally` : 'every write test cleans up in finally / a fixture'}`] : []), + ...(baselineDiff + ? ['', `**Against the baseline:** cases +${baselineDiff.newCases.length} / lost ${baselineDiff.lostCases.length} · gaps new ${baselineDiff.newGaps.length} / closed ${baselineDiff.closedGaps.length}`, ...baselineDiff.closedGaps.map((g) => `- closed: ${g}`), ...baselineDiff.newGaps.map((g) => `- NEW: ${g}`)] + : []), + ...(failures.length ? ['', '**Quality gates failed:**', ...failures.map((f) => `- ${f}`)] : ['', '**Quality gates:** passed']), +].join('\n'); +const out = opt('--out'); +if (out) { + mkdirSync(dirname(out), { recursive: true }); + writeFileSync(out, md + '\n'); + writeFileSync(out.replace(/\.md$/, '') + '.json', JSON.stringify({ totals, activeCaseIds: activeIds.length, gapsByCode: byCode, gaps, parity, cleanup, baseline: baselineDiff, failures }, null, 2) + '\n'); +} +if (process.env.GITHUB_STEP_SUMMARY) writeFileSync(process.env.GITHUB_STEP_SUMMARY, md + '\n', { flag: 'a' }); +console.log(md); +process.exit(failures.length ? 1 : 0); diff --git a/scripts/mutation-check.ts b/scripts/mutation-check.ts index 43ace71..7a3dac4 100644 --- a/scripts/mutation-check.ts +++ b/scripts/mutation-check.ts @@ -13,12 +13,14 @@ import { existsSync, rmSync, writeFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { findPython } from '../src/generate/generate.js'; -export const FAULTS = ['ignore-filter', 'wrong-sort', 'hide-created', 'duplicate', 'wrong-field', 'bad-pagination'] as const; +export const FAULTS = ['ignore-filter', 'wrong-sort', 'hide-created', 'duplicate', 'wrong-field', 'bad-pagination', 'require-optional', 'accept-expired', 'ignore-suspension'] as const; const args = process.argv.slice(2); const lang = args.includes('--lang') ? args[args.indexOf('--lang') + 1] : 'typescript'; -const targets = args.filter((a, i) => !a.startsWith('--') && args[i - 1] !== '--lang' && args[i - 1] !== '--port'); +const targets = args.filter((a, i) => !a.startsWith('--') && !['--lang', '--port', '--faults', '--label'].includes(args[i - 1])); const basePort = Number(args.includes('--port') ? args[args.indexOf('--port') + 1] : 3200); +/** --faults a,b: only these fault modes (each must be caught by the targets given). */ +const only = args.includes('--faults') ? args[args.indexOf('--faults') + 1].split(',') : undefined; if (!targets.length) { console.error('usage: mutation-check.ts [--lang typescript|python] [--port 3200] ...'); process.exit(2); @@ -70,7 +72,9 @@ async function withServer(fault: string, port: number, fn: (url: string) => T } const rows: { fault: string; passed: number; failed: number; skipped: number; ok: boolean }[] = []; -for (const [i, fault] of ['', ...FAULTS].entries()) { +const faults = only ? FAULTS.filter((f) => only.includes(f)) : FAULTS; +if (only && faults.length !== only.length) throw new Error(`unknown fault in --faults ${only.join(',')}: known ${FAULTS.join(', ')}`); +for (const [i, fault] of ['', ...faults].entries()) { const r = await withServer(fault, basePort + i, runTests); const ok = fault ? r.failed > 0 : r.failed === 0 && r.passed > 0; rows.push({ fault: fault || '(none)', passed: r.passed, failed: r.failed, skipped: r.skipped, ok }); @@ -80,6 +84,7 @@ console.log(`\nFault injection (${lang}): ${targets.join(', ')}`); console.log('fault passed failed skipped verdict'); for (const r of rows) console.log(`${r.fault.padEnd(16)} ${String(r.passed).padStart(6)} ${String(r.failed).padStart(6)} ${String(r.skipped).padStart(7)} ${r.fault === '(none)' ? (r.ok ? 'clean' : 'FAILS WITHOUT A FAULT') : r.ok ? 'detected' : 'MISSED'}`); const detected = rows.filter((r) => r.fault !== '(none)' && r.ok).length; -console.log(`detected ${detected}/${FAULTS.length} injected defects`); -if (existsSync('reports')) writeFileSync(`reports/mutation-${lang}.json`, JSON.stringify({ lang, targets, rows, detected, injected: FAULTS.length }, null, 2) + '\n'); +console.log(`detected ${detected}/${faults.length} injected defects`); +const label = args.includes('--label') ? args[args.indexOf('--label') + 1] : lang; +if (existsSync('reports')) writeFileSync(`reports/mutation-${label}.json`, JSON.stringify({ lang, targets, rows, detected, injected: faults.length }, null, 2) + '\n'); process.exit(rows.every((r) => r.ok) ? 0 : 1); diff --git a/src/cases/assign.ts b/src/cases/assign.ts index 661dcfb..86222a7 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -28,7 +28,7 @@ export interface ScenarioDefinition { export interface SuiteCaseIds { /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ - functional: { collection?: string[]; fixture?: string; success?: string; notFound?: string; unauthorized?: string; variants: string[]; invalidCredentials?: string; methodNotAllowed?: string; preconditionFailed?: string }; + functional: { collection?: string[]; fixture?: string; bodyVariants?: string[]; envCredentials?: string[]; success?: string; notFound?: string; unauthorized?: string; variants: string[]; invalidCredentials?: string; methodNotAllowed?: string; preconditionFailed?: string }; contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[]; unsupportedMediaType?: string }; scenario: { lifecycle?: string; createRead?: string; updateRead?: string; deleteGone?: string; conflict?: string; deleteTwice?: string; business: string[] }; /** Every case of this operation, by suite, with metadata for cases.json. */ @@ -58,6 +58,8 @@ export interface AssignInput { collectionChain?: CrudChain; /** An approved fixture is compared (strategy B). */ fixture?: boolean; + /** Positive request-body variants (one case each, in order). */ + bodyVariants?: { location: string; kind: string }[]; } export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): SuiteCaseIds { @@ -111,6 +113,7 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): // Documented error responses (stage 6). const e = s.errors; + if (e?.envCredentials?.length) ids.functional.envCredentials = e.envCredentials.map((c) => add('functional', { subjectUid: uid, polarity: 'negative', location: location.security(), rule: c.kind === 'expired' ? 'expired-credentials' : 'forbidden' })); 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); @@ -175,6 +178,7 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): ids.scenario.lifecycle = add('scenario', { subjectUid: sUid, polarity: 'positive', location: location.lifecycle(), rule: 'crud' }, { relatedOperationUids: [uidOf(ch.create), uidOf(ch.update), uidOf(ch.delete)] }); } } + if (s.bodyVariants?.length) ids.functional.bodyVariants = s.bodyVariants.map((v) => add('functional', { subjectUid: uid, polarity: 'positive', location: v.location, rule: v.kind }, rel)); if (s.fixture) ids.functional.fixture = add('functional', { subjectUid: uid, polarity: 'positive', location: location.operation(), rule: 'fixture' }); // Reviewed business scenarios: identity from the external ID (never from the title or the steps). for (const sc of s.business ?? []) { diff --git a/src/cases/ids.ts b/src/cases/ids.ts index 47753d1..99c46b8 100644 --- a/src/cases/ids.ts +++ b/src/cases/ids.ts @@ -15,9 +15,12 @@ export type Polarity = 'positive' | 'negative'; * `invalid-credentials`, `method-not-allowed`, `precondition-failed`. * v3 adds functional/positive collection rules: `collection-contains`, `unique`, `fixture` (on "operation" / * response.body), `filter`, `pagination` (on the query parameter), `sort` (request.query#//). + * v4 adds functional/positive request-body variants: `optional-omitted` (on "request.body#": only the required + * fields are sent) and `variant` (request.body#/@: branch n of the oneOf / anyOf at that pointer), and + * functional/negative `expired-credentials` (request.security; `forbidden` exists since v1). * Registries of older versions stay readable. */ -export const CASE_RULE_VOCABULARY_VERSION = 3; +export const CASE_RULE_VOCABULARY_VERSION = 4; const CONSTRAINT_RULES = [ 'required', 'nullable', 'type', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', @@ -26,8 +29,8 @@ const CONSTRAINT_RULES = [ /** Built-in vocabulary v1, by suiteType/polarity. */ export const VOCABULARY_V1: Record = { - 'functional/positive': ['documented-success', 'accepted-value', 'collection-contains', 'filter', 'sort', 'pagination', 'unique', 'fixture'], - 'functional/negative': ['not-found', 'unauthorized', 'forbidden', 'invalid-credentials', 'method-not-allowed', 'precondition-failed'], + 'functional/positive': ['documented-success', 'accepted-value', 'collection-contains', 'filter', 'sort', 'pagination', 'unique', 'fixture', 'optional-omitted', 'variant'], + 'functional/negative': ['not-found', 'unauthorized', 'forbidden', 'invalid-credentials', 'expired-credentials', 'method-not-allowed', 'precondition-failed'], 'contract/positive': ['documented', 'schema'], 'contract/negative': [...CONSTRAINT_RULES, 'content-type'], 'scenario/positive': ['crud', 'business-rule'], @@ -122,6 +125,8 @@ 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 === 'optional-omitted') return loc === 'request.body#' ? undefined : bad('optional-omitted is checked on "request.body#" (the whole body)'); + if (p.rule === 'variant') return /^request\.body#(\/[^/]*)*\/@\d+$/.test(loc) ? undefined : bad('variant names a body pointer and a branch: request.body#/@'); if (p.rule === 'collection-contains' || p.rule === 'fixture') return loc === 'operation' ? undefined : bad(`${p.rule} is checked on "operation"`); if (p.rule === 'unique') return loc.startsWith('response.body#') ? undefined : bad('unique names a response body field'); if (p.rule === 'filter' || p.rule === 'pagination') return /^request\.query#\/[^/]*$/.test(loc) ? undefined : bad(`${p.rule} names a query parameter`); diff --git a/src/cases/validate.ts b/src/cases/validate.ts index 6079ecf..c8a9c2f 100644 --- a/src/cases/validate.ts +++ b/src/cases/validate.ts @@ -228,12 +228,25 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine last = bad(`"${leaf}" is not a property`); continue; } + if (rule === 'variant') { + // request.body#/@: branch n of a oneOf / anyOf at . + const m = /^(.*)\/@(\d+)$/.exec(body[2]); + const at = m ? walk(s, m[1]) : { error: { code: 'INVALID_CASE_LOCATION', pointer: '', reason: `"${body[2]}" does not end with /@` } as Finding }; + if (at.error) { + last = at.error.code === 'CASE_LOCATION_UNRESOLVED' ? at.error : { ...at.error, reason: `${o.key}: ${at.error.reason}` }; + continue; + } + const branches = (at.node?.oneOf ?? at.node?.anyOf) as unknown[] | undefined; + if (Array.isArray(branches) && Number(m![2]) < branches.length) return undefined; + last = bad(`no oneOf / anyOf branch ${m![2]} at ${body[1]} body ${m![1] || '(root)'}`); + continue; + } const r = walk(s, body[2]); if (r.error) { last = r.error.code === 'CASE_LOCATION_UNRESOLVED' ? r.error : { ...r.error, reason: `${o.key}: ${r.error.reason}` }; continue; } - if (!['schema', 'type', 'required', 'nullable', 'enum', 'const', 'unique'].includes(rule) && !ruleFits(r.node, rule)) { + if (!['schema', 'type', 'required', 'nullable', 'enum', 'const', 'unique', 'optional-omitted'].includes(rule) && !ruleFits(r.node, rule)) { last = { code: 'INVALID_CASE_RULE_FOR_SCHEMA', pointer: '', reason: `${o.key}: "${rule}" does not apply to ${body[1]} body ${body[2] || '(root)'}` }; continue; } diff --git a/src/contract/contract.py b/src/contract/contract.py index 53f7bd4..2fb4e7f 100644 --- a/src/contract/contract.py +++ b/src/contract/contract.py @@ -203,6 +203,19 @@ def poll(fn, done, timeout_ms: int, interval_ms: int): return v +def without_fields(payload: Any, ptrs: list) -> Any: + """A copy of a payload without the fields at these JSON pointers (array elements by index).""" + out = copy.deepcopy(payload) + for ptr in ptrs: + keys = [_unesc(k) for k in ptr.split("/")[1:]] + node = out + for k in keys[:-1]: + node = node[int(k)] if isinstance(node, list) else (node or {}).get(k) + if isinstance(node, dict): + node.pop(keys[-1], None) + return out + + def with_value(payload: Any, ptr: str, value: Any) -> Any: out = copy.deepcopy(payload) keys = [k.replace("~1", "/").replace("~0", "~") for k in ptr.split("/")[1:]] diff --git a/src/contract/validator.ts b/src/contract/validator.ts index 1a74db6..6cd91e6 100644 --- a/src/contract/validator.ts +++ b/src/contract/validator.ts @@ -227,7 +227,7 @@ function resolve(doc: any, pointer: string, depth = 0): { node: any; pointer: st } /** OpenAPI 3.0 `nullable: true` → JSON Schema `type: [T, "null"]`. */ -function nullableToJsonSchema(node: any): any { +export function nullableToJsonSchema(node: any): any { if (Array.isArray(node)) return node.map(nullableToJsonSchema); if (!node || typeof node !== 'object') return node; for (const k of Object.keys(node)) node[k] = nullableToJsonSchema(node[k]); diff --git a/src/generate/coverage.ts b/src/generate/coverage.ts index b4495f3..ca7e886 100644 --- a/src/generate/coverage.ts +++ b/src/generate/coverage.ts @@ -47,6 +47,10 @@ export interface Exercised { invalidInput: boolean; // there are body / parameter cases errors?: ErrorPlan; deleteTwice: boolean; + /** Code of the reason the success call is not sent (positiveCode), when it is not. */ + positiveCode?: string | null; + /** False when no request is sent at all (a write without confirmed cleanup): no status of it is exercised. */ + reachable?: boolean; } /** Documented statuses no generated test exercises (2xx counts as exercised by the success call). */ @@ -60,11 +64,21 @@ export function uncheckedStatuses(op: Operation, x: Exercised): { status: string if (x.errors?.conflict) hit.add('409'); if (x.errors?.preconditionFailed) hit.add('412'); if (x.errors?.unsupportedMediaType) hit.add('415'); + for (const c of x.errors?.envCredentials ?? []) hit.add(c.status); // 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') })); + .map((r) => ({ status: r.status, code: reason(r.status) ?? codeFor(r.status, x) })); +} + +/** Why a documented status is not exercised, when no error gap names it. */ +function codeFor(status: string, x: Exercised): string { + if (/^(5|default)/i.test(status)) return 'UNREACHABLE_RESPONSE_STATUS'; + // Nothing is sent to this operation: every status has the success call's reason (e.g. MISSING_CLEANUP). + if (x.reachable === false && x.positiveCode) return x.positiveCode; + if (/^2/.test(status) && x.positiveCode) return x.positiveCode; + return /^4/.test(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. */ diff --git a/src/generate/error-cases.ts b/src/generate/error-cases.ts index 0ffd7bd..a9f2d9c 100644 --- a/src/generate/error-cases.ts +++ b/src/generate/error-cases.ts @@ -20,9 +20,58 @@ export interface ErrorPlan { preconditionFailed?: { header: string; value: string }; /** 409: the same create payload twice, on fields a reviewed deps file names (conflictOn). */ conflict?: { fields: string[] }; + /** + * 401 / 403 with a credential a reviewed deps file names by its environment variable ("auth"): an expired one + * (401) or a valid one of an account that must be refused (403). The test is skipped when the variable is unset. + */ + envCredentials?: EnvCredential[]; gaps: CoverageGap[]; } +export interface EnvCredential { + kind: 'expired' | 'forbidden'; + status: '401' | '403'; + env: string; + /** Where the credential goes: a header (with a prefix such as "Bearer ") or a query parameter. */ + header?: string; + query?: string; + prefix: string; + /** forbidden: the documented path values are used (a missing resource must not answer before the refusal). */ + knownPath: boolean; +} + +/** deps file "auth": credentials the reviewer provides through environment variables (never in the file). */ +export interface AuthConfig { + forbidden?: { credentialEnv: string; operations: string[] }; + expired?: { credentialEnv: string }; +} + +/** Checks a deps "auth" section against the spec; problems are INVALID_REVIEWED_CONFIG gaps of the operation named. */ +export function checkAuthConfig(auth: AuthConfig | undefined, ops: Operation[]): string[] { + if (!auth) return []; + const errors: string[] = []; + const envName = /^[A-Z][A-Z0-9_]*$/; + if (auth.forbidden) { + if (!envName.test(String(auth.forbidden.credentialEnv))) errors.push('auth.forbidden.credentialEnv must name an environment variable (e.g. API_FORBIDDEN_TOKEN)'); + for (const id of auth.forbidden.operations ?? []) if (!ops.some((o) => o.operationId === id)) errors.push(`auth.forbidden: operation "${id}" is not in the spec`); + } + if (auth.expired && !envName.test(String(auth.expired.credentialEnv))) errors.push('auth.expired.credentialEnv must name an environment variable (e.g. API_EXPIRED_TOKEN)'); + return errors; +} + +/** Where a credential of the operation's (single) security scheme goes. */ +function placement(doc: OpenApiDoc, op: Operation): { header?: string; query?: string; prefix: string } | string { + const req = op.security[0] ?? []; + if (req.length !== 1) return req.length ? 'several schemes must be satisfied together' : 'the operation needs no credentials'; + const s = (doc as any).components?.securitySchemes?.[req[0]]; + const type = String(s?.type ?? '').toLowerCase(); + if (type === 'http' && String(s.scheme).toLowerCase() === 'bearer') return { header: 'Authorization', prefix: 'Bearer ' }; + if (type === 'oauth2' || type === 'openidconnect') return { header: 'Authorization', prefix: 'Bearer ' }; + if (type === 'apikey' && s.in === 'header') return { header: s.name, prefix: '' }; + if (type === 'apikey' && s.in === 'query') return { query: s.name, prefix: '' }; + return `security scheme "${req[0]}" (${type || 'unknown'}) takes no single token`; +} + const INVALID_TOKEN = 'api-agent-invalid-token'; const PRECONDITION_VALUES: Record = { 'if-match': '"api-agent-no-such-etag"', @@ -42,6 +91,8 @@ export interface ErrorInput { reachable: boolean; /** The operation is the first one of its path documenting 405 (one case per path). */ firstWith405: boolean; + /** Reviewed deps "auth" section. */ + auth?: AuthConfig; } export function errorPlan(i: ErrorInput): ErrorPlan { @@ -98,7 +149,26 @@ export function errorPlan(i: ErrorInput): ErrorPlan { 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)'); + // 401 with an expired credential (deps auth.expired): the same safe request as the invalid-credential case. + const envCredentials: EnvCredential[] = []; + if (i.auth?.expired && plan.invalidCredentials) { + const at = placement(doc, op); + if (typeof at === 'string') gap('UNSUPPORTED_SCHEMA_KEYWORD', '401', `expired credential: ${at}`); + else envCredentials.push({ kind: 'expired', status: '401', env: i.auth.expired.credentialEnv, ...at, knownPath: false }); + } + // 403 with a valid credential of an account that must be refused (deps auth.forbidden), for the operations named. + const listed = !!op.operationId && (i.auth?.forbidden?.operations ?? []).includes(op.operationId); + if (listed && !codes.has('403')) plan.gaps.push({ code: 'INVALID_REVIEWED_CONFIG', location: 'request.security', reason: `deps auth.forbidden names ${op.operationId}, but it documents no 403` }); + if (codes.has('403')) { + const at = placement(doc, op); + const unknownPath = op.params.filter((p) => p.in === 'path' && p.knownValue === undefined); + if (!listed) gap('UNCONFIRMED_BUSINESS_RULE', '403', 'needs a reviewed role / scope configuration: deps "auth.forbidden" (an account that must be refused)'); + else if (!['get', 'head'].includes(op.method)) gap('UNSAFE_LIVE_CHECK', '403', 'a write with an account that must be refused could still change data if the API lets it through'); + else if (unknownPath.length) gap('MISSING_RESOURCE_SOURCE', '403', `no value for ${unknownPath.map((p) => `path "${p.name}"`).join(', ')}: a missing resource could answer before the refusal`); + else if (typeof at === 'string') gap('UNSUPPORTED_SCHEMA_KEYWORD', '403', at); + else envCredentials.push({ kind: 'forbidden', status: '403', env: i.auth!.forbidden!.credentialEnv, ...at, knownPath: true }); + } + if (envCredentials.length) plan.envCredentials = envCredentials; 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 7affc0c..025e576 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -14,8 +14,9 @@ import { headRevision } from '../change/baseline.js'; import { isUrl } from '../change/network.js'; import { bodyCasesDetailed, compositionGaps, type CoverageGap } from './body-cases.js'; import { paramCasesDetailed, sendable } from './param-cases.js'; -import { errorPlan } from './error-cases.js'; +import { checkAuthConfig, errorPlan } from './error-cases.js'; import { collectionGaps, resolveCollection } from './collection.js'; +import { bodyVariants as variantsOf, type BodyVariant } from './variants.js'; import { collectionStrategy, planCollectionTests } from './collection-tests.js'; import { tsFixtureModule, fixtureModule, type CollectionInput } from './collection-render.js'; import type { LoadedFixture } from '../fixtures/fixtures.js'; @@ -244,6 +245,9 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp if (op && !chainBlock.has(op)) chainBlock.set(op, c.question); } } + // Reviewed deps "auth": a broken section is not used; its problems are gaps of the operations it names. + const authErrors = checkAuthConfig(o.deps?.auth, ops); + const authOk = !authErrors.length; // Reviewed collection mappings (deps "collection"): checked strictly against the spec; errors become gaps. const collectionOf = new Map['collection']> }>(); const collectionErrors = new Map(); @@ -369,7 +373,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp 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 errors = op.deprecated ? { gaps: [] } : errorPlan({ doc: spec.doc, op, ops, chain: plan?.chain, role: errRole, hasUpdatePayload: plan?.updatePayload !== undefined, reachable, firstWith405, auth: authOk ? o.deps?.auth : undefined }); const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors, business: (o.scenarios ?? []).filter((b) => b.primaryOp === op) }; let collPlan: ReturnType | undefined; if (coll && input.positive && !op.deprecated) { @@ -380,16 +384,31 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const fixture = input.positive && !op.deprecated ? o.fixtures?.find((f) => f.op === op) : undefined; if (fixture) input.fixture = fixture; const fixtureGaps: CoverageGap[] = (o.fixtureErrors ?? []).filter((e) => e.operationId && e.operationId === op.operationId).flatMap((e) => e.errors.map((reason) => ({ code: 'INVALID_REVIEWED_CONFIG', location: 'operation', reason: `${e.file}: ${reason}` }))); - const collGaps: CoverageGap[] = [...fixtureGaps, ...(collectionErrors.get(op.key) ?? []), ...(collPlan?.gaps ?? []), ...(coll ? [] : collectionGaps(spec.doc, op, false))]; + const authGaps: CoverageGap[] = authErrors.filter((e) => !!op.operationId && e.includes(`"${op.operationId}"`) || (op === ops[0] && !/operation "/.test(e))).map((reason) => ({ code: 'INVALID_REVIEWED_CONFIG', location: 'request.security', reason })); + const collGaps: CoverageGap[] = [...authGaps, ...fixtureGaps, ...(collectionErrors.get(op.key) ?? []), ...(collPlan?.gaps ?? []), ...(coll ? [] : collectionGaps(spec.doc, op, false))]; + // Positive body variants of a create / update with a confirmed chain (written with cleanup only). + let variantResult: { variants: BodyVariant[]; gaps: CoverageGap[] } | undefined; + if (plan && input.positive && !op.deprecated && (plan.chain.create === op || (plan.chain.update === op && plan.updatePayload !== undefined))) { + const content = resolvePointer(spec.doc, `${operationPointer(op)}/requestBody`).node?.content ?? {}; + const key = Object.keys(content).find((k) => k.includes('json')); + const value = plan.chain.create === op ? plan.createPayload : plan.updatePayload; + if (key && value !== undefined) { + // Through any $ref (requestBodies, schemas): the pointer ajv compiles must exist as written. + const pointer = resolvePointer(spec.doc, `${operationPointer(op)}/requestBody/content/${key.replace(/~/g, '~0').replace(/\//g, '~1')}/schema`).pointer; + variantResult = variantsOf(spec.doc, pointer, content[key].schema, value, plan.chain.create === op ? (plan.chain.fill ?? []).map((f) => f.field) : []); + if (variantResult.variants.length) input.bodyVariants = variantResult.variants; + } + } const counts = suiteCounts(input); const variants = input.positive && !plan && op.method === 'get' ? queryVariants(op) : []; - const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants, errors, business: input.business, collection: collPlan, collectionChain: coll?.plan.chain, fixture: !!fixture }, uidOf); + const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants, errors, business: input.business, collection: collPlan, collectionChain: coll?.plan.chain, fixture: !!fixture, bodyVariants: input.bodyVariants }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. // oneOf / anyOf in a payload that is sent: the other branches are reported (never dropped silently). 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) : []; + // With body variants, a oneOf / anyOf branch is a gap only when it could not be sent (variants.ts says why). + const variantGaps: CoverageGap[] = variantResult ? variantResult.gaps : 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[] => { @@ -418,7 +437,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp 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 }), + uncheckedStatuses: uncheckedStatuses(op, { positive: input.positive, notFound: !!notFound, unauthorized, validation: rej.validation, invalidInput: bCases.length + qCases.length > 0, errors, deleteTwice: scn.deleteTwice, positiveCode: pCode, reachable }), uncheckedRequestContentTypes: req.contentTypes, uncheckedSecurityAlternatives: req.securityAlternatives, }); diff --git a/src/generate/graph.ts b/src/generate/graph.ts index 733d109..3040cad 100644 --- a/src/generate/graph.ts +++ b/src/generate/graph.ts @@ -44,6 +44,8 @@ export interface Candidate { } export interface DepsFile { + /** Reviewed credentials for 401 / 403 cases, by environment variable name (never the values). */ + auth?: import('./error-cases.js').AuthConfig; scenarios: { create: string; idFrom: string; diff --git a/src/generate/python.ts b/src/generate/python.ts index 2954fc9..cea5202 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -3,6 +3,7 @@ import { requiredRequest } from './param-cases.js'; import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/dsl.js'; import type { CrudChain } from './graph.js'; import { pyCollectionPrelude, pyCollectionTests, pyFixtureTest, pyLifecycle } from './collection-render.js'; +import { pyVariantTests } from './variant-render.js'; import { hasFill, queryVariants, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; /** @@ -519,6 +520,7 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { L.push(...pyCollectionTests(s, s.collection)); } if (s.fixture) L.push(...pyFixtureTest(s, s.fixture)); + L.push(...pyVariantTests(s)); return finish(L); } @@ -542,6 +544,26 @@ function pyErrorTests(s: SuiteInput): string[] { '', ); } + (e.envCredentials ?? []).forEach((c, n) => { + const what = c.kind === 'expired' ? 'an_expired_credential' : 'a_refused_account'; + const params = pyLit({ ...req.params }, 4); + const headers = pyLit({ ...req.headers }, 4); + const cred = `${str(c.prefix)} + credential`; + const path = c.knownPath ? pathExpr(op) : pathExpr(op, plan?.chain.param, '"unused"'); + L.push( + withId(NEG, s.ids?.functional.envCredentials?.[n]), + `def test_returns_documented_${c.status}_for_${what}(anonymous_api):`, + ' import os', + '', + ` credential = os.environ.get(${str(c.env)}, "")`, + ' if not credential:', + ` pytest.skip(${str(`${c.env} is not set: the reviewed ${c.kind === 'expired' ? 'expired credential (deps auth.expired)' : 'refused account (deps auth.forbidden)'} is not available`)})`, + ` res = anonymous_api.${op.method}(${path}, params=${c.query ? `{**${params}, ${str(c.query)}: ${cred}}` : params}, headers=${c.header ? `{**${headers}, ${str(c.header)}: ${cred}}` : headers})`, + ` ${statusIs(op, c.status)}`, + '', + '', + ); + }); 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. diff --git a/src/generate/templates.ts b/src/generate/templates.ts index f7f009f..c2347b6 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -9,6 +9,8 @@ import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/d import { boundaryValues } from './boundaries.js'; import { tsCollectionImports, tsCollectionPrelude, tsCollectionTests, tsFixtureImport, tsFixtureTest, tsLifecycle, type CollectionInput } from './collection-render.js'; import type { LoadedFixture } from '../fixtures/fixtures.js'; +import type { BodyVariant } from './variants.js'; +import { tsVariantImports, tsVariantTests } from './variant-render.js'; /** Payloads and assumptions for one confirmed resource chain. */ export interface ChainPlan { @@ -234,6 +236,8 @@ export interface SuiteInput { collection?: CollectionInput; /** An approved fixture of this list operation (strategy B). */ fixture?: LoadedFixture; + /** Positive request-body variants of a create / update (only required fields, other oneOf / anyOf branches). */ + bodyVariants?: BodyVariant[]; } export type Role = 'create' | 'read' | 'update' | 'delete'; @@ -263,12 +267,12 @@ export function suiteCounts(s: SuiteInput): Record { const sc = scenarioCases(s); const e = s.errors; const base = { - functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0) + (e?.invalidCredentials ? 1 : 0) + (e?.methodNotAllowed ? 1 : 0) + (e?.preconditionFailed && s.plan ? 1 : 0), + functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0) + (e?.invalidCredentials ? 1 : 0) + (e?.envCredentials?.length ?? 0) + (e?.methodNotAllowed ? 1 : 0) + (e?.preconditionFailed && s.plan ? 1 : 0), contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length + (e?.unsupportedMediaType && s.plan ? 1 : 0), }; return { contract: base.contract, - functional: base.functional + (s.collection?.plan.tests.length ?? 0) + (s.fixture ? 1 : 0), + functional: base.functional + (s.collection?.plan.tests.length ?? 0) + (s.fixture ? 1 : 0) + (s.bodyVariants?.length ?? 0), scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0) + (sc.conflict ? 1 : 0) + (sc.deleteTwice ? 1 : 0) + (s.business?.length ?? 0) + (s.collection?.plan.lifecycle ? 1 : 0), }; } @@ -366,10 +370,10 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { const chain = plan?.chain; const role = roleOf(op, plan); const fx = chain ? 'api' : apiFixture(op); - const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan) || !!s.collection?.plan.tests.length; - const errorStatus = !!(s.errors?.invalidCredentials || s.errors?.methodNotAllowed || s.errors?.preconditionFailed); + const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan) || !!s.collection?.plan.tests.length || !!s.bodyVariants?.length; + const errorStatus = !!(s.errors?.invalidCredentials || s.errors?.envCredentials?.length || s.errors?.methodNotAllowed || s.errors?.preconditionFailed); const coll = s.collection?.plan.tests.length ? s.collection : undefined; - const names = [...new Set(['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : []), ...(coll ? tsCollectionImports('functional') : []), ...(s.fixture ? ['itemsOf', 'expectMatchesFixture'] : [])])]; + const names = [...new Set(['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : []), ...(coll ? tsCollectionImports('functional') : []), ...(s.fixture ? ['itemsOf', 'expectMatchesFixture'] : []), ...tsVariantImports(s)])]; const L = suiteHeader('functional', s, meta, ['Checks the behavior of the endpoint: status and result. The response schema is checked in contract.spec.ts.', ...(coll ? ['Collection checks run on records the tests create (controlled datasets) or, where marked read-only, on existing data.'] : [])]); L.push(...imports(s, names, usesHelpers), ...(s.fixture ? [tsFixtureImport(s.fixture)] : []), ...(coll ? ['', ...tsCollectionPrelude(s, coll)] : ['']), `test.describe('${op.key} · functional', { tag: '@functional' }, () => {`); @@ -419,6 +423,7 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { L.push(...errorTests(s)); if (coll) L.push(...tsCollectionTests(s, coll)); if (s.fixture) L.push(...tsFixtureTest(s, s.fixture)); + if (s.bodyVariants?.length) L.push(...tsVariantTests(s)); return close(L); } @@ -490,6 +495,27 @@ function errorTests(s: SuiteInput): string[] { '', ); } + (e.envCredentials ?? []).forEach((c, n) => { + // The credential comes from the environment at run time (a reviewed deps "auth" entry names the variable). + const params = { ...req.params }; + const headers = { ...req.headers }; + const cred = `${q(c.prefix)} + credential`; + const opts = [ + c.query ? `params: { ...${JSON.stringify(params)}, ${q(c.query)}: ${cred} }` : Object.keys(params).length ? `params: ${JSON.stringify(params)}` : '', + c.header ? `headers: { ...${JSON.stringify(headers)}, ${q(c.header)}: ${cred} }` : Object.keys(headers).length ? `headers: ${JSON.stringify(headers)}` : '', + ].filter(Boolean).join(', '); + const args = c.knownPath ? pathArgs(op, ref) : pathArgs(op, ref, plan?.chain.param, "'unused'"); + const what = c.kind === 'expired' ? 'an expired credential' : 'an account that must be refused'; + L.push( + ` test(${q(`returns documented ${c.status} for ${what} (${c.env})`)}, ${testOptions('negative', s.ids?.functional.envCredentials?.[n])}, async ({ publicApi }) => {`, + ` const credential = process.env.${c.env} ?? '';`, + ` test.skip(!credential, ${q(`${c.env} is not set: the reviewed ${c.kind === 'expired' ? 'expired credential (deps auth.expired)' : 'refused account (deps auth.forbidden)'} is not available`)});`, + ` const res = await ${apiCall(ref, 'publicApi', args, `{ ${opts} }`)};`, + ` expectStatus(res, ['${c.status}'], '${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. @@ -892,6 +918,18 @@ export async function poll(fn: () => Promise, done: (v: T) => boolean, tim return v; } +/** A copy of a payload without the fields at these JSON pointers (array elements by index). */ +export function withoutFields(payload: T, ptrs: string[]): T { + const out = structuredClone(payload) as any; + for (const ptr of ptrs) { + const keys = ptr.split('/').slice(1).map((k) => k.replace(/~1/g, '/').replace(/~0/g, '~')); + let node = out; + for (const k of keys.slice(0, -1)) node = node == null ? undefined : node[k]; + if (node && typeof node === 'object') delete node[keys[keys.length - 1]]; + } + return out; +} + /** A copy of a payload with one field (JSON pointer through objects) set. */ export function withValue(payload: T, ptr: string, value: unknown): T { const out = structuredClone(payload) as any; diff --git a/src/generate/variant-render.ts b/src/generate/variant-render.ts new file mode 100644 index 0000000..804bffe --- /dev/null +++ b/src/generate/variant-render.ts @@ -0,0 +1,105 @@ +import { apiCall } from './api-objects.js'; +import type { BodyVariant } from './variants.js'; +import { expectSuccess, hasFill, optionsWith, pathArgs, roleOf, testOptions, type SuiteInput } from './templates.js'; +import { assertSuccess, pathExpr, pyLit, pyName, pyRequired, resourceModule, withId } from './python.js'; + +/** + * Positive request-body variants (src/generate/variants.ts) in functional.spec.ts / test_functional.py of the + * create or update operation of a confirmed chain. The status must be the documented success and the response must + * match the contract; whatever the test creates is removed in finally. Same tests and case IDs in both languages. + */ + +const js = (v: unknown) => JSON.stringify(v); + +/** The fresh payload of the role with the variant applied (TypeScript expression). */ +function tsPayload(s: SuiteInput, v: BodyVariant): string { + const role = roleOf(s.op, s.plan); + const fresh = role === 'create' ? (hasFill(s.plan) ? 'await resource.newCreatePayload(api)' : 'resource.newCreatePayload()') : 'resource.newUpdatePayload()'; + return v.remove ? `withoutFields(${fresh}, ${js(v.remove)})` : `withValue(${fresh}, ${js(v.set!.pointer)}, ${js(v.set!.value)})`; +} + +export const tsVariantImports = (s: SuiteInput) => (s.bodyVariants?.length ? ['expectContract', ...(s.bodyVariants.some((v) => v.remove) ? ['withoutFields'] : []), ...(s.bodyVariants.some((v) => v.set) ? ['withValue'] : [])] : []); + +export function tsVariantTests(s: SuiteInput): string[] { + const { op, refs, plan } = s; + const chain = plan!.chain; + const ref = refs.get(op)!; + const role = roleOf(op, plan); + const call = (idVar?: string) => apiCall(ref, 'api', pathArgs(op, ref, chain.param, idVar), optionsWith(op, '{ data: payload }')); + const check = (i: string) => [`${i}${expectSuccess(op)}`, `${i}await expectContract(res, '${op.method}', ${js(op.path)});`]; + return (s.bodyVariants ?? []).flatMap((v, n) => { + const opts = testOptions('positive', s.ids?.functional.bodyVariants?.[n]); + if (role === 'create') { + return [ + ` test(${js(v.title)}, ${opts}, async ({ api }) => {`, + ` const payload = ${tsPayload(s, v)};`, + ` const res = await ${call()};`, + ` try {`, + ...check(' '), + ` } finally {`, + ` await resource.removeIfCreated(api, res);`, + ` }`, + ` });`, + '', + ]; + } + return [ + ` test(${js(v.title)}, ${opts}, async ({ api }) => {`, + ` const { id } = await resource.create(api);`, + ` try {`, + ` const payload = ${tsPayload(s, v)};`, + ` const res = await ${call('id')};`, + ...check(' '), + ` } finally {`, + ` await resource.remove(api, id);`, + ` }`, + ` });`, + '', + ]; + }); +} + +export function pyVariantTests(s: SuiteInput): string[] { + const { op, plan } = s; + if (!s.bodyVariants?.length) return []; + const chain = plan!.chain; + const role = roleOf(op, plan); + const fx = resourceModule(plan!).replace(/_resource$/, ''); + const names = new Set(); + const L = ['from contract import with_value, without_fields # noqa: E402,F401', '', '']; + s.bodyVariants.forEach((v, n) => { + let name = v.kind === 'optional-omitted' ? 'test_accepts_only_required_fields' : pyName(`test_accepts_${v.location.replace(/^request\.body#/, '').replace(/@/g, 'branch_')}`).replace(/_+/g, '_'); + while (names.has(name)) name += '_2'; + names.add(name); + const fresh = role === 'create' ? `${fx}.new_create_payload()` : `${fx}.new_update_payload()`; + const payload = v.remove ? `without_fields(${fresh}, ${pyLit(v.remove)})` : `with_value(${fresh}, ${pyLit(v.set!.pointer)}, ${pyLit(v.set!.value, 4)})`; + const check = [` ${assertSuccess(op)}`, ` contract.expect(res, ${js(op.method)}, ${js(op.path)})`]; + L.push(withId('@pytest.mark.positive', s.ids?.functional.bodyVariants?.[n])); + if (role === 'create') { + L.push( + `def ${name}(api, contract, ${fx}):`, + ` """${v.title.replace(/"/g, "'")}"""`, + ` payload = ${payload}`, + ` res = api.${op.method}(${pathExpr(op)}, json=payload${pyRequired(op)})`, + ' try:', + ...check, + ' finally:', + ` ${fx}.remove_if_created(res)`, + '', + '', + ); + } else { + // created_ removes the precondition record after the test (fixture teardown). + L.push( + `def ${name}(api, contract, ${fx}, created_${fx}):`, + ` """${v.title.replace(/"/g, "'")}"""`, + ` payload = ${payload}`, + ` res = api.${op.method}(${pathExpr(op, chain.param, `created_${fx}`)}, json=payload${pyRequired(op)})`, + ...check.map((l) => l.slice(4)), + '', + '', + ); + } + }); + return L; +} diff --git a/src/generate/variants.ts b/src/generate/variants.ts new file mode 100644 index 0000000..aedc72f --- /dev/null +++ b/src/generate/variants.ts @@ -0,0 +1,179 @@ +import { Ajv, type ValidateFunction } from 'ajv'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import addFormatsModule from 'ajv-formats'; +import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; +import { nullableToJsonSchema } from '../contract/validator.js'; +import { ARRAY, bodyPointer } from '../cases/ids.js'; +import { sampleFromSchema } from './sample.js'; +import type { CoverageGap, PathSeg } from './body-cases.js'; + +/** + * Positive request-body variants (docs/SUPPORT_MATRIX.md, "Request body: positive variants"). Each one is a valid + * payload that differs from the documented example in one documented way, so it can expose an API that accepts + * only the example's shape: + * - optional-omitted: only the required fields (optional ones removed wherever the schema allows it); + * - variant: another branch of a oneOf / anyOf, with a sample built from that branch. + * Every variant is checked against the request schema with ajv before a test is written; one that is not valid is + * a gap with the reason, never a test that would fail for the wrong reason. + */ + +export interface BodyVariant { + kind: 'optional-omitted' | 'variant'; + /** Case location: request.body# or request.body#/@. */ + location: string; + title: string; + /** Runtime transformation of the fresh payload: JSON pointers (array element 0 for "*") to remove, or one value to set. */ + remove?: string[]; + set?: { pointer: string; value: unknown }; +} + +const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; +const DOC_ID = 'request.json'; +const cache = new WeakMap(); + +/** ajv over the spec for REQUEST bodies (readOnly / writeOnly are annotations here, not checks). */ +function requestAjv(doc: OpenApiDoc): Ajv { + let entry = cache.get(doc as object); + if (!entry) { + const is31 = /^3\.[12]\./.test(String((doc as any).openapi ?? '')); + const copy = structuredClone(doc); + const opts = { strict: false, allErrors: true, validateSchema: false } as const; + const ajv = (is31 ? new Ajv2020(opts) : new Ajv(opts)) as Ajv; + addFormats(ajv); + ajv.addSchema(is31 ? copy : nullableToJsonSchema(copy), DOC_ID); + entry = { ajv }; + cache.set(doc as object, entry); + } + return entry.ajv; +} + +/** A validator for the request schema at `schemaPointer` (an operation's requestBody JSON schema). */ +export function requestValidator(doc: OpenApiDoc, schemaPointer: string): ValidateFunction { + return requestAjv(doc).compile({ $ref: `${DOC_ID}#${schemaPointer}` }); +} + +/** A validator for an inline schema of the spec (a oneOf / anyOf branch): its local $refs point into the spec. */ +function inlineValidator(doc: OpenApiDoc, schema: any): ValidateFunction { + const is31 = /^3\.[12]\./.test(String((doc as any).openapi ?? '')); + const rewrite = (n: any): any => { + if (Array.isArray(n)) return n.map(rewrite); + if (!n || typeof n !== 'object') return n; + const out: any = {}; + for (const [k, v] of Object.entries(n)) out[k] = k === '$ref' && typeof v === 'string' && v.startsWith('#') ? `${DOC_ID}${v}` : rewrite(v); + return out; + }; + const copy = rewrite(structuredClone(schema)); + return requestAjv(doc).compile(is31 ? copy : nullableToJsonSchema(copy)); +} + +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 runtimePointer = (path: PathSeg[]) => path.map((p) => '/' + (p === ARRAY ? '0' : String(p).replace(/~/g, '~0').replace(/\//g, '~1'))).join(''); + +function removeAt(root: any, path: PathSeg[]): any { + const out = structuredClone(root); + let node = out; + for (const seg of path.slice(0, -1)) node = node?.[seg === ARRAY ? 0 : (seg as string)]; + const last = path[path.length - 1]; + if (node && typeof node === 'object' && last !== ARRAY) delete node[last as string]; + return out; +} + +function setAt(root: any, path: PathSeg[], value: unknown): any { + if (!path.length) return structuredClone(value); + const out = structuredClone(root); + let node = out; + for (const seg of path.slice(0, -1)) node = node?.[seg === ARRAY ? 0 : (seg as string)]; + node[path[path.length - 1] === ARRAY ? 0 : (path[path.length - 1] as string)] = structuredClone(value); + return out; +} + +const COMPOSITE = ['oneOf', 'anyOf', 'if', 'dependentRequired', 'dependentSchemas', 'dependencies', 'not']; + +/** Optional properties present in the value, outer ones first; never inside a oneOf / anyOf / conditional subtree. */ +function optionalPaths(doc: OpenApiDoc, raw: any, value: unknown, path: PathSeg[], keep: Set, depth = 0): PathSeg[][] { + const s = deref(doc, raw); + if (!s || depth > 12 || COMPOSITE.some((k) => s[k] !== undefined)) return []; + const parts = [s, ...(Array.isArray(s.allOf) ? s.allOf.map((p: any) => deref(doc, p)) : [])]; + if (parts.some((p) => p && COMPOSITE.some((k) => p[k] !== undefined))) return []; + if (Array.isArray(value)) return value.length && s.items ? optionalPaths(doc, s.items, value[0], [...path, ARRAY], keep, depth + 1) : []; + if (!value || typeof value !== 'object') return []; + const props = Object.assign({}, ...parts.map((p) => p?.properties ?? {})); + const required = new Set(parts.flatMap((p) => p?.required ?? [])); + const out: PathSeg[][] = []; + for (const [k, v] of Object.entries(value as Record)) { + const here = [...path, k]; + if (!required.has(k) && props[k] !== undefined && !(path.length === 0 && keep.has(k))) out.push(here); + } + for (const [k, v] of Object.entries(value as Record)) { + if (props[k] !== undefined) out.push(...optionalPaths(doc, props[k], v, [...path, k], keep, depth + 1)); + } + return out; +} + +/** oneOf / anyOf points in the value (like compositionGaps): where another branch can be sent. */ +function compositions(doc: OpenApiDoc, raw: any, value: unknown, path: PathSeg[], depth = 0): { path: PathSeg[]; key: 'oneOf' | 'anyOf'; branches: any[] }[] { + const s = deref(doc, raw); + if (!s || depth > 12) return []; + const out: { path: PathSeg[]; key: 'oneOf' | 'anyOf'; branches: any[] }[] = []; + for (const key of ['oneOf', 'anyOf'] as const) if (Array.isArray(s[key]) && s[key].length > 1) out.push({ path, key, branches: s[key] }); + if (Array.isArray(value) && s.items && value.length) out.push(...compositions(doc, s.items, value[0], [...path, ARRAY], depth + 1)); + else if (value && typeof value === 'object' && !Array.isArray(value) && s.properties) { + for (const [k, sub] of Object.entries(s.properties)) if (k in (value as object)) out.push(...compositions(doc, sub, (value as any)[k], [...path, k], depth + 1)); + } + return out; +} + +/** + * Variants of one payload. `schemaPointer` locates the operation's JSON request schema in the spec; `keep` lists + * top-level fields that must stay (deps "fill": values from existing data). Gaps say what could not be varied. + */ +export function bodyVariants(doc: OpenApiDoc, schemaPointer: string, schema: any, payload: unknown, keep: string[] = []): { variants: BodyVariant[]; gaps: CoverageGap[] } { + const variants: BodyVariant[] = []; + const gaps: CoverageGap[] = []; + if (!payload || typeof payload !== 'object') return { variants, gaps }; + const validate = requestValidator(doc, schemaPointer); + if (!validate(payload)) return { variants, gaps }; // the example itself is not valid: the body cases already say so + + // optional-omitted: remove optional fields one by one (outer first), keeping each removal only while the payload + // stays valid (minProperties, dependent rules...). Deterministic: the schema's own order. + const candidates = optionalPaths(doc, schema, payload, [], new Set(keep)); + let current: unknown = payload; + const removed: PathSeg[][] = []; + for (const p of candidates) { + if (removed.some((r) => r.length <= p.length && r.every((seg, i) => seg === p[i]))) continue; // its parent is gone + const next = removeAt(current, p); + if (validate(next)) { + current = next; + removed.push(p); + } + } + if (removed.length) { + variants.push({ kind: 'optional-omitted', location: 'request.body#', title: `accepts the payload with only its required fields (${removed.length} optional field(s) left out)`, remove: removed.map(runtimePointer) }); + } else if (candidates.length) { + gaps.push({ code: 'CANNOT_ISOLATE_RULE', location: 'request.body#', rule: 'optional-omitted', reason: 'no optional field can be left out without breaking another rule of the schema' }); + } + + // variant: every other oneOf / anyOf branch with a valid sample. + for (const c of compositions(doc, schema, payload, [])) { + const at = runtimePointer(c.path); + const sentValue = c.path.reduce((n, seg) => n?.[seg === ARRAY ? 0 : (seg as string)], payload); + // The branch(es) the example already sends are covered by the documented-success test. + const sent = c.branches.map((b) => inlineValidator(doc, b)(sentValue)); + c.branches.forEach((branch, i) => { + if (sent[i]) return; + const loc = `request.body#${bodyPointer(c.path)}/@${i}`; + const sample = sampleFromSchema(doc, branch); + if (!sample.ok) { + gaps.push({ code: 'UNCOVERED_VARIANT', location: `request.body#${bodyPointer(c.path)}`, rule: c.key, reason: `${c.key} branch ${i}: no valid sample (${sample.reason})` }); + return; + } + const candidate = setAt(payload, c.path, sample.value); + if (!validate(candidate)) { + gaps.push({ code: 'UNCOVERED_VARIANT', location: `request.body#${bodyPointer(c.path)}`, rule: c.key, reason: `${c.key} branch ${i}: its sample is not a valid payload (${(validate.errors ?? []).slice(0, 2).map((e) => `${e.instancePath || '(root)'} ${e.message}`).join('; ')})` }); + return; + } + variants.push({ kind: 'variant', location: loc, title: `accepts ${c.key} branch ${i} at ${bodyPointer(c.path) || '(body)'}`, set: { pointer: at, value: sample.value } }); + }); + } + return { variants, gaps }; +} diff --git a/src/report/quality-gates.ts b/src/report/quality-gates.ts new file mode 100644 index 0000000..cf3a788 --- /dev/null +++ b/src/report/quality-gates.ts @@ -0,0 +1,51 @@ +/** + * CI quality gates of a generated suite (scripts/coverage-summary.ts): cleanup of write tests, the active case IDs + * and the gaps against a reviewed baseline, TypeScript / Python parity. + */ + +export interface CleanupProblem { + test: string; + problem: string; +} + +/** + * Tests that create data must remove it whatever happens: in `finally`, through a fixture teardown (pytest + * created_), or with removeIfCreated / remove_if_created right after the write request and before any + * assertion (they never throw, so nothing can skip them). + */ +export function cleanupProblems(text: string, lang: 'typescript' | 'python'): CleanupProblem[] { + const out: CleanupProblem[] = []; + const blocks = lang === 'typescript' ? text.split(/\n test\(/).slice(1) : text.split(/\n(?=@pytest\.mark\.(?:positive|negative))/).slice(1); + for (const b of blocks) { + const title = b.split('\n')[lang === 'typescript' ? 0 : 1 + (b.includes('api_case_id') ? 1 : 0)]?.slice(0, 100) ?? ''; + const creates = lang === 'typescript' ? /resource\.create\(|\.create\(api, |removeIfCreated/.test(b) : /\w+\.create\(|remove_if_created|\.new_create_payload\(\)/.test(b); + if (!creates) continue; + const cleaned = + lang === 'typescript' + ? /finally\s*\{[\s\S]*(resource\.remove|removeIfCreated|reportCleanupFailure)/.test(b) || /=\s*await [^\n]+;\n\s*await resource\.removeIfCreated\(api, res\);/.test(b) + : /finally:[\s\S]*(\.remove\(|report_cleanup_failure|remove_if_created)/.test(b) || /def \w+\([^)]*created_\w+[^)]*\)/.test(b) || /res = api\.\w+\((?:(?!assert|contract\.)[\s\S])*?\)\n\s+\w+\.remove_if_created\(res\)/.test(b); + if (!cleaned) out.push({ test: title.trim(), problem: 'creates data without guaranteed cleanup' }); + } + return out; +} + +export interface BaselineDiff { + lostCases: string[]; + newCases: string[]; + newGaps: string[]; + closedGaps: string[]; +} + +/** Lost active cases and new gaps fail the gate until the reviewed baseline is updated with the PR. */ +export function compareBaseline(base: { activeCaseIds: string[]; gaps: string[] }, now: { activeCaseIds: string[]; gaps: string[] }): BaselineDiff { + const was = new Set(base.activeCaseIds); + const is = new Set(now.activeCaseIds); + const gapsWas = new Set(base.gaps); + const gapsIs = new Set(now.gaps); + return { + lostCases: base.activeCaseIds.filter((id) => !is.has(id)), + newCases: now.activeCaseIds.filter((id) => !was.has(id)), + newGaps: now.gaps.filter((g) => !gapsWas.has(g)), + closedGaps: base.gaps.filter((g) => !gapsIs.has(g)), + }; +} diff --git a/tests/fixtures/coverage/kitchen-sink.deps.json b/tests/fixtures/coverage/kitchen-sink.deps.json index e28e8f3..a5d6672 100644 --- a/tests/fixtures/coverage/kitchen-sink.deps.json +++ b/tests/fixtures/coverage/kitchen-sink.deps.json @@ -1,4 +1,15 @@ { + "auth": { + "forbidden": { + "credentialEnv": "API_FORBIDDEN_TOKEN", + "operations": [ + "listOrders" + ] + }, + "expired": { + "credentialEnv": "API_EXPIRED_TOKEN" + } + }, "scenarios": [ { "create": "createOrder", @@ -7,8 +18,13 @@ "read": "getOrder", "update": "updateOrder", "delete": "deleteOrder", - "conflictOn": ["customer"], - "echoes": ["total", "status"] + "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 index 8c38cd1..1fad68d 100644 --- a/tests/fixtures/coverage/kitchen-sink.expected-gaps.json +++ b/tests/fixtures/coverage/kitchen-sink.expected-gaps.json @@ -1,8 +1,7 @@ { "CANNOT_ISOLATE_RULE": 6, "MISSING_CLEANUP": 1, - "UNCONFIRMED_BUSINESS_RULE": 2, - "UNCOVERED_VARIANT": 2, + "UNCONFIRMED_BUSINESS_RULE": 1, "UNREACHABLE_RESPONSE_STATUS": 1, "UNSAFE_LIVE_CHECK": 1, "UNSUPPORTED_SCHEMA_KEYWORD": 1 diff --git a/tests/unit/coverage-depth.test.ts b/tests/unit/coverage-depth.test.ts new file mode 100644 index 0000000..6122495 --- /dev/null +++ b/tests/unit/coverage-depth.test.ts @@ -0,0 +1,175 @@ +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 { sampleFromSchema } from '../../src/generate/sample.js'; +import { bodyVariants, requestValidator } from '../../src/generate/variants.js'; +import { checkAuthConfig } from '../../src/generate/error-cases.js'; +import { parseCaseId } from '../../src/cases/ids.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { normalizeSpec } from '../../src/change/normalize.js'; +import { cleanupProblems, compareBaseline } from '../../src/report/quality-gates.js'; + +/** Coverage depth (docs/SUPPORT_MATRIX.md): body variants, reviewed auth cases, gap codes, CI quality gates. */ + +const ks = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); +const ksOps = buildCatalog(ks.doc); +const ksDeps = JSON.parse(await readFile('tests/fixtures/coverage/kitchen-sink.deps.json', 'utf8')); +const demo = await loadSpec('demo-api/openapi.yaml'); +const demoOps = buildCatalog(demo.doc); +const demoDeps = JSON.parse(await readFile('demo-api/deps.json', 'utf8')); + +async function gen(spec: typeof ks, ops: typeof ksOps, deps: unknown, lang: 'typescript' | 'python') { + const dir = await mkdtemp(join(tmpdir(), 'ata-depth-')); + const r = await generate(spec, ops, { outDir: dir, version: 'test', lang, deps: deps as any, maxCases: 500 }); + return { dir, r, read: (f: string) => readFile(join(dir, f), 'utf8') }; +} +const idsIn = (text: string) => [...text.matchAll(/(?:description: |caseId: )'([^']+)'|api_case_id\("([^"]+)"\)/g)].map((m) => m[1] ?? m[2]).filter((x) => x !== 'c.caseId'); + +describe('positive request-body variants', () => { + const schema = { $ref: '#/components/schemas/OrderInput' }; + const base = (sampleFromSchema(ks.doc, schema) as any).value; + const r = bodyVariants(ks.doc, '/components/schemas/OrderInput', schema, base); + const validate = requestValidator(ks.doc, '/components/schemas/OrderInput'); + const apply = (v: (typeof r.variants)[number]) => { + const out = structuredClone(base); + for (const p of v.remove ?? []) { + const keys = p.split('/').slice(1); + let n = out; + for (const k of keys.slice(0, -1)) n = n[k]; + delete n[keys[keys.length - 1]]; + } + if (v.set) out[v.set.pointer.slice(1)] = v.set.value; + return out; + }; + + it('only the required fields: valid, and every optional field the schema allows is left out', () => { + const v = r.variants.find((x) => x.kind === 'optional-omitted')!; + const payload = apply(v); + expect(validate(payload), JSON.stringify(validate.errors)).toBe(true); + expect(Object.keys(payload).sort()).toEqual(['customer', 'items', 'total']); + }); + + it('another oneOf branch: only the branch the example does not send, and the payload is valid', () => { + const variants = r.variants.filter((x) => x.kind === 'variant'); + expect(variants.map((x) => x.location)).toEqual(['request.body#/payment/@1']); + expect(validate(apply(variants[0])), JSON.stringify(validate.errors)).toBe(true); + for (const x of r.variants) expect(parseCaseId(`ata:op_AAAAAAAAAAAA:functional:positive:${x.location}:${x.kind}`).ok, x.location).toBe(true); + }); + + it('a field minProperties needs is kept (ItemPatch: one field must stay)', () => { + const s = { $ref: '#/components/schemas/ItemPatch' }; + const p = bodyVariants(demo.doc, '/components/schemas/ItemPatch', s, { name: 'a', price: 1 }); + expect(p.variants[0].remove).toEqual(['/name']); + }); + + it('TypeScript and Python have the same variant cases; cleanup is guaranteed; the registry is valid', async () => { + const ts = await gen(ks, ksOps, ksDeps, 'typescript'); + const py = await gen(ks, ksOps, ksDeps, 'python'); + const tsText = await ts.read('orders/post/functional.spec.ts'); + const pyText = await py.read('orders/post/test_functional.py'); + const pick = (ids: string[]) => ids.filter((id) => /:(optional-omitted|variant)$/.test(id)).sort(); + expect(pick(idsIn(pyText))).toEqual(pick(idsIn(tsText))); + expect(pick(idsIn(tsText))).toHaveLength(2); + expect(cleanupProblems(tsText.replace(/\r\n/g, '\n'), 'typescript')).toEqual([]); + expect(cleanupProblems(pyText.replace(/\r\n/g, '\n'), 'python')).toEqual([]); + const reg = validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('tests/fixtures/coverage/kitchen-sink.yaml', 'utf8'), 'ks')); + expect(reg.errors).toEqual([]); + expect(ts.r.coverage.flatMap((c) => c.gaps).filter((g) => g.code === 'UNCOVERED_VARIANT')).toEqual([]); + }); +}); + +describe('reviewed auth cases (deps "auth")', () => { + it('403 for the operations named and 401 with an expired credential, from environment variables only', async () => { + const ts = await gen(demo, demoOps, demoDeps, 'typescript'); + const text = await ts.read('me/get/functional.spec.ts'); + expect(text).toContain('process.env.API_FORBIDDEN_TOKEN'); + expect(text).toContain('process.env.API_EXPIRED_TOKEN'); + expect(text).toContain("test.skip(!credential,"); + expect(text).not.toContain('demo-suspended-token'); + const rules = idsIn(text).map((id) => (parseCaseId(id) as any).parts.rule); + expect(rules).toEqual(expect.arrayContaining(['forbidden', 'expired-credentials'])); + const me = ts.r.coverage.find((c) => c.operation === 'GET /me')!; + expect(me.uncheckedStatuses).toEqual([]); + }); + + it('a section that does not match the spec is reported, never used', async () => { + expect(checkAuthConfig({ forbidden: { credentialEnv: 'lower', operations: ['nope'] } }, demoOps)).toEqual([ + 'auth.forbidden.credentialEnv must name an environment variable (e.g. API_FORBIDDEN_TOKEN)', + 'auth.forbidden: operation "nope" is not in the spec', + ]); + const deps = { ...demoDeps, auth: { forbidden: { credentialEnv: 'API_FORBIDDEN_TOKEN', operations: ['getHealth'] } } }; + const ts = await gen(demo, demoOps, deps, 'typescript'); + const health = ts.r.coverage.find((c) => c.operation === 'GET /health')!; + expect(health.gaps.map((g) => g.code)).toContain('INVALID_REVIEWED_CONFIG'); + }); + + it('without a reviewed section 403 stays a gap that names the missing configuration', async () => { + const { auth, ...withoutAuth } = ksDeps; + void auth; + const ts = await gen(ks, ksOps, withoutAuth, 'typescript'); + const orders = ts.r.coverage.find((c) => c.operation === 'GET /orders')!; + expect(orders.gaps.find((g) => g.location === 'response.status#/403')?.reason).toContain('deps "auth.forbidden"'); + }); +}); + +describe('gap codes say the actual reason', () => { + it('a write without confirmed cleanup: every status has the success call\'s reason', async () => { + const ts = await gen(demo, demoOps, demoDeps, 'typescript'); + const reset = ts.r.coverage.find((c) => c.operation === 'POST /admin/reset')!; + expect(reset.uncheckedStatuses).toEqual([{ status: '204', code: 'MISSING_CLEANUP' }, { status: '401', code: 'MISSING_CLEANUP' }]); + const report = ts.r.coverage.find((c) => c.operation === 'GET /reports/{reportId}')!; + expect(report.uncheckedStatuses).toEqual([{ status: '200', code: 'MISSING_RESOURCE_SOURCE' }]); + }); +}); + +describe('CI quality gates', () => { + it('a write test without guaranteed cleanup fails the gate (TypeScript and Python)', () => { + const ts = [ + "import x;", + " test('creates and forgets', {}, async ({ api }) => {", + ' const { id } = await resource.create(api);', + ' const res = await api.items.getItem(id);', + ' expect(res.status()).toBe(200);', + ' });', + " test('creates and cleans', {}, async ({ api }) => {", + ' const { id } = await resource.create(api);', + ' try {', + ' expect(1).toBe(1);', + ' } finally {', + ' await resource.remove(api, id);', + ' }', + ' });', + " test('asserts before cleanup', {}, async ({ api }) => {", + ' const res = await api.items.createItem({ data: payload });', + ' expect(res.status()).toBe(201);', + ' await resource.removeIfCreated(api, res);', + ' });', + ].join('\n'); + expect(cleanupProblems(ts, 'typescript').map((p) => p.test)).toEqual(["'creates and forgets', {}, async ({ api }) => {", "'asserts before cleanup', {}, async ({ api }) => {"]); + const py = [ + 'import pytest', + '@pytest.mark.positive', + 'def test_forgets(api, items):', + ' rid, _ = items.create()', + ' assert rid', + '@pytest.mark.positive', + 'def test_asserts_first(api, items):', + ' res = api.post("items", json=items.new_create_payload())', + ' assert res.status_code == 201', + ' items.remove_if_created(res)', + '@pytest.mark.positive', + 'def test_fixture(api, items, created_items):', + ' res = api.patch(f"items/{created_items}", json={})', + ].join('\n'); + expect(cleanupProblems(py, 'python').map((p) => p.test)).toEqual(['def test_forgets(api, items):', 'def test_asserts_first(api, items):']); + }); + + it('a lost active case or an unexplained new gap fails until the baseline is updated', () => { + const d = compareBaseline({ activeCaseIds: ['a', 'b'], gaps: ['G1'] }, { activeCaseIds: ['b', 'c'], gaps: ['G2'] }); + expect(d).toEqual({ lostCases: ['a'], newCases: ['c'], newGaps: ['G2'], closedGaps: ['G1'] }); + }); +}); diff --git a/tests/unit/coverage-report.test.ts b/tests/unit/coverage-report.test.ts index b1b2702..444b648 100644 --- a/tests/unit/coverage-report.test.ts +++ b/tests/unit/coverage-report.test.ts @@ -41,10 +41,8 @@ describe('stage 10: coverage report', () => { 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' }, - ]); + // 403 is exercised through the reviewed deps "auth.forbidden" of the fixture; 429 never is. + expect(list.uncheckedStatuses).toEqual([{ 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; diff --git a/tests/unit/functional-variants.test.ts b/tests/unit/functional-variants.test.ts index 9e8e5d8..d9889be 100644 --- a/tests/unit/functional-variants.test.ts +++ b/tests/unit/functional-variants.test.ts @@ -38,7 +38,7 @@ describe('stage 7: valid limits, sampler fixes, confirmed functional assertions' 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 () => { + it('generated: one accepted-value test per limit, echoes from the deps file, the other oneOf branch as its own test; 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 }); @@ -57,7 +57,9 @@ describe('stage 7: valid limits, sampler fixes, confirmed functional assertions' 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' })); + // The other oneOf branch is sent by its own test (variants.ts): no longer a gap. + expect(cov.gaps.filter((g) => g.code === 'UNCOVERED_VARIANT')).toEqual([]); + expect(Object.keys(ts.reg.cases).some((id) => id.endsWith(':functional:positive:request.body#/payment/@1:variant'))).toBe(true); 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); });