From ca2c522d318de340e5afdbb31c0fa0a6e85f91ff Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:08:47 +0100 Subject: [PATCH 1/8] feat(coverage): audit matrix; one case ID per physical test; CI checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stage 1 + 2 of the coverage plan. - docs/SUPPORT_MATRIX.md: OpenAPI keyword / check โ†’ supported, partial, missing, with the stage that changes it. - Query enum variants: each value is its own test with its own case ID (vocabulary v2, functional/positive accepted-value, request.query#//); Python renders them too (it counted them but rendered none). Values equal as strings are sent once. - Cases the generator no longer produces become tombstones in cases.json. - generate --run checks the physical tests: Playwright JSON annotations, pytest collection via API_AGENT_CASES_OUT (conftest hook); report generated.caseIdCheck {tests, missing, duplicates, unregistered}. - CI: case-ID check, registry validate --spec, manifest validate for TypeScript and Python, same active cases in both. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 20 +++ docs/SUPPORT_MATRIX.md | 134 ++++++++++++++++++ src/cases/assign.ts | 10 +- src/cases/ids.ts | 15 +- src/cases/registry.ts | 4 + src/cases/validate.ts | 9 +- src/cli.ts | 9 ++ src/generate/generate.ts | 62 +++++++- src/generate/python.ts | 22 ++- src/generate/templates.ts | 13 +- src/report/report.ts | 2 + tests/api/_support/cases.json | 13 +- tests/api/_support/generation-manifest.json | 10 +- tests/api/_support/openapi.snapshot.meta.json | 2 +- tests/api/items/delete-by-id/contract.spec.ts | 2 +- tests/unit/cases.test.ts | 6 +- tests/unit/coverage.test.ts | 111 +++++++++++++++ 17 files changed, 415 insertions(+), 29 deletions(-) create mode 100644 docs/SUPPORT_MATRIX.md create mode 100644 tests/unit/coverage.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 697d5d0..619888c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,6 +65,16 @@ jobs: if (JSON.stringify(bad) !== JSON.stringify(["stats/get/contract"]) || passed < 10) process.exit(1); ' + - name: Self-check - every physical test has its own registered case ID; registry and manifest are valid + run: | + node -e ' + const c = require("./reports/generate/report.json").generated.caseIdCheck; + console.log(JSON.stringify(c)); + if (!c || c.tests < 10 || c.missing.length || c.duplicates.length || c.unregistered.length) process.exit(1); + ' + npx tsx src/cli.ts registry validate tests/api/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null + npx tsx src/cli.ts manifest validate --tests-dir tests/api + - name: Generate Python tests (pytest + requests) and run them once run: | pip install pytest requests jsonschema @@ -75,7 +85,17 @@ jobs: const passed = r.generated.scenarios.filter(s => s.status === "PASS").length; console.log("failing:", bad, "passed:", passed); if (JSON.stringify(bad) !== JSON.stringify(["stats/get/contract"]) || passed < 10) process.exit(1); + const c = r.generated.caseIdCheck; + console.log(JSON.stringify(c)); + if (!c || c.tests < 10 || c.missing.length || c.duplicates.length || c.unregistered.length) process.exit(1); + // TypeScript and Python generate the same active cases (retired ones are history). + const active = (f) => Object.entries(require(f).cases).filter(([, c]) => c.status !== "retired").map(([id]) => id).sort(); + const ts = active("./tests/api/_support/cases.json"); + const py = active("./tests/api-python/_support/cases.json"); + if (JSON.stringify(ts) !== JSON.stringify(py)) { console.log("TS/Python case sets differ"); process.exit(1); } ' + npx tsx src/cli.ts registry validate tests/api-python/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null + npx tsx src/cli.ts manifest validate --tests-dir tests/api-python - name: Analyse the legacy example project (init + run) working-directory: examples/legacy-project diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md new file mode 100644 index 0000000..8444f06 --- /dev/null +++ b/docs/SUPPORT_MATRIX.md @@ -0,0 +1,134 @@ +# OpenAPI support matrix + +What the generator derives from an OpenAPI document today, per keyword and per suite. Updated with every change that adds or closes a gap. + +Legend: โœ… supported ยท ๐ŸŸก partial (limits listed) ยท โŒ missing ยท โ›” not generated on purpose (unsafe or needs a business requirement; reported as a gap) + +Baseline: `main` at 4c34a85 (audit of 2026-11-09). Each row names the stage of the coverage plan that changes it. + +## Request body: negative contract cases (`contract.spec.ts`, `src/generate/negative.ts`) + +| Keyword | State | Limits | Stage | +|---|---|---|---| +| `required` | ๐ŸŸก | top-level properties only | 3 | +| `type` | ๐ŸŸก | top-level only | 3 | +| `nullable` / `type: [.., null]` (null not allowed) | โŒ | | 3 | +| `enum` | ๐ŸŸก | top-level **string** only | 3 | +| `const` | โŒ | | 3 | +| `minLength` / `maxLength` | ๐ŸŸก | top-level only | 3 | +| `pattern` | โŒ | | 3 | +| `format` | โŒ | | 3 | +| `minimum` / `maximum` | ๐ŸŸก | top-level only | 3 | +| `exclusiveMinimum` / `exclusiveMaximum` | ๐ŸŸก | top-level; numeric (3.1) form only, not 3.0 boolean form | 3 | +| `multipleOf` | โŒ | | 3 | +| `minItems` / `maxItems` | ๐ŸŸก | top-level only | 3 | +| `uniqueItems` | โŒ | | 3 | +| `items` constraints | โŒ | | 3 | +| `minProperties` | ๐ŸŸก | body root only | 3 | +| `maxProperties` | โŒ | | 3 | +| `additionalProperties: false` | ๐ŸŸก | body root only | 3 | +| nested objects / arrays (`request.body#/a/b`, `/items/*/sku`) | โŒ | | 3 | +| `oneOf` / `anyOf` / `allOf` / `not` | โŒ | | 3 | +| `discriminator` | โŒ | | 3 | +| case limit | ๐ŸŸก | fixed 20 per operation, **silently truncated** | 3 | + +## Parameters (`src/generate/negative.ts`, `templates.ts`) + +| Target | State | Limits | Stage | +|---|---|---|---| +| query `required` | ๐ŸŸก | only when the spec gives a valid value | 4 | +| query `type` | ๐ŸŸก | number, integer, boolean | 4 | +| query `minimum` / `maximum` / exclusive | โœ… | | | +| query `minLength` / `maxLength` | โœ… | | | +| query `enum` (invalid value) | ๐ŸŸก | string only | 4 | +| query `const`, `pattern`, `format`, `multipleOf` | โŒ | | 4 | +| query arrays, `style` / `explode` | โŒ | | 4 | +| query boundary-valid values | โŒ | | 4 / 7 | +| path parameter constraints | โŒ | only unknown id โ†’ 404 | 4 | +| header parameters | โŒ | | 4 | +| cookie parameters | โŒ | | 4 | + +## Functional (`functional.spec.ts`) + +| Check | State | Limits | Stage | +|---|---|---|---| +| documented success status | โœ… | | | +| create returns an id | โœ… | confirmed chain | | +| read returns the created resource (same id) | โœ… | | | +| create response echoes sent fields | โŒ | | 7 | +| GET with each documented query `enum` value | โœ… | one test and one `accepted-value` case ID per value (`request.query#//`), TypeScript and Python; values equal as strings are sent once; max 5 per parameter, 15 per operation | 2 โœ” | +| list contains the created resource | โŒ | | 7 / 8 | +| filter / search / pagination / sort | โ›” | need a confirmed mapping (deps / scenario config) | 7 / 8 | +| boundary-valid values accepted | โŒ | | 7 | +| optional-field variants | โŒ | | 7 | +| response examples as requirements | โ›” | examples are illustrations unless marked | 7 | + +## Response contract (`src/contract/validator.ts`) + +| Check | State | Limits | Stage | +|---|---|---|---| +| status, `NXX` ranges, `default` | โœ… | | | +| Content-Type of the matched response | โœ… | | | +| JSON schema (3.0 nullable, 3.1 / 2020-12, formats via ajv-formats) | โœ… | | | +| local / bundled `$ref` | โœ… | snapshot is bundled | | +| non-JSON media types | ๐ŸŸก | body not checked; not reported as unchecked | 5 | +| response headers (required, schema) | โŒ | | 5 | +| no body for `204` / `205` / `HEAD` / no `content` | โŒ | an unexpected body is accepted | 5 | +| `readOnly` / `writeOnly` | โŒ | | 5 | +| `discriminator` | ๐ŸŸก | `oneOf` validated, mapping ignored | 5 | +| contract tests exercise | ๐ŸŸก | success, 404 and 401 responses only | 5 / 6 | + +## Documented error responses + +| Status | State | Limits | Stage | +|---|---|---|---| +| 400 / 422 (invalid input) | โœ… | body + query | | +| 401 (no credentials) | โœ… | | | +| 401 (invalid token / API key) | โŒ | | 6 | +| 404 (unknown id) | โœ… | single trailing path parameter | | +| 403 (scope / role) | โ›” | needs a reviewed role configuration | 6 | +| 405 | โŒ | | 6 | +| 409 (conflict) | โŒ | unique suffix only prevents it | 6 | +| 412 (precondition) | โŒ | | 6 | +| 415 (wrong Content-Type) | โŒ | | 6 | +| 429 (rate limit) | โ›” | opt-in only | 6 | + +## Scenarios (`scenarios.spec.ts`) + +| Flow | State | Stage | +|---|---|---| +| create โ†’ read | โœ… | | +| create โ†’ update โ†’ read | โœ… (marked ASSUMPTION) | | +| create โ†’ delete โ†’ read 404 | โœ… | | +| create โ†’ list / search / filter | โŒ | 8 | +| create โ†’ duplicate create โ†’ 409 | โŒ | 6 / 8 | +| repeated delete, update / delete unknown | โŒ | 8 | +| login / refresh โ†’ authorized request | โŒ | 8 | +| parent โ†’ child, state transitions, idempotency key, bounded polling | โ›” | need the reviewed scenario file | 8 | +| business scenario config with schema validation | โŒ | 8 | + +## Valid data (`src/generate/sample.ts`) + +| Keyword | State | Limits | Stage | +|---|---|---|---| +| `example`, `default`, `enum`, `const` | ๐ŸŸก | first value only | 7 | +| `examples` | ๐ŸŸก | first only | 7 | +| `oneOf` / `anyOf` | ๐ŸŸก | **first variant chosen silently** | 3 / 7 | +| `discriminator` | ๐ŸŸก | blocked (explicit) | 7 | +| `pattern` | ๐ŸŸก | blocked without an example (explicit) | 7 | +| `multipleOf` | โŒ | minimum used, may not be a multiple | 7 | +| formats | ๐ŸŸก | uuid, email, date-time, date, uri, url, hostname, ipv4 | 7 | +| `minItems`, nested objects / arrays | โœ… | | | +| `uniqueItems` | โŒ | copies one value `minItems` times | 7 | +| boundary-valid, optional-field, nullable variants | โŒ | | 7 | + +## Reporting and CI + +| Item | State | Stage | +|---|---|---| +| `coverage-gaps.json` per operation | ๐ŸŸก | counts + free-text reasons, no machine codes, no potential / dropped counts | 10 | +| unique case ID per physical test | โœ… | checked on the real run: Playwright JSON report annotations, pytest collection (`API_AGENT_CASES_OUT`) | 2 โœ” | +| CI: registry and manifest validation | โœ… | `registry validate --spec --require-spec`, `manifest validate`, TypeScript and Python | 2 โœ” | +| CI: no duplicate case IDs, every test registered | โœ… | plus: TypeScript and Python generate the same active cases | 2 โœ” | +| cases no longer generated | โœ… | become tombstones (`status: retired`), reactivated when generated again | 2 โœ” | +| CI: expected coverage gaps | โŒ | | 10 | diff --git a/src/cases/assign.ts b/src/cases/assign.ts index 1797569..5917345 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -23,7 +23,8 @@ export interface ScenarioDefinition { } export interface SuiteCaseIds { - functional: { success?: string; notFound?: string; unauthorized?: string }; + /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ + functional: { success?: string; notFound?: string; unauthorized?: string; variants: string[] }; contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; query: string[] }; scenario: { createRead?: string; updateRead?: string; deleteGone?: string }; /** Every case of this operation, by suite, with metadata for cases.json. */ @@ -42,6 +43,8 @@ export interface AssignInput { notFound?: { param: string }; unauthorized: boolean; scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean }; + /** Documented query values the suite sends one by one (functional positive), each its own physical test. */ + queryVariants?: { name: string; value: string | number | boolean }[]; } export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): SuiteCaseIds { @@ -58,7 +61,7 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): return id; }; const ok = successStatus(s.op); - const ids: SuiteCaseIds = { functional: {}, contract: { body: [], query: [] }, scenario: {}, records, scenarios }; + const ids: SuiteCaseIds = { functional: { variants: [] }, contract: { body: [], query: [] }, scenario: {}, records, scenarios }; const rel = related.length ? { relatedOperationUids: related } : {}; if (s.positive) { @@ -72,6 +75,9 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): ids.contract.success = add('contract', { subjectUid: uid, polarity: 'positive', location: location.status(ok?.status ?? '200'), rule: 'documented' }, rel); } } + for (const v of s.queryVariants ?? []) { + ids.functional.variants.push(add('functional', { subjectUid: uid, polarity: 'positive', location: location.paramValue('query', v.name, v.value), rule: 'accepted-value' })); + } if (s.notFound) { ids.functional.notFound = add('functional', { subjectUid: uid, polarity: 'negative', location: location.path(s.notFound.param), rule: 'not-found' }); ids.contract.notFound = add('contract', { subjectUid: uid, polarity: 'positive', location: location.status('404'), rule: 'documented' }); diff --git a/src/cases/ids.ts b/src/cases/ids.ts index 07ad5b8..ac716a0 100644 --- a/src/cases/ids.ts +++ b/src/cases/ids.ts @@ -10,7 +10,8 @@ import { base32 } from '../change/normalize.js'; export type SuiteType = 'functional' | 'contract' | 'scenario'; export type Polarity = 'positive' | 'negative'; -export const CASE_RULE_VOCABULARY_VERSION = 1; +/** v2 adds functional/positive `accepted-value` (one case per documented parameter value). Registries of v1 stay readable. */ +export const CASE_RULE_VOCABULARY_VERSION = 2; const CONSTRAINT_RULES = [ 'required', 'nullable', 'type', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', @@ -19,7 +20,7 @@ const CONSTRAINT_RULES = [ /** Built-in vocabulary v1, by suiteType/polarity. */ export const VOCABULARY_V1: Record = { - 'functional/positive': ['documented-success'], + 'functional/positive': ['documented-success', 'accepted-value'], 'functional/negative': ['not-found', 'unauthorized', 'forbidden'], 'contract/positive': ['documented', 'schema'], 'contract/negative': [...CONSTRAINT_RULES, 'content-type'], @@ -56,6 +57,9 @@ export const location = { requestContentType: () => 'request.content-type', query: (name: string) => `request.query#/${encodeSegment(name)}`, path: (name: string) => `request.path#/${encodeSegment(name)}`, + /** One documented value of a parameter: `request.query#//` (string, number or boolean as in the spec). */ + paramValue: (where: 'query' | 'path' | 'header' | 'cookie', name: string, value: string | number | boolean) => + `request.${where}#/${encodeSegment(where === 'header' ? name.toLowerCase() : name)}/${encodeSegment(String(value))}`, header: (name: string) => `request.header#/${encodeSegment(name.toLowerCase())}`, cookie: (name: string) => `request.cookie#/${encodeSegment(name)}`, /** `pointer` is already a case pointer ('' = body root). */ @@ -81,7 +85,7 @@ export interface CaseIdError { } const UID = /^(op|scn)_[A-Z2-7]{12,52}$/; -const LOCATION = /^(operation|lifecycle|request\.security|request\.content-type|request\.(query|path|header|cookie)#\/[^/]*|request\.body#(\/[^/]*)*|response\.body#(\/[^/]*)*|response\.status#\/[^/]+|response\.content-type#\/[^/]+)$/; +const LOCATION = /^(operation|lifecycle|request\.security|request\.content-type|request\.(query|path|header|cookie)#\/[^/]*(\/[^/]*)?|request\.body#(\/[^/]*)*|response\.body#(\/[^/]*)*|response\.status#\/[^/]+|response\.content-type#\/[^/]+)$/; /** Splits on the five structural colons and checks encoding, vocabulary and the allowed combination (no spec needed). */ export function parseCaseId(id: string): { ok: true; parts: CaseParts } | { ok: false; error: CaseIdError } { @@ -112,16 +116,17 @@ export function checkCombination(p: CaseParts): CaseIdError | undefined { const subject = (why: string): CaseIdError => ({ code: 'INVALID_CASE_SUBJECT', reason: why }); switch (`${p.suiteType}/${p.polarity}`) { case 'functional/positive': + if (p.rule === 'accepted-value') return /^request\.(query|path|header|cookie)#\/[^/]*\/[^/]*$/.test(loc) ? undefined : bad('accepted-value names a parameter and its value: request.#//'); return loc === 'operation' ? undefined : bad(`documented-success is checked on "operation", not "${loc}"`); case 'functional/negative': - if (p.rule === 'not-found') return loc.startsWith('request.path#/') ? undefined : bad('not-found is checked on a path parameter'); + if (p.rule === 'not-found') return /^request\.path#\/[^/]*$/.test(loc) ? undefined : bad('not-found is checked on a path parameter'); return loc === 'request.security' ? undefined : bad(`${p.rule} is checked on "request.security"`); case 'contract/positive': if (p.rule === 'schema') return loc.startsWith('response.body#') ? undefined : bad('schema is checked on a response body location'); return loc.startsWith('response.status#/') || loc.startsWith('response.content-type#/') ? undefined : bad('documented is checked on a response status or content type'); case 'contract/negative': if (p.rule === 'content-type') return loc === 'request.content-type' ? undefined : bad('content-type is checked on "request.content-type"'); - return /^request\.(body|query|path|header|cookie)#/.test(loc) ? undefined : bad('a constraint rule is checked on a request field or parameter'); + return /^request\.body#/.test(loc) || /^request\.(query|path|header|cookie)#\/[^/]*$/.test(loc) ? undefined : bad('a constraint rule is checked on a request field or one parameter'); default: // scenario if (loc === 'lifecycle') return p.subjectUid.startsWith('scn_') ? undefined : subject('a lifecycle scenario needs a scn_ subject'); if (loc === 'operation' && p.polarity === 'negative' && p.rule === 'business-rule') return p.subjectUid.startsWith('op_') ? undefined : subject('a single-operation scenario needs an op_ subject'); diff --git a/src/cases/registry.ts b/src/cases/registry.ts index 9d9bb4a..54111db 100644 --- a/src/cases/registry.ts +++ b/src/cases/registry.ts @@ -159,6 +159,10 @@ export function buildRegistry(i: BuildInput): Registry { if (active.has(uid) || e.status === 'retired') continue; reg.operations[uid] = { ...e, status: 'retired', retiredRevision: i.spec.revision, retiredSpecHash: i.spec.hash, lastValidatedGeneratorVersion: i.generatorVersion }; } + // Cases this run generates are active (a retired one the generator produces again is reactivated: it is the + // same rule on the same subject); every other case stays as a tombstone, never deleted, never reused. + const current = new Set(i.cases.map((c) => c.caseId)); + for (const [id, c] of Object.entries(reg.cases)) if (!current.has(id) && c.status !== 'retired') reg.cases[id] = { ...c, status: 'retired' }; for (const c of i.cases) { const { caseId: id, ...rest } = c; reg.cases[id] = { ...rest }; diff --git a/src/cases/validate.ts b/src/cases/validate.ts index b098b2b..46fbb68 100644 --- a/src/cases/validate.ts +++ b/src/cases/validate.ts @@ -190,9 +190,16 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine const bad = (reason: string): Finding => ({ code: 'INVALID_CASE_LOCATION', pointer: '', reason: `${o.key}: ${reason}` }); const m = loc.match(/^request\.(query|path|header|cookie)#\/(.*)$/); if (m) { - const name = String(decodeSegment(m[2])); + const [rawName, rawValue] = m[2].split('/'); + const name = String(decodeSegment(rawName)); const p = o.params.find((x) => x.in === m[1] && (m[1] === 'header' ? x.name.toLowerCase() === name : x.name === name)); if (!p) return bad(`no ${m[1]} parameter "${name}"`); + if (rawValue !== undefined) { + // accepted-value: the value must be one the spec documents for this parameter. + const value = String(decodeSegment(rawValue)); + const allowed = Array.isArray(p.schema?.enum) ? p.schema.enum.map(String) : p.schema?.const !== undefined ? [String(p.schema.const)] : []; + return allowed.includes(value) ? undefined : bad(`"${value}" is not a documented value of ${m[1]} "${name}"`); + } if (rule !== 'required' && rule !== 'not-found' && !ruleFits(p.schema, rule)) return { code: 'INVALID_CASE_RULE_FOR_SCHEMA', pointer: '', reason: `${o.key}: "${rule}" does not apply to ${m[1]} "${name}"` }; return undefined; } diff --git a/src/cli.ts b/src/cli.ts index 3ec84c2..a490491 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -242,6 +242,14 @@ common(program.command('generate').description('audit, then generate Playwright log('Running generated tests once (assertions are never changed to pass)โ€ฆ'); await runGenerated(gen, { baseUrl: o.baseUrl! }, o.out, o.lang); for (const s of gen.scenarios.filter((x) => x.file)) log(` ${s.status.padEnd(9)} ${s.name}`); + const ids = gen.caseIdCheck; + if (ids) { + const bad = ids.missing.length + ids.duplicates.length + ids.unregistered.length; + log(`Case IDs: ${ids.tests} test(s)${bad ? ` ยท WARNING: ${ids.missing.length} without an ID, ${ids.duplicates.length} duplicated, ${ids.unregistered.length} not in cases.json` : ', each with its own registered ID'}`); + for (const t of ids.missing.slice(0, 10)) log(` NO ID ${t}`); + for (const d of ids.duplicates.slice(0, 10)) log(` DUPLICATE ${d}`); + for (const u of ids.unregistered.slice(0, 10)) log(` UNREGISTERED ${u}`); + } if (gen.cleanupFailures.length) { log(`WARNING: cleanup could not remove ${gen.cleanupFailures.length} record(s); they stay on ${o.baseUrl}:`); for (const line of cleanupSummary(gen.cleanupFailures)) log(` LEFT ${line}`); @@ -259,6 +267,7 @@ common(program.command('generate').description('audit, then generate Playwright files: gen.files.map((f) => resolve(f).replace(process.cwd() + (process.platform === 'win32' ? '\\' : '/'), '').replace(/\\/g, '/')), scenarios: gen.scenarios.map(({ name, status, reason, operations }) => ({ name, status, reason, operations })), cleanupFailures: gen.cleanupFailures, + ...(gen.caseIdCheck ? { caseIdCheck: gen.caseIdCheck } : {}), }, }); const files = await writeReport(report, o.out); diff --git a/src/generate/generate.ts b/src/generate/generate.ts index d4401f4..79739bc 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -13,7 +13,7 @@ import { buildRegistry, canonicalJson, fileHash, readRegistry, resolveOperationU import { headRevision } from '../change/baseline.js'; import { isUrl } from '../change/network.js'; import { bodyCases, documentedRejections, nonexistentIdExpr, queryCases } from './negative.js'; -import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; +import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; import { API_BASE, buildApiIndex, renderApiBaseClass, renderApiChildClass, renderApis } from './api-objects.js'; import { PY_FILES, pyName, renderConftest, renderPyContract, renderPyFunctional, renderPyResource, renderPyScenarios, resourceModule } from './python.js'; @@ -52,6 +52,8 @@ export interface GenerateResult { coverage: Coverage[]; /** Test data the generated cleanup could not remove during --run (it stays on the target). */ cleanupFailures: CleanupFailure[]; + /** After --run: every physical test has its own registered case ID. */ + caseIdCheck?: CaseIdCheck; } export interface CleanupFailure { @@ -291,7 +293,8 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp // --- suites const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, queryCases: qCases, notFound, unauthorized }; const counts = suiteCounts(input); - const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, queryCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input) }, uidOf); + const variants = input.positive && !plan && op.method === 'get' ? queryVariants(op) : []; + const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, queryCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null }); @@ -476,8 +479,15 @@ export async function runGenerated(result: GenerateResult, env: { baseUrl: strin const cleanupLog = resolve(outDir, 'cleanup-failures.jsonl'); await mkdir(dirname(cleanupLog), { recursive: true }); await rm(cleanupLog, { force: true }); - const runEnv = { ...process.env, API_BASE_URL: env.baseUrl, API_AGENT_CLEANUP_LOG: cleanupLog }; + const casesOut = resolve(outDir, 'collected-cases.jsonl'); + await rm(casesOut, { force: true }); + const runEnv = { ...process.env, API_BASE_URL: env.baseUrl, API_AGENT_CLEANUP_LOG: cleanupLog, API_AGENT_CASES_OUT: casesOut }; await (lang === 'python' ? runPytest(specs, runEnv, outDir) : runPlaywright(specs, runEnv, outDir)); + // Every physical test that ran (or was collected) must carry its own case ID from the registry. + const collected = lang === 'python' ? await readCollected(casesOut) : await playwrightCaseIds(resolve(outDir, 'playwright-results.json')); + const registryFile = result.files.find((f) => /[\\/]_support[\\/]cases\.json$/.test(f)); + const registered = registryFile && existsSync(registryFile) ? new Set(Object.keys(JSON.parse(await readFile(registryFile, 'utf8')).cases ?? {})) : new Set(); + result.caseIdCheck = checkCaseIds(collected, registered); result.cleanupFailures = existsSync(cleanupLog) ? (await readFile(cleanupLog, 'utf8')).split('\n').filter((l) => l.trim()).flatMap((l) => { try { @@ -489,6 +499,52 @@ export async function runGenerated(result: GenerateResult, env: { baseUrl: strin : []; } +export interface CaseIdCheck { + tests: number; + /** Tests without a case ID. */ + missing: string[]; + /** Case IDs carried by more than one physical test. */ + duplicates: string[]; + /** Case IDs that are not in _support/cases.json. */ + unregistered: string[]; +} + +export function checkCaseIds(tests: { test: string; caseId: string | null }[], registered: Set): CaseIdCheck { + const count = new Map(); + for (const t of tests) if (t.caseId) count.set(t.caseId, (count.get(t.caseId) ?? 0) + 1); + return { + tests: tests.length, + missing: tests.filter((t) => !t.caseId).map((t) => t.test), + duplicates: [...count].filter(([, n]) => n > 1).map(([id]) => id), + unregistered: [...count.keys()].filter((id) => !registered.has(id)), + }; +} + +async function readCollected(file: string): Promise<{ test: string; caseId: string | null }[]> { + if (!existsSync(file)) return []; + return (await readFile(file, 'utf8')).split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l)); +} + +/** Case IDs from the Playwright JSON report: the `caseId` annotation of every test. */ +async function playwrightCaseIds(file: string): Promise<{ test: string; caseId: string | null }[]> { + if (!existsSync(file)) return []; + const report = JSON.parse(await readFile(file, 'utf8')); + const out: { test: string; caseId: string | null }[] = []; + const walk = (suite: any, file?: string) => { + const f = suite.file ?? file; + for (const spec of suite.specs ?? []) { + for (const t of spec.tests ?? []) { + const annotations = [...(t.annotations ?? []), ...(t.results ?? []).flatMap((r: any) => r.annotations ?? [])]; + const id = annotations.find((a: any) => a.type === 'caseId')?.description ?? null; + out.push({ test: `${f} โ€บ ${spec.title}`, caseId: id }); + } + } + for (const s of suite.suites ?? []) walk(s, f); + }; + for (const s of report.suites ?? []) walk(s); + return out; +} + /** Groups cleanup failures by operation and status: "DELETE /brands/{brandId} โ†’ 403: 13 record(s)". */ export function cleanupSummary(failures: CleanupFailure[]): string[] { const groups = new Map(); diff --git a/src/generate/python.ts b/src/generate/python.ts index 1f27baf..fd57fcf 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -1,5 +1,5 @@ import type { Operation } from '../types.js'; -import { hasFill, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; +import { hasFill, queryVariants, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; /** * pytest + requests output. Same cases and safety rules as the TypeScript templates; @@ -234,6 +234,17 @@ def pytest_configure(config): config.addinivalue_line("markers", "api_case_id(id): stable case ID from _support/cases.json") +def pytest_collection_modifyitems(config, items): + # api-test-agent sets API_AGENT_CASES_OUT to check that every collected test has its own case ID. + out = os.environ.get("API_AGENT_CASES_OUT") + if not out: + return + with open(out, "w", encoding="utf-8") as f: + for item in items: + mark = item.get_closest_marker("api_case_id") + f.write(json.dumps({"test": item.nodeid, "caseId": mark.args[0] if mark else None}) + "\\n") + + class ApiClient(requests.Session): """requests.Session with a base URL, JSON accept header and a default timeout.""" @@ -401,6 +412,15 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { }, s.ids?.functional.success), ); } + // One physical test (and case ID) per documented query value, as in the TypeScript suite. + const variants = s.positive && !plan && op.method === 'get' ? queryVariants(op) : []; + if (variants.length) { + const base = Object.fromEntries(op.params.filter((p) => p.in === 'query' && p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); + L.push('QUERY_VALUES = ['); + variants.forEach((v, n) => L.push(` pytest.param(${pyLit({ ...base, [v.name]: v.value }, 4)}, id=${str(`${v.name}=${String(v.value)}`)}${paramMarks(s.ids?.functional.variants[n])}),`)); + L.push(']', '', '', POS, '@pytest.mark.parametrize("params", QUERY_VALUES)', 'def test_accepts_documented_query_value(api, params):'); + L.push(` res = api.${op.method}(${pathExpr(op)}, params=params)`, ` ${assertSuccess(op)}`, '', ''); + } if (s.notFound) L.push(...pyNotFound(s, 'test_returns_documented_404_for_unknown_id', withId(NEG, s.ids?.functional.notFound), statusIs(op, '404'))); if (s.unauthorized) L.push(...pyAnonymous(s, 'test_returns_documented_401_without_credentials', withId(NEG, s.ids?.functional.unauthorized), statusIs(op, '401'))); return finish(L); diff --git a/src/generate/templates.ts b/src/generate/templates.ts index bd7aaa6..3ac912a 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -63,9 +63,10 @@ export function queryVariants(op: Operation): Array<{ name: string; value: strin return op.params.filter((p) => p.in === 'query' && !p.required).flatMap((p) => { const schema = p.schema ?? {}; const values = Array.isArray(schema.enum) ? schema.enum : []; - return values.filter((v): v is string | number | boolean => - typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' - ).slice(0, 5).map((value) => ({ name: p.name, value })); + const kept = values.filter((v): v is string | number | boolean => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'); + // One physical test per value, each with its own case ID: values equal as strings would share an ID. + const unique = kept.filter((v, i) => kept.findIndex((x) => String(x) === String(v)) === i); + return unique.slice(0, 5).map((value) => ({ name: p.name, value })); }).slice(0, 15); } @@ -354,16 +355,16 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { if (s.positive && !plan && op.method === 'get') { const ref = s.refs.get(op)!; const base = requiredQuery(op); - for (const variant of queryVariants(op)) { + queryVariants(op).forEach((variant, n) => { const params = { ...base, [variant.name]: variant.value }; L.push( - ` test(${q(`accepts documented ${variant.name}=${String(variant.value)}`)}, ${testOptions('positive', s.ids?.functional.success)}, async ({ ${fx} }) => {`, + ` test(${q(`accepts documented ${variant.name}=${String(variant.value)}`)}, ${testOptions('positive', s.ids?.functional.variants[n])}, async ({ ${fx} }) => {`, ` const res = await ${apiCall(ref, fx, pathArgs(op, ref), `{ params: ${JSON.stringify(params)} }`)};`, ` ${expectSuccess(op)}`, ` });`, '', ); - } + }); } if (s.notFound) { L.push(` test('returns documented 404 for an id that does not exist', ${testOptions('negative', s.ids?.functional.notFound)}, async ({ ${fx} }) => {`, ...notFoundCall(s, fx), ` expectStatus(res, ['404'], '${op.method}', ${q(op.path)});`, ` });`, ''); diff --git a/src/report/report.ts b/src/report/report.ts index 7d74c59..c0a1a96 100644 --- a/src/report/report.ts +++ b/src/report/report.ts @@ -34,6 +34,8 @@ export interface AuditReport { scenarios: { name: string; status: Status; reason: string; operations: string[] }[]; /** Test data cleanup could not remove during the run: it stays on the target. */ cleanupFailures?: { operation: string; id: string; status: number | string }[]; + /** After a run: every physical test has its own case ID registered in cases.json. */ + caseIdCheck?: { tests: number; missing: string[]; duplicates: string[]; unregistered: string[] }; }; } diff --git a/tests/api/_support/cases.json b/tests/api/_support/cases.json index 3f0fcb1..5be4142 100644 --- a/tests/api/_support/cases.json +++ b/tests/api/_support/cases.json @@ -1,5 +1,5 @@ { - "caseRuleVocabularyVersion": 1, + "caseRuleVocabularyVersion": 2, "cases": { "ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:maximum": { "location": "request.query#/limit", @@ -90,6 +90,17 @@ "op_UPN7JLUXYUZ7" ], "rule": "schema", + "status": "retired", + "subjectUid": "op_EDRRXKOK26ZL", + "suiteType": "contract" + }, + "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/204:documented": { + "location": "response.status#/204", + "polarity": "positive", + "relatedOperationUids": [ + "op_UPN7JLUXYUZ7" + ], + "rule": "documented", "subjectUid": "op_EDRRXKOK26ZL", "suiteType": "contract" }, diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index 5100f7e..0521caf 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -1,5 +1,5 @@ { - "caseRegistryHash": "37bb92bb8ccf1d6d2643ea93e47adf3d78bf2df717b5c0f8bf6923f42ab643c1", + "caseRegistryHash": "351fb71f8b54ff5394019b8e29ae73c62398b2f91669315594bbbccb061cb8ec", "files": { "_support/api/generated/AdminApiBase.ts": { "ownership": "generated", @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "d76615ab812db149bbc2fa0f3c6c54fcd33dd32425f30a112183076446a41a2c" + "sha256": "96f6872343f76e0718b009caafc62f280eded6df36ad52cbff911ff9b42edbcf" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -85,7 +85,7 @@ }, "items/delete-by-id/contract.spec.ts": { "caseIds": [ - "ata:op_EDRRXKOK26ZL:contract:positive:response.body#:schema", + "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/204:documented", "ata:op_EDRRXKOK26ZL:contract:positive:response.status#/404:documented" ], "operationUids": [ @@ -93,7 +93,7 @@ "op_UPN7JLUXYUZ7" ], "ownership": "generated", - "sha256": "8fe5d6a0c20e08c655890970e0e5fbe2ba95433a08c265830d32dc644898382b", + "sha256": "36d18c0e4bb64b7b82cf35fed29edea67c5c62ccd54354f608485b3187f23457", "suiteType": "contract" }, "items/delete-by-id/functional.spec.ts": { @@ -346,7 +346,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "8ee4d7f0ebae3dc6c359ad03e9879676cc689ac7", + "revision": "4c34a850465f66f749be62929c9df568b247a6d7", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index 66b37b0..7ab1bc5 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "8ee4d7f0ebae3dc6c359ad03e9879676cc689ac7", + "capturedRevision": "4c34a850465f66f749be62929c9df568b247a6d7", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/api/items/delete-by-id/contract.spec.ts b/tests/api/items/delete-by-id/contract.spec.ts index b6334c1..3bbd892 100644 --- a/tests/api/items/delete-by-id/contract.spec.ts +++ b/tests/api/items/delete-by-id/contract.spec.ts @@ -11,7 +11,7 @@ import { expectContract } from '../../_support/contract-assert.js'; import * as resource from '../../_support/items.resource.js'; test.describe('DELETE /items/{itemId} ยท contract', { tag: '@contract' }, () => { - test('success response matches the documented contract', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_EDRRXKOK26ZL:contract:positive:response.body#:schema' } }, async ({ api }) => { + test('success response matches the documented contract', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_EDRRXKOK26ZL:contract:positive:response.status#/204:documented' } }, async ({ api }) => { const { id } = await resource.create(api); try { const res = await api.items.deleteItem(id); diff --git a/tests/unit/cases.test.ts b/tests/unit/cases.test.ts index 16b0546..6062de0 100644 --- a/tests/unit/cases.test.ts +++ b/tests/unit/cases.test.ts @@ -8,7 +8,7 @@ import { stringify, parse } from 'yaml'; import { loadSpec } from '../../src/spec/loader.js'; import { buildCatalog } from '../../src/spec/catalog.js'; import { generate, findPython } from '../../src/generate/generate.js'; -import { ARRAY, bodyPointer, encodeSegment, parseCaseId, scenarioUid } from '../../src/cases/ids.js'; +import { ARRAY, CASE_RULE_VOCABULARY_VERSION, bodyPointer, encodeSegment, parseCaseId, scenarioUid } from '../../src/cases/ids.js'; import { canonicalJson } from '../../src/cases/registry.js'; import { validateManifest, validateRegistry } from '../../src/cases/validate.js'; import { normalizeSpec, operationUid } from '../../src/change/normalize.js'; @@ -69,7 +69,7 @@ describe('generated suites carry case IDs', () => { expect((text.match(/ test\(/g) ?? []).length, f).toBe((text.match(/annotation: \{ type: 'caseId'/g) ?? []).length); } const reg = await registry(); - expect(reg.caseRuleVocabularyVersion).toBe(1); + expect(reg.caseRuleVocabularyVersion).toBe(CASE_RULE_VOCABULARY_VERSION); expect(reg.operations[uid]).toEqual({ method: 'GET', path: '/items/{itemId}', normalizedPath: '/items/{}', operationId: 'getItem' }); const covers = reg.cases[`ata:${operationUid('POST', '/items')}:contract:positive:response.body#:schema`].covers; expect(covers).toEqual(['contract:positive:response.content-type#/application~1json:documented', 'contract:positive:response.status#/201:documented']); @@ -156,7 +156,7 @@ describe('registry validate', () => { reg.operations.op_AAAAAAAAAAAA = { method: 'GET', path: '/gone', normalizedPath: '/gone', status: 'retired' }; const codes = run(reg).errors.map((e) => e.code); for (const c of ['CASE_ENTRY_MISMATCH', 'CASE_SUBJECT_NOT_FOUND', 'INVALID_SCENARIO', 'DUPLICATE_API_TEST_AGENT_ID', 'ALIAS_CYCLE', 'INVALID_TOMBSTONE']) expect(codes, c).toContain(c); - expect(run({ ...(await base()), caseRuleVocabularyVersion: 2 }).blocked.map((x) => x.code)).toEqual(['UNSUPPORTED_CASE_RULE_VOCABULARY']); + expect(run({ ...(await base()), caseRuleVocabularyVersion: CASE_RULE_VOCABULARY_VERSION + 1 }).blocked.map((x) => x.code)).toEqual(['UNSUPPORTED_CASE_RULE_VOCABULARY']); }); it('with a spec: missing operations, unknown fields and parameters, wildcards on non-arrays, rules that do not fit', async () => { diff --git a/tests/unit/coverage.test.ts b/tests/unit/coverage.test.ts new file mode 100644 index 0000000..1335d5f --- /dev/null +++ b/tests/unit/coverage.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { parse, stringify } from 'yaml'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { checkCaseIds, findPython, generate } from '../../src/generate/generate.js'; +import { parseCaseId } from '../../src/cases/ids.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { canonicalJson } from '../../src/cases/registry.js'; +import { normalizeSpec, operationUid } from '../../src/change/normalize.js'; + +/** + * Coverage completeness (docs/SUPPORT_MATRIX.md): one physical test โ†’ one stable case ID, + * the same cases in TypeScript and Python. + */ + +const demo = await loadSpec('demo-api/openapi.yaml'); + +async function gen(doc: any, lang: 'typescript' | 'python' = 'typescript') { + const dir = await mkdtemp(join(tmpdir(), 'ata-cov-')); + const r = await generate({ ...demo, doc } as any, buildCatalog(doc), { outDir: dir, version: 'test', lang }); + const read = (f: string) => readFile(join(dir, f), 'utf8'); + return { dir, r, read, registry: async () => JSON.parse(await read('_support/cases.json')) }; +} + +/** Case IDs written into a generated file: annotations / caseId fields (TS) or api_case_id markers (Python). */ +const idsIn = (text: string) => [...text.matchAll(/(?:description: |caseId: )'([^']+)'|api_case_id\("([^"]+)"\)/g)].map((m) => m[1] ?? m[2]).filter((x) => x !== 'c.caseId'); + +describe('stage 2: one case ID per physical test', () => { + const withSort = () => { + const d = parse(stringify(demo.doc)); + d.paths['/items'].get.parameters.push({ name: 'sort', in: 'query', required: false, schema: { type: 'string', enum: ['asc', 'desc', 'asc'] } }); + d.paths['/items'].get.parameters.push({ name: 'flag', in: 'query', required: false, schema: { enum: [true, 'true', 1] } }); + return d; + }; + + it('each documented query value is its own test with its own accepted-value case ID (duplicates as strings dropped)', async () => { + const { read, registry } = await gen(withSort()); + const text = await read('items/get/functional.spec.ts'); + const uid = operationUid('GET', '/items'); + for (const v of ['asc', 'desc', 'true', '1']) { + const loc = v === 'asc' || v === 'desc' ? `request.query#/sort/${v}` : `request.query#/flag/${v}`; + expect(text).toContain(`'ata:${uid}:functional:positive:${loc}:accepted-value'`); + } + expect(text.match(/accepts documented flag=/g)).toHaveLength(2); // true and "true" are one value + const ids = idsIn(text); + expect(new Set(ids).size).toBe(ids.length); + const reg = await registry(); + for (const id of ids) expect(reg.cases[id], id).toBeDefined(); + expect(validateRegistry(await read('_support/cases.json'), normalizeSpec(stringify(withSort()), 'x')).errors).toEqual([]); + }); + + it('Python renders the same values, each pytest.param with its own case ID', async () => { + const ts = await gen(withSort()); + const py = await gen(withSort(), 'python'); + const tsIds = idsIn(await ts.read('items/get/functional.spec.ts')).sort(); + const pyIds = idsIn(await py.read('items/get/test_functional.py')).sort(); + expect(pyIds).toEqual(tsIds); + expect(await py.read('items/get/test_functional.py')).toContain('def test_accepts_documented_query_value(api, params):'); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', join(py.dir, 'items/get/test_functional.py')], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); + + it('TypeScript and Python register the same cases for the demo API', async () => { + const ts = await gen(demo.doc); + const py = await gen(demo.doc, 'python'); + expect(Object.keys((await py.registry()).cases).sort()).toEqual(Object.keys((await ts.registry()).cases).sort()); + }); + + it('accepted-value: a value the spec does not document is an invalid location', () => { + const d = withSort(); + const uid = operationUid('GET', '/items'); + const id = `ata:${uid}:functional:positive:request.query#/sort/random:accepted-value`; + const parsed = parseCaseId(id); + expect(parsed.ok).toBe(true); + const reg = { schemaVersion: 1, caseRuleVocabularyVersion: 2, operations: { [uid]: { method: 'GET', path: '/items', normalizedPath: '/items' } }, cases: { [id]: (parsed as any).parts }, scenarios: {}, externalIdAliases: {}, externalScenarioIdAliases: {} }; + expect(validateRegistry(canonicalJson(reg), normalizeSpec(stringify(d), 'x')).errors.map((e) => e.code)).toEqual(['INVALID_CASE_LOCATION']); + expect(parseCaseId(`ata:${uid}:functional:positive:request.query#/sort:accepted-value`).ok).toBe(false); // needs a value + expect(parseCaseId(`ata:${uid}:contract:negative:request.query#/sort/asc:enum`).ok).toBe(false); // constraint rules: one segment + }); + + it('a case the generator no longer produces becomes a tombstone; producing it again reactivates it', async () => { + const { dir } = await gen(withSort()); + const uid = operationUid('GET', '/items'); + const id = `ata:${uid}:functional:positive:request.query#/sort/desc:accepted-value`; + const without = withSort(); + without.paths['/items'].get.parameters.find((p: any) => p.name === 'sort').schema.enum = ['asc']; + await generate({ ...demo, doc: without } as any, buildCatalog(without), { outDir: dir, version: 'test' }); + const reg1 = JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')); + expect(reg1.cases[id].status).toBe('retired'); + await generate({ ...demo, doc: withSort() } as any, buildCatalog(withSort()), { outDir: dir, version: 'test' }); + const reg2 = JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')); + expect(reg2.cases[id].status).toBeUndefined(); + }); + + it('checkCaseIds reports tests without an ID, shared IDs and unregistered IDs', () => { + const r = checkCaseIds( + [ + { test: 'a', caseId: 'x' }, + { test: 'b', caseId: 'x' }, + { test: 'c', caseId: null }, + { test: 'd', caseId: 'y' }, + ], + new Set(['x']), + ); + expect(r).toEqual({ tests: 4, missing: ['c'], duplicates: ['x'], unregistered: ['y'] }); + }); +}); From 93b4d144ee116dffa83c091e603b4c385ab916cb Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:16:37 +0100 Subject: [PATCH 2/8] feat(coverage): recursive request-body negative cases (stage 3) - src/generate/body-cases.ts: from a valid payload, one broken rule per case at any depth (request.body#/customer/address/city, request.body#/items/*/price): required, type, nullable, enum (string, number, integer, boolean), const, min/maxLength, pattern, format, minimum/maximum, exclusive min/max (3.1 numeric and 3.0 boolean), multipleOf, min/maxItems, uniqueItems, items, min/maxProperties, additionalProperties: false; allOf merged. - Rules that cannot be broken alone, oneOf / anyOf / not / discriminator, and missing samples become coverage gaps with a code and the exact location (CANNOT_ISOLATE_RULE, UNSUPPORTED_SCHEMA_KEYWORD, MISSING_VALID_SAMPLE). Fixes minProperties sending {} (it also broke required). - Limit: --max-cases (default 60); potential / generated / dropped per operation in coverage-gaps.json, dropped ones as CASE_LIMIT_REACHED. - tests/fixtures/coverage/kitchen-sink.yaml: synthetic spec with a wide keyword set. Every generated case is checked with ajv: exactly one error, the expected keyword, the expected instance path (68 cases). Demo API: 58 tests in TypeScript and in Python, only stats/get/contract fails; every test has its own registered case ID. Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 48 +-- src/cases/assign.ts | 4 +- src/cli.ts | 7 +- src/generate/body-cases.ts | 289 ++++++++++++++++++ src/generate/generate.ts | 18 +- src/generate/negative.ts | 78 +---- tests/api/_support/cases.json | 65 ++++ tests/api/_support/generation-manifest.json | 29 +- tests/api/_support/openapi.snapshot.meta.json | 2 +- tests/api/items/patch-by-id/contract.spec.ts | 8 +- tests/api/items/post/contract.spec.ts | 15 +- tests/fixtures/coverage/kitchen-sink.yaml | 124 ++++++++ tests/unit/body-cases.test.ts | 107 +++++++ 13 files changed, 678 insertions(+), 116 deletions(-) create mode 100644 src/generate/body-cases.ts create mode 100644 tests/fixtures/coverage/kitchen-sink.yaml create mode 100644 tests/unit/body-cases.test.ts diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 8444f06..9b774bf 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -6,31 +6,33 @@ Legend: โœ… supported ยท ๐ŸŸก partial (limits listed) ยท โŒ missing ยท โ›” not Baseline: `main` at 4c34a85 (audit of 2026-11-09). Each row names the stage of the coverage plan that changes it. -## Request body: negative contract cases (`contract.spec.ts`, `src/generate/negative.ts`) +## Request body: negative contract cases (`contract.spec.ts`, `src/generate/body-cases.ts`) -| Keyword | State | Limits | Stage | +Recursive from a valid payload; every case breaks exactly one rule (verified with ajv in `tests/unit/body-cases.test.ts`: one error, the expected keyword, the expected instance path). Locations are JSON pointers at any depth, `*` for array elements (the first element stands for all). A rule that cannot be broken alone is a gap with a code, never a guess. + +| Keyword | State | Limits / gap | Stage | |---|---|---|---| -| `required` | ๐ŸŸก | top-level properties only | 3 | -| `type` | ๐ŸŸก | top-level only | 3 | -| `nullable` / `type: [.., null]` (null not allowed) | โŒ | | 3 | -| `enum` | ๐ŸŸก | top-level **string** only | 3 | -| `const` | โŒ | | 3 | -| `minLength` / `maxLength` | ๐ŸŸก | top-level only | 3 | -| `pattern` | โŒ | | 3 | -| `format` | โŒ | | 3 | -| `minimum` / `maximum` | ๐ŸŸก | top-level only | 3 | -| `exclusiveMinimum` / `exclusiveMaximum` | ๐ŸŸก | top-level; numeric (3.1) form only, not 3.0 boolean form | 3 | -| `multipleOf` | โŒ | | 3 | -| `minItems` / `maxItems` | ๐ŸŸก | top-level only | 3 | -| `uniqueItems` | โŒ | | 3 | -| `items` constraints | โŒ | | 3 | -| `minProperties` | ๐ŸŸก | body root only | 3 | -| `maxProperties` | โŒ | | 3 | -| `additionalProperties: false` | ๐ŸŸก | body root only | 3 | -| nested objects / arrays (`request.body#/a/b`, `/items/*/sku`) | โŒ | | 3 | -| `oneOf` / `anyOf` / `allOf` / `not` | โŒ | | 3 | -| `discriminator` | โŒ | | 3 | -| case limit | ๐ŸŸก | fixed 20 per operation, **silently truncated** | 3 | +| `required` | โœ… | any depth; a required field without a valid sample โ†’ `MISSING_VALID_SAMPLE` | 3 โœ” | +| `type` | โœ… | any depth; skipped for `enum` / `const` fields (`CANNOT_ISOLATE_RULE`: the enum case covers it) | 3 โœ” | +| `nullable` / `type: [.., null]` | โœ… | `null` where null is not allowed (rule `nullable`) | 3 โœ” | +| `enum` | โœ… | string, number, integer, boolean; an enum covering all values โ†’ gap | 3 โœ” | +| `const` | โœ… | scalars | 3 โœ” | +| `minLength` / `maxLength` | โœ… | gap when `pattern` / `format` / `enum` / `const` would break too | 3 โœ” | +| `pattern` | โœ… | a simple non-matching string within the length limits; otherwise gap | 3 โœ” | +| `format` | โœ… | email, uuid, date-time, date, time, uri, url, hostname, ipv4, ipv6; others โ†’ `UNSUPPORTED_SCHEMA_KEYWORD` | 3 โœ” | +| `minimum` / `maximum` | โœ… | step = `multipleOf` when present; gap when the value would break another bound | 3 โœ” | +| `exclusiveMinimum` / `exclusiveMaximum` | โœ… | 3.1 numeric and 3.0 boolean form | 3 โœ” | +| `multipleOf` | โœ… | a neighbour of the sample value inside the bounds | 3 โœ” | +| `minItems` / `maxItems` | โœ… | `maxItems` with `uniqueItems` โ†’ gap (repeating breaks uniqueness) | 3 โœ” | +| `uniqueItems` | โœ… | duplicate first element; gap when it would exceed `maxItems` | 3 โœ” | +| `items` constraints | โœ… | recursive through the first element; an empty sample array โ†’ gap | 3 โœ” | +| `minProperties` / `maxProperties` | โœ… | drops optional properties only / adds extra ones; gap when required or `additionalProperties: false` would break | 3 โœ” | +| `additionalProperties: false` | โœ… | any depth | 3 โœ” | +| nested objects / arrays | โœ… | `request.body#/customer/address/city`, `request.body#/items/*/price`, depth โ‰ค 12 | 3 โœ” | +| `allOf` | โœ… | object parts merged | 3 โœ” | +| `oneOf` / `anyOf` / `not` / `discriminator` | โ›” | `UNSUPPORTED_SCHEMA_KEYWORD` at that location: a broken value may still match another branch | 3 โœ” (gap) | +| `readOnly` | โœ… | not sent, no case | 3 โœ” | +| case limit | โœ… | `--max-cases` (default 60 per operation); potential / generated / dropped in `coverage-gaps.json`, each dropped case as `CASE_LIMIT_REACHED` | 3 โœ” | ## Parameters (`src/generate/negative.ts`, `templates.ts`) diff --git a/src/cases/assign.ts b/src/cases/assign.ts index 5917345..01cd7af 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -88,11 +88,11 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): } for (const c of s.bodyCases) { const t = c.target; - ids.contract.body.push(t ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.requestBody(t.field === null ? '' : bodyPointer([t.field])), rule: t.rule }) : ''); + ids.contract.body.push(t?.in === 'body' ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.requestBody(bodyPointer(t.path)), rule: t.rule }) : ''); } for (const c of s.queryCases) { const t = c.target; - ids.contract.query.push(t?.field ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.query(t.field), rule: t.rule }) : ''); + ids.contract.query.push(t?.in === 'query' && t.field ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.query(t.field), rule: t.rule }) : ''); } // CRUD scenarios: steps in order; the operation under test is the action. diff --git a/src/cli.ts b/src/cli.ts index a490491..4f0c54c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -214,6 +214,7 @@ common(program.command('audit').description('analyse a spec (and, if allowed, a common(program.command('generate').description('audit, then generate Playwright API tests for confirmed CRUD dependencies')) .option('--tests-dir ', 'where generated tests are written (default: API_TESTS_DIR or tests/api)') .option('--deps ', 'JSON file with human-confirmed dependencies') + .option('--max-cases ', 'request-body negative cases per operation; the rest is reported as CASE_LIMIT_REACHED', '60') .addOption(new Option('--lang ', 'language of generated tests (default: API_TESTS_LANG or typescript)').choices(['typescript', 'python'])) .option('--run', 'run the generated tests once against --base-url (needs --allow-write)', false) .option('--draft-pr', 'commit to a new branch and open a GitHub Draft PR for review', false) @@ -221,7 +222,7 @@ common(program.command('generate').description('audit, then generate Playwright .addOption(new Option('--ai-runner ', 'console tool: claude, codex, or command (API_AI_COMMAND). Default: API_AI or claude').choices(RUNNERS)) .option('--ai-max-calls ', 'AI call budget per run', '10') .option('--ai-model ', 'model name passed to the console tool (default: its own default)') - .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; aiModel?: string; aiRunner?: RunnerKind }) => { + .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; maxCases: string; aiModel?: string; aiRunner?: RunnerKind }) => { const location = await resolveInputs(specArg, o); o.testsDir ??= cfg.testsDir; o.lang ??= cfg.testsLang; @@ -235,7 +236,9 @@ common(program.command('generate').description('audit, then generate Playwright const deps = o.deps ? JSON.parse(await readFile(o.deps, 'utf8')) : undefined; if (o.ai) await aiProposals(r.spec.doc, r.ops, o.out, { maxCalls: Number(o.aiMaxCalls), model: o.aiModel, runner: o.aiRunner }, deps); log('Generating test suites (functional / contract / scenarios)โ€ฆ'); - const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang }); + const maxCases = Number(o.maxCases); + if (!Number.isInteger(maxCases) || maxCases < 1) throw new Error(`--max-cases must be a positive integer, got "${o.maxCases}".`); + const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases }); for (const s of gen.scenarios) log(` ${s.status.padEnd(9)} ${s.name}`); for (const f of gen.removed) log(` REMOVED ${relative(process.cwd(), f).replace(/\\/g, '/')} (generated earlier, no longer produced)`); if (o.run) { diff --git a/src/generate/body-cases.ts b/src/generate/body-cases.ts new file mode 100644 index 0000000..4eb4e47 --- /dev/null +++ b/src/generate/body-cases.ts @@ -0,0 +1,289 @@ +import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; +import { ARRAY, bodyPointer } from '../cases/ids.js'; +import type { NegCase } from './negative.js'; + +/** + * Request-body negative cases, recursive (docs/SUPPORT_MATRIX.md, stage 3). + * Start from a VALID payload and break exactly ONE rule per case, at any depth: `request.body#/customer/name`, + * `request.body#/items/*\/sku` (the first array element stands for `*`). A rule that cannot be broken without + * breaking another one too (or without a valid element to start from) becomes a coverage gap, never a guess. + */ + +export type PathSeg = string | typeof ARRAY; + +export interface CoverageGap { + code: string; // MISSING_VALID_SAMPLE, CANNOT_ISOLATE_RULE, UNSUPPORTED_SCHEMA_KEYWORD, CASE_LIMIT_REACHED, โ€ฆ + location: string; // case location, e.g. request.body#/customer/address + rule?: string; + reason: string; +} + +export interface BodyCaseResult { + cases: NegCase[]; + gaps: CoverageGap[]; + /** Every case found before the limit. */ + potential: number; + /** Cases dropped by the limit (also listed in gaps as CASE_LIMIT_REACHED). */ + dropped: { location: string; rule: string }[]; +} + +export const DEFAULT_MAX_BODY_CASES = 60; + +const deref = (doc: OpenApiDoc, s: any, depth = 0): any => (s?.$ref && depth < 20 ? deref(doc, resolvePointer(doc, s.$ref.slice(1)).node, depth + 1) : s); +const typesOf = (s: any): string[] => (s?.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type]); +const mainType = (s: any): string | undefined => typesOf(s).find((t) => t !== 'null') ?? (s?.properties ? 'object' : s?.items ? 'array' : undefined); +const allowsNull = (s: any) => typesOf(s).includes('null') || s?.nullable === true || (Array.isArray(s?.enum) && s.enum.includes(null)); +const isNum = (t?: string) => t === 'number' || t === 'integer'; + +/** Merges `allOf` parts that are plain objects (properties, required); anything else is left for the gap check. */ +function merged(doc: OpenApiDoc, raw: any): any { + const s = deref(doc, raw); + if (!s || !Array.isArray(s.allOf)) return s; + const { allOf, ...rest } = s; + const out: any = { ...rest }; + for (const partRaw of allOf) { + const part = merged(doc, partRaw); + if (!part || typeof part !== 'object') continue; + for (const [k, v] of Object.entries(part)) { + if (k === 'properties') out.properties = { ...(out.properties ?? {}), ...v }; + else if (k === 'required') out.required = [...new Set([...(out.required ?? []), ...v])]; + else if (out[k] === undefined) out[k] = v; + } + } + return out; +} + +const clone = (v: T): T => structuredClone(v); +function setAt(root: unknown, path: PathSeg[], value: unknown): unknown { + if (!path.length) return value; + const out = clone(root) as any; + let node = out; + for (let i = 0; i < path.length - 1; i++) node = node[path[i] === ARRAY ? 0 : (path[i] as string)]; + const last = path[path.length - 1]; + node[last === ARRAY ? 0 : (last as string)] = value; + return out; +} +function removeAt(root: unknown, path: PathSeg[]): unknown { + const out = clone(root) as any; + let node = out; + for (let i = 0; i < path.length - 1; i++) node = node[path[i] === ARRAY ? 0 : (path[i] as string)]; + delete node[path[path.length - 1] as string]; + return out; +} + +const label = (path: PathSeg[]) => path.map((p, i) => (p === ARRAY ? '[]' : `${i ? '.' : ''}${p}`)).join('') || '(body)'; + +/** A string that does not match `pattern`, within the length limits; undefined when none of the candidates works. */ +function violatePattern(pattern: string, minLength = 0, maxLength = Infinity): string | undefined { + let re: RegExp; + try { + re = new RegExp(pattern, 'u'); + } catch { + return undefined; + } + const seeds = ['!', '~', ' ', '#', '0', 'a', 'Z', '-', '_']; + for (const seed of seeds) { + for (let len = Math.max(minLength, 1); len <= Math.min(maxLength, Math.max(minLength, 1) + 3); len++) { + const v = seed.repeat(len); + if (!re.test(v)) return v; + } + } + return undefined; +} + +/** Strings that are certainly not of the format (and still strings). */ +const BAD_FORMAT: Record = { + email: 'not-an-email', + uuid: 'not-a-uuid', + 'date-time': 'not-a-date-time', + date: 'not-a-date', + time: 'not-a-time', + uri: 'not a uri', + url: 'not a url', + hostname: '-not_a_host-', + ipv4: '999.999.999.999', + ipv6: 'not-an-ipv6', +}; + +function wrongTypeValue(t: string): unknown { + return { string: 12345, integer: 'not-a-number', number: 'not-a-number', boolean: 'not-a-boolean', array: 'not-an-array', object: 'not-an-object' }[t]; +} + +export function bodyCasesDetailed(doc: OpenApiDoc, rawSchema: any, base: unknown, schemaName = 'body', maxCases = DEFAULT_MAX_BODY_CASES): BodyCaseResult { + const cases: NegCase[] = []; + const gaps: CoverageGap[] = []; + const loc = (path: PathSeg[]) => `request.body#${bodyPointer(path)}`; + const add = (path: PathSeg[], rule: string, title: string, data: unknown) => + cases.push({ title, source: `${schemaName}${path.length ? '.' + label(path) : ''}.${rule}`, data, target: { in: 'body', path, rule } }); + const gap = (path: PathSeg[], code: string, reason: string, rule?: string): void => { + gaps.push({ code, location: loc(path), ...(rule ? { rule } : {}), reason }); + }; + + const walk = (raw: any, value: unknown, path: PathSeg[], depth: number): void => { + if (depth > 12) return gap(path, 'UNSUPPORTED_SCHEMA_KEYWORD', 'schema nesting deeper than 12 levels'); + const s = merged(doc, raw); + if (!s || typeof s !== 'object') return; + if (s.readOnly) return; // not sent in requests + const name = label(path); + // Composition other than allOf: which branch rejects a broken value is not deterministic. + for (const k of ['oneOf', 'anyOf', 'not']) { + if (s[k] !== undefined) { + gap(path, 'UNSUPPORTED_SCHEMA_KEYWORD', `${k}${s.discriminator ? ' with discriminator' : ''}: a broken value may still match another branch, so no case is derived below this point`, k); + return; + } + } + const t = mainType(s); + + // type and null: the value of another type / null where null is not allowed. + if (path.length && t) { + const fixed = Array.isArray(s.enum) || s.const !== undefined; // another type / null would also break enum / const + const wt = wrongTypeValue(t); + if (fixed) gap(path, 'CANNOT_ISOLATE_RULE', 'a value of another type (or null) would also break enum / const; the enum / const case covers it', 'type'); + else { + if (wt !== undefined) add(path, 'type', `"${name}" has wrong type (${t} expected)`, setAt(base, path, wt)); + if (!allowsNull(s)) add(path, 'nullable', `"${name}" is null (not nullable)`, setAt(base, path, null)); + } + } + // enum / const for any scalar type. + if (Array.isArray(s.enum) && s.enum.length && path.length) { + const bad = t === 'string' ? '__not_in_enum__' : isNum(t) ? Math.max(...s.enum.filter((x: unknown) => typeof x === 'number')) + 1 : t === 'boolean' ? [true, false].find((b) => !s.enum.includes(b)) : undefined; + if (bad === undefined || !Number.isFinite(bad as number) && isNum(t)) gap(path, 'CANNOT_ISOLATE_RULE', `enum ${JSON.stringify(s.enum)} covers every value of type ${t}`, 'enum'); + else add(path, 'enum', `"${name}" not in enum`, setAt(base, path, bad)); + } + if (s.const !== undefined && path.length) { + const c = s.const; + const bad = typeof c === 'string' ? `${c}__other` : typeof c === 'number' ? c + 1 : typeof c === 'boolean' ? !c : undefined; + if (bad === undefined) gap(path, 'CANNOT_ISOLATE_RULE', 'const of a non-scalar type', 'const'); + else add(path, 'const', `"${name}" differs from const ${JSON.stringify(c)}`, setAt(base, path, bad)); + } + + if (t === 'string' && path.length) { + const others = (except: string) => ['pattern', 'format', 'enum', 'const'].filter((k) => k !== except && s[k] !== undefined); + const lengthOk = (v: string) => (s.minLength === undefined || v.length >= s.minLength) && (s.maxLength === undefined || v.length <= s.maxLength); + if (typeof s.minLength === 'number' && s.minLength > 0) { + if (others('').length) gap(path, 'CANNOT_ISOLATE_RULE', `a shorter string would also break ${others('').join(', ')}`, 'minLength'); + else add(path, 'minLength', `"${name}" shorter than minLength ${s.minLength}`, setAt(base, path, 'x'.repeat(s.minLength - 1))); + } + if (typeof s.maxLength === 'number') { + if (others('').length) gap(path, 'CANNOT_ISOLATE_RULE', `a longer string would also break ${others('').join(', ')}`, 'maxLength'); + else add(path, 'maxLength', `"${name}" longer than maxLength ${s.maxLength}`, setAt(base, path, 'x'.repeat(s.maxLength + 1))); + } + if (typeof s.pattern === 'string') { + const v = others('pattern').length ? undefined : violatePattern(s.pattern, s.minLength, s.maxLength); + if (v === undefined) gap(path, 'CANNOT_ISOLATE_RULE', others('pattern').length ? `a non-matching string would also break ${others('pattern').join(', ')}` : `no simple string violates ${s.pattern} within the length limits`, 'pattern'); + else add(path, 'pattern', `"${name}" does not match pattern ${s.pattern}`, setAt(base, path, v)); + } + if (typeof s.format === 'string') { + const v = BAD_FORMAT[s.format]; + if (v === undefined) gap(path, 'UNSUPPORTED_SCHEMA_KEYWORD', `format "${s.format}" has no known invalid value`, 'format'); + else if (others('format').length || !lengthOk(v)) gap(path, 'CANNOT_ISOLATE_RULE', `an invalid ${s.format} would also break ${[...others('format'), ...(lengthOk(v) ? [] : ['the length limits'])].join(', ')}`, 'format'); + else add(path, 'format', `"${name}" is not a valid ${s.format}`, setAt(base, path, v)); + } + } + + if (isNum(t) && path.length) { + const step = typeof s.multipleOf === 'number' && s.multipleOf > 0 ? s.multipleOf : t === 'integer' ? 1 : 1; + const isMultiple = (v: number) => typeof s.multipleOf !== 'number' || Math.abs(v / s.multipleOf - Math.round(v / s.multipleOf)) < 1e-9; + const inRange = (v: number, skip: string) => + (skip === 'minimum' || s.minimum === undefined || v >= s.minimum) && + (skip === 'maximum' || s.maximum === undefined || v <= s.maximum) && + (skip === 'exclusiveMinimum' || typeof s.exclusiveMinimum !== 'number' || v > s.exclusiveMinimum) && + (skip === 'exclusiveMaximum' || typeof s.exclusiveMaximum !== 'number' || v < s.exclusiveMaximum); + const tryAdd = (rule: string, v: number, title: string) => { + if ((t === 'integer' && !Number.isInteger(v)) || !isMultiple(v) || !inRange(v, rule) || (Array.isArray(s.enum) && s.enum.length)) gap(path, 'CANNOT_ISOLATE_RULE', `${title}: the value ${v} would also break another constraint`, rule); + else add(path, rule, title, setAt(base, path, v)); + }; + if (typeof s.minimum === 'number') { + // OpenAPI 3.0: exclusiveMinimum: true makes the minimum itself invalid. + if (s.exclusiveMinimum === true) tryAdd('exclusiveMinimum', s.minimum, `"${name}" equals the exclusive minimum ${s.minimum}`); + else tryAdd('minimum', s.minimum - step, `"${name}" below minimum ${s.minimum}`); + } + if (typeof s.maximum === 'number') { + if (s.exclusiveMaximum === true) tryAdd('exclusiveMaximum', s.maximum, `"${name}" equals the exclusive maximum ${s.maximum}`); + else tryAdd('maximum', s.maximum + step, `"${name}" above maximum ${s.maximum}`); + } + if (typeof s.exclusiveMinimum === 'number') tryAdd('exclusiveMinimum', s.exclusiveMinimum, `"${name}" equals the exclusive minimum ${s.exclusiveMinimum}`); + if (typeof s.exclusiveMaximum === 'number') tryAdd('exclusiveMaximum', s.exclusiveMaximum, `"${name}" equals the exclusive maximum ${s.exclusiveMaximum}`); + if (typeof s.multipleOf === 'number' && s.multipleOf > 0) { + const cur = typeof value === 'number' ? value : 0; + const candidates = t === 'integer' ? [cur + 1, cur - 1] : [cur + s.multipleOf / 2, cur - s.multipleOf / 2]; + const v = candidates.find((c) => (t !== 'integer' || Number.isInteger(c)) && !isMultipleOf(c, s.multipleOf) && inRange(c, 'multipleOf') && !(Array.isArray(s.enum) && s.enum.length)); + if (v === undefined) gap(path, 'CANNOT_ISOLATE_RULE', `no value next to ${cur} breaks multipleOf ${s.multipleOf} alone`, 'multipleOf'); + else add(path, 'multipleOf', `"${name}" is not a multiple of ${s.multipleOf}`, setAt(base, path, v)); + } + } + + if (t === 'array') { + const arr = Array.isArray(value) ? value : undefined; + if (!arr) return gap(path, 'MISSING_VALID_SAMPLE', 'no valid array value to start from'); + if (typeof s.minItems === 'number' && s.minItems > 0) add(path, 'minItems', `"${name}" has fewer than minItems ${s.minItems}`, setAt(base, path, arr.slice(0, s.minItems - 1))); + if (typeof s.maxItems === 'number') { + if (!arr.length) gap(path, 'MISSING_VALID_SAMPLE', 'no element to repeat', 'maxItems'); + else if (s.uniqueItems) gap(path, 'CANNOT_ISOLATE_RULE', 'repeating an element would also break uniqueItems', 'maxItems'); + else add(path, 'maxItems', `"${name}" has more than maxItems ${s.maxItems}`, setAt(base, path, Array.from({ length: s.maxItems + 1 }, (_, i) => arr[i % arr.length]))); + } + if (s.uniqueItems === true) { + if (!arr.length) gap(path, 'MISSING_VALID_SAMPLE', 'no element to duplicate', 'uniqueItems'); + else { + const dup = arr.length >= 2 ? [arr[0], arr[0], ...arr.slice(2)] : [arr[0], arr[0]]; + if (typeof s.maxItems === 'number' && dup.length > s.maxItems) gap(path, 'CANNOT_ISOLATE_RULE', 'a duplicate element would also break maxItems', 'uniqueItems'); + else add(path, 'uniqueItems', `"${name}" has duplicate items`, setAt(base, path, dup)); + } + } + if (s.items) { + if (!arr.length) gap([...path, ARRAY], 'MISSING_VALID_SAMPLE', 'the array has no element to break constraints of its items'); + else walk(s.items, arr[0], [...path, ARRAY], depth + 1); + } + return; + } + + if (t === 'object' || s.properties) { + const obj = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : undefined; + if (!obj) return gap(path, 'MISSING_VALID_SAMPLE', 'no valid object value to start from'); + const props: Record = s.properties ?? {}; + const required: string[] = s.required ?? []; + for (const r of required) { + if (r in obj) add([...path, r], 'required', `missing required field "${label([...path, r])}"`, removeAt(base, [...path, r])); + else gap([...path, r], 'MISSING_VALID_SAMPLE', `required "${r}" has no valid value in the sample`, 'required'); + } + if (s.additionalProperties === false) { + const extra = '__unexpected_field__'; + if (typeof s.maxProperties === 'number' && Object.keys(obj).length + 1 > s.maxProperties) gap(path, 'CANNOT_ISOLATE_RULE', 'an unknown field would also break maxProperties', 'additionalProperties'); + else add(path, 'additionalProperties', path.length ? `"${name}" has an unknown field (additionalProperties: false)` : 'unknown field is rejected (additionalProperties: false)', setAt(base, path, { ...obj, [extra]: 'api-agent' })); + } + if (typeof s.minProperties === 'number' && s.minProperties > 0) { + // Drop optional properties only, until one fewer than minProperties remain. + const count = Object.keys(obj).length; + const drop = count - s.minProperties + 1; + const optional = Object.keys(obj).filter((k) => !required.includes(k)); + if (count < s.minProperties) gap(path, 'MISSING_VALID_SAMPLE', 'the sample already breaks minProperties'); + else if (optional.length < drop) gap(path, 'CANNOT_ISOLATE_RULE', 'fewer properties would also drop a required one', 'minProperties'); + else { + const removed = optional.slice(0, drop); + add(path, 'minProperties', `"${name}" has fewer than minProperties ${s.minProperties}`, setAt(base, path, Object.fromEntries(Object.entries(obj).filter(([k]) => !removed.includes(k))))); + } + } + if (typeof s.maxProperties === 'number') { + const free = Object.keys(props).filter((k) => !(k in obj) && !deref(doc, props[k])?.readOnly); + const need = s.maxProperties + 1 - Object.keys(obj).length; + if (need <= 0) gap(path, 'MISSING_VALID_SAMPLE', 'the sample already breaks maxProperties'); + else if (s.additionalProperties !== false) add(path, 'maxProperties', `"${name}" has more than maxProperties ${s.maxProperties}`, setAt(base, path, { ...obj, ...Object.fromEntries(Array.from({ length: need }, (_, i) => [`__extra_${i}__`, 'api-agent'])) })); + else gap(path, 'CANNOT_ISOLATE_RULE', `extra properties would break additionalProperties: false (${free.length} documented optional ones have no valid sample)`, 'maxProperties'); + } + for (const [prop, sub] of Object.entries(props)) { + if (prop in obj) walk(sub, obj[prop], [...path, prop], depth + 1); + } + } + }; + + walk(rawSchema, base, [], 0); + const potential = cases.length; + const kept = cases.slice(0, maxCases); + const dropped = cases.slice(maxCases).map((c) => ({ location: loc((c.target as any).path), rule: c.target!.rule })); + for (const d of dropped) gaps.push({ code: 'CASE_LIMIT_REACHED', location: d.location, rule: d.rule, reason: `limit of ${maxCases} body cases per operation (--max-cases)` }); + return { cases: kept, gaps, potential, dropped }; +} + +function isMultipleOf(v: number, m: number): boolean { + return Math.abs(v / m - Math.round(v / m)) < 1e-9; +} diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 79739bc..9387e6b 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -12,6 +12,7 @@ import { assignCaseIds, type CaseRecord, type ScenarioDefinition } from '../case import { buildRegistry, canonicalJson, fileHash, readRegistry, resolveOperationUids } from '../cases/registry.js'; import { headRevision } from '../change/baseline.js'; import { isUrl } from '../change/network.js'; +import { bodyCasesDetailed, type CoverageGap } from './body-cases.js'; import { bodyCases, documentedRejections, nonexistentIdExpr, queryCases } from './negative.js'; import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; import { API_BASE, buildApiIndex, renderApiBaseClass, renderApiChildClass, renderApis } from './api-objects.js'; @@ -32,6 +33,8 @@ export interface GenerateOptions { deps?: DepsFile; version: string; lang?: TestLang; // default typescript + /** Body negative cases per operation (default 60); the rest is reported as CASE_LIMIT_REACHED. */ + maxCases?: number; } export interface Scenario { @@ -68,6 +71,10 @@ export interface Coverage { positiveBlocked: string | null; negativeGaps: string[]; lifecycle: string | null; + /** Checks that could not be generated, each with a machine code and its exact location. */ + gaps: CoverageGap[]; + /** Body negative cases found / generated / dropped by the limit. */ + bodyCases?: { potential: number; generated: number; dropped: number }; } function jsonBodySchema(spec: LoadedSpec, op: Operation): any { @@ -262,6 +269,8 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const reachable = safe || !!plan; // never fire write requests at operations without confirmed cleanup const why: string[] = []; let bCases: ReturnType = []; + let bodyGaps: CoverageGap[] = []; + let bodyStats: Coverage['bodyCases']; let qCases: ReturnType = []; let notFound: { idExpr: string; param: string } | undefined; let unauthorized = false; @@ -273,7 +282,12 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const schema = jsonBodySchema(spec, op); const base = plan?.chain.create === op ? plan.createPayload : plan?.chain.update === op ? plan.updatePayload : undefined; const bodyTarget = schema && base && typeof base === 'object' && (plan?.chain.create === op || plan?.chain.update === op); - if (bodyTarget) bCases = bodyCases(spec.doc, schema, base as Record, schema.$ref?.split('/').pop() ?? 'body'); + if (bodyTarget) { + const detailed = bodyCasesDetailed(spec.doc, schema, base, schema.$ref?.split('/').pop() ?? 'body', o.maxCases); + bCases = detailed.cases; + bodyGaps = detailed.gaps; + bodyStats = { potential: detailed.potential, generated: detailed.cases.length, dropped: detailed.dropped.length }; + } if (!unresolvedPath.length) qCases = queryCases(op); if (!bCases.length && !qCases.length) why.push(`${rej.validation.join('/')} is documented but there is no constraint the agent can break safely`); } else why.push('no 400/422 documented'); @@ -297,7 +311,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, queryCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. - coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null }); + coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: bodyGaps, ...(bodyStats ? { bodyCases: bodyStats } : {}) }); const render: Record string> = py ? { functional: renderPyFunctional, contract: renderPyContract, scenario: renderPyScenarios } : { functional: renderFunctional, contract: renderContract, scenario: renderScenarios }; diff --git a/src/generate/negative.ts b/src/generate/negative.ts index 4e297dd..b27f518 100644 --- a/src/generate/negative.ts +++ b/src/generate/negative.ts @@ -1,5 +1,7 @@ import type { Operation } from '../types.js'; import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; +import type { ARRAY } from '../cases/ids.js'; +import { bodyCasesDetailed } from './body-cases.js'; /** * Negative cases derived ONLY from what the spec states: @@ -12,19 +14,16 @@ export interface NegCase { source: string; data?: unknown; query?: Record; - /** What the case breaks, for its case ID: a top-level body field (null = the body root) or a query parameter, and the rule. */ - target?: { in: 'body' | 'query'; field: string | null; rule: string }; + /** What the case breaks, for its case ID: a body field (path from the root; [] = the body) or a parameter, and the rule. */ + target?: { in: 'body'; path: (string | typeof ARRAY)[]; rule: string } | { in: 'query'; field: string | null; rule: string }; } -/** Derives the target from the source ("..", ".", "query.."). */ -function withTargets(cases: NegCase[], prefix: string, where: 'body' | 'query'): NegCase[] { +/** Derives the target of a query case from its source ("query.."). */ +function withTargets(cases: NegCase[], prefix: string): NegCase[] { return cases.map((c) => { const rest = c.source.startsWith(prefix + '.') ? c.source.slice(prefix.length + 1) : c.source; const dot = rest.lastIndexOf('.'); - const rule = dot < 0 ? rest : rest.slice(dot + 1); - let field = dot < 0 ? null : rest.slice(0, dot); - if (where === 'body' && field === null && rule === 'required') field = c.title.match(/missing required field "(.*)"$/)?.[1] ?? null; - return { ...c, target: { in: where, field, rule } }; + return { ...c, target: { in: 'query' as const, field: dot < 0 ? null : rest.slice(0, dot), rule: dot < 0 ? rest : rest.slice(dot + 1) } }; }); } @@ -61,64 +60,9 @@ function wrongType(type: string): unknown { const typeOf = (s: any): string | undefined => (Array.isArray(s?.type) ? s.type.find((t: string) => t !== 'null') : s?.type); -/** Body cases: start from a VALID base payload and break exactly one rule per case. */ -export function bodyCases(doc: OpenApiDoc, rawSchema: any, base: Record, schemaName = 'body'): NegCase[] { - const schema = deref(doc, rawSchema); - if (!schema || typeOf(schema) !== 'object' && !schema.properties) return []; - const cases: NegCase[] = []; - const props: Record = schema.properties ?? {}; - const required: string[] = schema.required ?? []; - - for (const r of required) { - if (!(r in base)) continue; - const { [r]: _omit, ...rest } = base; - cases.push({ title: `missing required field "${r}"`, source: `${schemaName}.required`, data: rest }); - } - - for (const [name, raw] of Object.entries(props)) { - const p = deref(doc, raw); - if (!p || p.readOnly) continue; - const t = typeOf(p); - const at = `${schemaName}.${name}`; - const withValue = (v: unknown) => ({ ...base, [name]: v }); - - const wt = t ? wrongType(t) : undefined; - if (wt !== undefined) cases.push({ title: `"${name}" has wrong type (${t} expected)`, source: `${at}.type`, data: withValue(wt) }); - - if (t === 'string') { - if (typeof p.minLength === 'number' && p.minLength > 0) cases.push({ title: `"${name}" shorter than minLength ${p.minLength}`, source: `${at}.minLength`, data: withValue('x'.repeat(p.minLength - 1)) }); - if (typeof p.maxLength === 'number') cases.push({ title: `"${name}" longer than maxLength ${p.maxLength}`, source: `${at}.maxLength`, data: withValue('x'.repeat(p.maxLength + 1)) }); - } - if (t === 'number' || t === 'integer') { - if (typeof p.minimum === 'number') cases.push({ title: `"${name}" below minimum ${p.minimum}`, source: `${at}.minimum`, data: withValue(p.minimum - 1) }); - if (typeof p.maximum === 'number') cases.push({ title: `"${name}" above maximum ${p.maximum}`, source: `${at}.maximum`, data: withValue(p.maximum + 1) }); - } - if (Array.isArray(p.enum) && p.enum.length && t === 'string') { - cases.push({ title: `"${name}" not in enum`, source: `${at}.enum`, data: withValue('__not_in_enum__') }); - } - if ((t === 'number' || t === 'integer') && typeof p.exclusiveMinimum === 'number') { - cases.push({ title: `"${name}" violates exclusiveMinimum ${p.exclusiveMinimum}`, source: `${at}.exclusiveMinimum`, data: withValue(p.exclusiveMinimum) }); - } - if ((t === 'number' || t === 'integer') && typeof p.exclusiveMaximum === 'number') { - cases.push({ title: `"${name}" violates exclusiveMaximum ${p.exclusiveMaximum}`, source: `${at}.exclusiveMaximum`, data: withValue(p.exclusiveMaximum) }); - } - if (t === 'array' && typeof p.minItems === 'number' && p.minItems > 0) { - cases.push({ title: `"${name}" has fewer than minItems ${p.minItems}`, source: `${at}.minItems`, data: withValue([]) }); - } - if (t === 'array' && typeof p.maxItems === 'number') { - const item = deref(doc, p.items); - const sample = item?.example ?? (typeOf(item) === 'string' ? 'x' : typeOf(item) === 'number' || typeOf(item) === 'integer' ? 1 : undefined); - if (sample !== undefined) cases.push({ title: `"${name}" has more than maxItems ${p.maxItems}`, source: `${at}.maxItems`, data: withValue(Array.from({ length: p.maxItems + 1 }, () => sample)) }); - } - } - - if (schema.additionalProperties === false) { - cases.push({ title: 'unknown field is rejected (additionalProperties: false)', source: `${schemaName}.additionalProperties`, data: { ...base, unexpectedField: 'api-agent' } }); - } - if (typeof schema.minProperties === 'number' && schema.minProperties > 0) { - cases.push({ title: `empty object (minProperties ${schema.minProperties})`, source: `${schemaName}.minProperties`, data: {} }); - } - return withTargets(cases.slice(0, MAX_CASES), schemaName, 'body'); +/** Body cases: start from a VALID base payload and break exactly one rule per case, at any depth (see body-cases.ts). */ +export function bodyCases(doc: OpenApiDoc, rawSchema: any, base: Record, schemaName = "body", maxCases?: number): NegCase[] { + return bodyCasesDetailed(doc, rawSchema, base, schemaName, maxCases).cases; } /** Query cases: break one documented query-parameter constraint per case. */ @@ -150,7 +94,7 @@ export function queryCases(op: Operation): NegCase[] { if (t === 'string' && Array.isArray(s.enum) && s.enum.length) cases.push({ title: `query "${p.name}" not in enum`, source: `${at}.enum`, query: withValue('__not_in_enum__') }); if (t === 'string' && typeof s.maxLength === 'number') cases.push({ title: `query "${p.name}" longer than maxLength ${s.maxLength}`, source: `${at}.maxLength`, query: withValue('x'.repeat(s.maxLength + 1)) }); } - return withTargets(cases.slice(0, MAX_CASES), 'query', 'query'); + return withTargets(cases.slice(0, MAX_CASES), 'query'); } /** A runtime expression (TypeScript source) for an id that should not exist, matching the param's schema. */ diff --git a/tests/api/_support/cases.json b/tests/api/_support/cases.json index 5be4142..3c1fb90 100644 --- a/tests/api/_support/cases.json +++ b/tests/api/_support/cases.json @@ -174,6 +174,13 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable": { + "location": "request.body#/name", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required": { "location": "request.body#/name", "polarity": "negative", @@ -195,6 +202,13 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:nullable": { + "location": "request.body#/price", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required": { "location": "request.body#/price", "polarity": "negative", @@ -209,6 +223,34 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:maxLength": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "maxLength", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:minLength": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "minLength", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:nullable": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:type": { + "location": "request.body#/tags/*", + "polarity": "negative", + "rule": "type", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems": { "location": "request.body#/tags", "polarity": "negative", @@ -216,6 +258,13 @@ "subjectUid": "op_UPN7JLUXYUZ7", "suiteType": "contract" }, + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:nullable": { + "location": "request.body#/tags", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_UPN7JLUXYUZ7", + "suiteType": "contract" + }, "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:type": { "location": "request.body#/tags", "polarity": "negative", @@ -318,6 +367,13 @@ "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:nullable": { + "location": "request.body#/name", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_Z4MCICNBZN3S", + "suiteType": "contract" + }, "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:type": { "location": "request.body#/name", "polarity": "negative", @@ -332,6 +388,13 @@ "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:nullable": { + "location": "request.body#/price", + "polarity": "negative", + "rule": "nullable", + "subjectUid": "op_Z4MCICNBZN3S", + "suiteType": "contract" + }, "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:type": { "location": "request.body#/price", "polarity": "negative", @@ -343,6 +406,7 @@ "location": "request.body#/tags", "polarity": "negative", "rule": "maxItems", + "status": "retired", "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, @@ -350,6 +414,7 @@ "location": "request.body#/tags", "polarity": "negative", "rule": "type", + "status": "retired", "subjectUid": "op_Z4MCICNBZN3S", "suiteType": "contract" }, diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index 0521caf..ee02fbd 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -1,5 +1,5 @@ { - "caseRegistryHash": "351fb71f8b54ff5394019b8e29ae73c62398b2f91669315594bbbccb061cb8ec", + "caseRegistryHash": "8b7eb6331738126984b0de2b2ae737f245b0f9fcd294de32cb8e5d1a91e976c8", "files": { "_support/api/generated/AdminApiBase.ts": { "ownership": "generated", @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "96f6872343f76e0718b009caafc62f280eded6df36ad52cbff911ff9b42edbcf" + "sha256": "211c48082b5b8c39231e13220eef773881f49ea29dcc24370e20cfdb5ff743fb" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -179,15 +179,15 @@ "caseIds": [ "ata:op_Z4MCICNBZN3S:contract:positive:response.body#:schema", "ata:op_Z4MCICNBZN3S:contract:positive:response.status#/404:documented", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:type", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:nullable", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:minLength", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:maxLength", "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:type", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:minimum", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:type", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:maxItems", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties", - "ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties" + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:nullable", + "ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:minimum" ], "operationUids": [ "op_Z4MCICNBZN3S", @@ -195,7 +195,7 @@ "op_EDRRXKOK26ZL" ], "ownership": "generated", - "sha256": "8c0b79701cc998ccd4afd0f16c274536cb7fad84af02ef5fbe2189c35bdf4a5b", + "sha256": "1f353d4c44630a9cc9556190625ad61b71aeee5b3215d3159d7f097ca61758cd", "suiteType": "contract" }, "items/patch-by-id/functional.spec.ts": { @@ -231,21 +231,28 @@ "ata:op_UPN7JLUXYUZ7:contract:positive:response.body#:schema", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:minLength", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:maxLength", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:nullable", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:minimum", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:nullable", "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems", - "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties" + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:type", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:nullable", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:minLength", + "ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:maxLength" ], "operationUids": [ "op_UPN7JLUXYUZ7", "op_EDRRXKOK26ZL" ], "ownership": "generated", - "sha256": "373f0a7807196e97caf331181e6cbac8867e14ade0e9a1074f63eb1359b9967b", + "sha256": "c14bca7ba83da65165b9631315895ad5e9323a98af6283aaf043697d783c738b", "suiteType": "contract" }, "items/post/functional.spec.ts": { @@ -346,7 +353,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "4c34a850465f66f749be62929c9df568b247a6d7", + "revision": "ca2c522d318de340e5afdbb31c0fa0a6e85f91ff", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index 7ab1bc5..fac70ce 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "4c34a850465f66f749be62929c9df568b247a6d7", + "capturedRevision": "ca2c522d318de340e5afdbb31c0fa0a6e85f91ff", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/api/items/patch-by-id/contract.spec.ts b/tests/api/items/patch-by-id/contract.spec.ts index 80db385..9c425cd 100644 --- a/tests/api/items/patch-by-id/contract.spec.ts +++ b/tests/api/items/patch-by-id/contract.spec.ts @@ -30,15 +30,15 @@ test.describe('PATCH /items/{itemId} ยท contract', { tag: '@contract' }, () => { }); const invalidBodies = [ + { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemPatch.additionalProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard v2","price":99.5,"__unexpected_field__":"api-agent"} }, + { title: '"(body)" has fewer than minProperties 1', source: 'ItemPatch.minProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties', data: {} }, { title: '"name" has wrong type (string expected)', source: 'ItemPatch.name.type', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:type', data: {"name":12345,"price":99.5} }, + { title: '"name" is null (not nullable)', source: 'ItemPatch.name.nullable', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:nullable', data: {"name":null,"price":99.5} }, { title: '"name" shorter than minLength 1', source: 'ItemPatch.name.minLength', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:minLength', data: {"name":"","price":99.5} }, { title: '"name" longer than maxLength 100', source: 'ItemPatch.name.maxLength', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/name:maxLength', data: {"name":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","price":99.5} }, { title: '"price" has wrong type (number expected)', source: 'ItemPatch.price.type', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:type', data: {"name":"Mechanical keyboard v2","price":"not-a-number"} }, + { title: '"price" is null (not nullable)', source: 'ItemPatch.price.nullable', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:nullable', data: {"name":"Mechanical keyboard v2","price":null} }, { title: '"price" below minimum 0', source: 'ItemPatch.price.minimum', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/price:minimum', data: {"name":"Mechanical keyboard v2","price":-1} }, - { title: '"tags" has wrong type (array expected)', source: 'ItemPatch.tags.type', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:type', data: {"name":"Mechanical keyboard v2","price":99.5,"tags":"not-an-array"} }, - { title: '"tags" has more than maxItems 10', source: 'ItemPatch.tags.maxItems', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#/tags:maxItems', data: {"name":"Mechanical keyboard v2","price":99.5,"tags":["x","x","x","x","x","x","x","x","x","x","x"]} }, - { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemPatch.additionalProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard v2","price":99.5,"unexpectedField":"api-agent"} }, - { title: 'empty object (minProperties 1)', source: 'ItemPatch.minProperties', caseId: 'ata:op_Z4MCICNBZN3S:contract:negative:request.body#:minProperties', data: {} }, ]; for (const c of invalidBodies) { diff --git a/tests/api/items/post/contract.spec.ts b/tests/api/items/post/contract.spec.ts index ce6c540..a66c5cb 100644 --- a/tests/api/items/post/contract.spec.ts +++ b/tests/api/items/post/contract.spec.ts @@ -22,16 +22,23 @@ test.describe('POST /items ยท contract', { tag: '@contract' }, () => { }); const invalidBodies = [ - { title: 'missing required field "name"', source: 'ItemInput.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required', data: {"price":89.9,"tags":["hardware"]} }, - { title: 'missing required field "price"', source: 'ItemInput.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required', data: {"name":"Mechanical keyboard","tags":["hardware"]} }, + { title: 'missing required field "name"', source: 'ItemInput.name.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:required', data: {"price":89.9,"tags":["hardware"]} }, + { title: 'missing required field "price"', source: 'ItemInput.price.required', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:required', data: {"name":"Mechanical keyboard","tags":["hardware"]} }, + { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemInput.additionalProperties', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard","price":89.9,"tags":["hardware"],"__unexpected_field__":"api-agent"} }, { title: '"name" has wrong type (string expected)', source: 'ItemInput.name.type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:type', data: {"name":12345,"price":89.9,"tags":["hardware"]} }, + { title: '"name" is null (not nullable)', source: 'ItemInput.name.nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:nullable', data: {"name":null,"price":89.9,"tags":["hardware"]} }, { title: '"name" shorter than minLength 1', source: 'ItemInput.name.minLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:minLength', data: {"name":"","price":89.9,"tags":["hardware"]} }, { title: '"name" longer than maxLength 100', source: 'ItemInput.name.maxLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/name:maxLength', data: {"name":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","price":89.9,"tags":["hardware"]} }, { title: '"price" has wrong type (number expected)', source: 'ItemInput.price.type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:type', data: {"name":"Mechanical keyboard","price":"not-a-number","tags":["hardware"]} }, + { title: '"price" is null (not nullable)', source: 'ItemInput.price.nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:nullable', data: {"name":"Mechanical keyboard","price":null,"tags":["hardware"]} }, { title: '"price" below minimum 0', source: 'ItemInput.price.minimum', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/price:minimum', data: {"name":"Mechanical keyboard","price":-1,"tags":["hardware"]} }, { title: '"tags" has wrong type (array expected)', source: 'ItemInput.tags.type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:type', data: {"name":"Mechanical keyboard","price":89.9,"tags":"not-an-array"} }, - { title: '"tags" has more than maxItems 10', source: 'ItemInput.tags.maxItems', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems', data: {"name":"Mechanical keyboard","price":89.9,"tags":["x","x","x","x","x","x","x","x","x","x","x"]} }, - { title: 'unknown field is rejected (additionalProperties: false)', source: 'ItemInput.additionalProperties', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#:additionalProperties', data: {"name":"Mechanical keyboard","price":89.9,"tags":["hardware"],"unexpectedField":"api-agent"} }, + { title: '"tags" is null (not nullable)', source: 'ItemInput.tags.nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:nullable', data: {"name":"Mechanical keyboard","price":89.9,"tags":null} }, + { title: '"tags" has more than maxItems 10', source: 'ItemInput.tags.maxItems', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags:maxItems', data: {"name":"Mechanical keyboard","price":89.9,"tags":["hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware","hardware"]} }, + { title: '"tags[]" has wrong type (string expected)', source: 'ItemInput.tags[].type', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:type', data: {"name":"Mechanical keyboard","price":89.9,"tags":[12345]} }, + { title: '"tags[]" is null (not nullable)', source: 'ItemInput.tags[].nullable', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:nullable', data: {"name":"Mechanical keyboard","price":89.9,"tags":[null]} }, + { title: '"tags[]" shorter than minLength 1', source: 'ItemInput.tags[].minLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:minLength', data: {"name":"Mechanical keyboard","price":89.9,"tags":[""]} }, + { title: '"tags[]" longer than maxLength 30', source: 'ItemInput.tags[].maxLength', caseId: 'ata:op_UPN7JLUXYUZ7:contract:negative:request.body#/tags/*:maxLength', data: {"name":"Mechanical keyboard","price":89.9,"tags":["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"]} }, ]; for (const c of invalidBodies) { diff --git a/tests/fixtures/coverage/kitchen-sink.yaml b/tests/fixtures/coverage/kitchen-sink.yaml new file mode 100644 index 0000000..bff4664 --- /dev/null +++ b/tests/fixtures/coverage/kitchen-sink.yaml @@ -0,0 +1,124 @@ +# Synthetic spec covering as many schema keywords and parameter types as possible (docs/SUPPORT_MATRIX.md). +# Every example is valid, so the sampled payload is valid and each negative case breaks exactly one rule. +openapi: 3.1.0 +info: + title: Kitchen sink + version: '1.0' +paths: + /orders: + get: + operationId: listOrders + parameters: + - { name: status, in: query, schema: { type: string, enum: [new, paid] } } + - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 50, multipleOf: 1 } } + - { name: code, in: query, schema: { type: string, pattern: '^[A-Z]{3}$' } } + - { name: since, in: query, schema: { type: string, format: date } } + - { name: tags, in: query, style: form, explode: false, schema: { type: array, items: { type: string }, maxItems: 3 } } + - { name: X-Request-Id, in: header, required: true, schema: { type: string, format: uuid, example: 00000000-0000-4000-8000-000000000001 } } + - { name: session, in: cookie, schema: { type: string, minLength: 8 } } + responses: + '200': + description: ok + headers: + X-Total-Count: { required: true, schema: { type: integer, minimum: 0 } } + content: + application/json: + schema: { type: array, items: { $ref: '#/components/schemas/Order' } } + '400': { description: invalid } + post: + operationId: createOrder + requestBody: + required: true + content: + application/json: + schema: { $ref: '#/components/schemas/OrderInput' } + responses: + '201': + description: created + content: + application/json: + schema: { $ref: '#/components/schemas/Order' } + links: + GetOrder: { operationId: getOrder, parameters: { orderId: '$response.body#/id' } } + DeleteOrder: { operationId: deleteOrder, parameters: { orderId: '$response.body#/id' } } + '400': { description: invalid } + '409': { description: duplicate } + '415': { description: unsupported media type } + /orders/{orderId}: + parameters: + - { name: orderId, in: path, required: true, schema: { type: string, format: uuid } } + get: + operationId: getOrder + responses: + '200': + description: ok + content: + application/json: + schema: { $ref: '#/components/schemas/Order' } + '404': { description: missing } + delete: + operationId: deleteOrder + responses: + '204': { description: deleted } + '404': { description: missing } +components: + schemas: + OrderInput: + type: object + additionalProperties: false + required: [customer, items, total] + properties: + customer: + type: object + required: [name, email] + properties: + name: { type: string, minLength: 2, maxLength: 40, example: Ada } + email: { type: string, format: email, example: ada@example.com } + code: { type: string, pattern: '^[A-Z]{3}$', example: ABC } + address: + type: object + maxProperties: 3 + properties: + city: { type: string, maxLength: 20 } + zip: { type: string } + example: { city: Paris, zip: '75001' } + items: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + type: object + required: [sku, qty] + properties: + sku: { type: string } + qty: { type: integer, minimum: 1, maximum: 10 } + price: { type: number, exclusiveMinimum: 0, exclusiveMaximum: 1000, multipleOf: 0.5 } + example: [{ sku: SKU-1, qty: 2, price: 9.5 }] + total: { type: number, minimum: 0, example: 19 } + status: { type: string, enum: [new, paid], example: new } + priority: { type: integer, enum: [1, 2, 3], example: 1 } + gift: { type: boolean, enum: [false], example: false } + kind: { const: order, example: order } + note: { type: string, example: hi } + comment: { type: [string, 'null'], example: null } + tags: { type: array, items: { type: string, maxLength: 5 }, maxItems: 2, example: [a] } + meta: + type: object + minProperties: 1 + properties: + a: { type: string } + b: { type: string } + example: { a: x, b: y } + payment: + oneOf: + - { type: object, required: [card], properties: { card: { type: string } } } + - { type: object, required: [iban], properties: { iban: { type: string } } } + example: { card: '4111' } + Order: + allOf: + - $ref: '#/components/schemas/OrderInput' + - type: object + required: [id] + properties: + id: { type: string, format: uuid, readOnly: true } diff --git a/tests/unit/body-cases.test.ts b/tests/unit/body-cases.test.ts new file mode 100644 index 0000000..bcfd428 --- /dev/null +++ b/tests/unit/body-cases.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from 'vitest'; +import { readFile, mkdtemp } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import * as addFormatsModule from 'ajv-formats'; +import { parse } from 'yaml'; +import { bodyCasesDetailed } from '../../src/generate/body-cases.js'; +import { sampleFromSchema } from '../../src/generate/sample.js'; +import { generate, findPython } from '../../src/generate/generate.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { loadSpec } from '../../src/spec/loader.js'; +import { ARRAY, bodyPointer, parseCaseId } from '../../src/cases/ids.js'; +import { operationUid } from '../../src/change/normalize.js'; + +const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; +const doc = parse(await readFile('tests/fixtures/coverage/kitchen-sink.yaml', 'utf8')); +const schemaRef = { $ref: '#/components/schemas/OrderInput' }; +const sample = sampleFromSchema(doc, schemaRef); +if (!sample.ok) throw new Error(sample.reason); +const base = sample.value as Record; + +const ajv = new Ajv2020({ allErrors: true, strict: false }); +addFormats(ajv); +ajv.addSchema({ ...doc, $id: 'doc' }); +const validate = ajv.compile({ $ref: 'doc#/components/schemas/OrderInput' }); + +/** The instance path ajv reports for a rule at a case path (array elements are index 0). */ +const instancePath = (path: (string | typeof ARRAY)[]) => path.map((p) => '/' + (p === ARRAY ? '0' : String(p).replace(/~/g, '~0').replace(/\//g, '~1'))).join(''); + +describe('stage 3: recursive request-body cases', () => { + const r = bodyCasesDetailed(doc, schemaRef, base, 'OrderInput', 500); + + it('the sampled base payload is valid', () => { + expect(validate(base), JSON.stringify(validate.errors)).toBe(true); + }); + + it('every case breaks exactly one rule: one ajv error, the expected keyword, at the expected place', () => { + expect(r.cases.length).toBeGreaterThan(30); + for (const c of r.cases) { + const t = c.target as { in: 'body'; path: (string | typeof ARRAY)[]; rule: string }; + expect(validate(c.data), `${c.title} should be invalid`).toBe(false); + const errors = validate.errors ?? []; + expect(errors.length, `${c.title}: ${JSON.stringify(errors)}`).toBe(1); + const e = errors[0]; + const keyword = t.rule === 'nullable' ? 'type' : t.rule; + expect(e.keyword, c.title).toBe(keyword); + if (t.rule === 'required') { + expect(e.instancePath, c.title).toBe(instancePath(t.path.slice(0, -1))); + expect(e.params.missingProperty, c.title).toBe(t.path[t.path.length - 1]); + } else expect(e.instancePath, c.title).toBe(instancePath(t.path)); + } + }); + + it('covers nested objects, array items and every supported keyword', () => { + const got = new Set(r.cases.map((c) => `${bodyPointer((c.target as any).path)}:${c.target!.rule}`)); + for (const want of [ + '/customer:type', '/customer/name:required', '/customer/name:minLength', '/customer/name:maxLength', '/customer/name:nullable', + '/customer/email:format', '/customer/code:pattern', '/customer/address:maxProperties', '/customer/address/city:maxLength', + '/items:minItems', '/items:uniqueItems', '/items/*/sku:required', '/items/*/qty:minimum', '/items/*/qty:maximum', + '/items/*/price:exclusiveMinimum', '/items/*/price:exclusiveMaximum', '/items/*/price:multipleOf', + '/total:minimum', '/status:enum', '/priority:enum', '/gift:enum', '/kind:const', '/tags/*:maxLength', '/tags:maxItems', + '/meta:minProperties', ':additionalProperties', + ]) expect(got, want).toContain(want); + expect(got).not.toContain('/comment:nullable'); // null is allowed there + }); + + it('cannot-isolate and unsupported rules are coverage gaps with code and exact location', () => { + const gaps = r.gaps.map((g) => `${g.code} ${g.location} ${g.rule ?? ''}`.trim()); + expect(gaps).toContain('UNSUPPORTED_SCHEMA_KEYWORD request.body#/payment oneOf'); + expect(gaps).toContain('CANNOT_ISOLATE_RULE request.body#/items maxItems'); // repeating would break uniqueItems + expect(gaps).toContain('CANNOT_ISOLATE_RULE request.body#/status type'); // the enum case covers it + }); + + it('the case limit is reported, not silent', () => { + const limited = bodyCasesDetailed(doc, schemaRef, base, 'OrderInput', 5); + expect(limited.cases).toHaveLength(5); + expect(limited.potential).toBe(r.cases.length); + expect(limited.dropped).toHaveLength(r.cases.length - 5); + expect(limited.gaps.filter((g) => g.code === 'CASE_LIMIT_REACHED')).toHaveLength(r.cases.length - 5); + }); + + it('generated suites: nested pointers in case IDs, same cases in TypeScript and Python, gaps in coverage', async () => { + const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); + const ops = buildCatalog(spec.doc); + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-ks-')); + const res = await generate(spec, ops, { outDir: dir, version: 'test', lang, maxCases: 500 }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')) }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const uid = operationUid('POST', '/orders'); + expect(ts.reg.cases[`ata:${uid}:contract:negative:request.body#/items/*/price:multipleOf`]).toBeDefined(); + expect(ts.reg.cases[`ata:${uid}:contract:negative:request.body#/customer/address/city:maxLength`]).toBeDefined(); + for (const id of Object.keys(ts.reg.cases)) expect(parseCaseId(id).ok, id).toBe(true); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + const cov = ts.res.coverage.find((c) => c.operation === 'POST /orders')!; + expect(cov.bodyCases).toEqual({ potential: r.cases.length, generated: r.cases.length, dropped: 0 }); + expect(cov.gaps.some((g) => g.code === 'UNSUPPORTED_SCHEMA_KEYWORD' && g.location === 'request.body#/payment')).toBe(true); + const pyFile = join(py.dir, 'orders/post/test_contract.py'); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', pyFile], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); +}); From 9142b4bfc92cba8ebcfaecd302af395090aac8c6 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:24:45 +0100 Subject: [PATCH 3/8] feat(coverage): query, header, cookie and path parameter cases (stage 4) - src/generate/param-cases.ts: a valid request (every required query / header / cookie parameter with its documented value) in which exactly one parameter breaks exactly one rule; rules from the body engine (required, type for number / integer / boolean, enum, const, pattern, format, bounds, multipleOf, lengths, min/maxItems, uniqueItems). - Arrays serialized as documented: form explode true / false, spaceDelimited, pipeDelimited; header simple; cookies in the Cookie header. - Path parameters: invalid type / format / pattern / enum / length; numeric bounds on write operations are UNSAFE_LIVE_CHECK gaps (an out-of-range id could address a real record). - Required header / cookie parameters are sent in every generated call (TypeScript optionsWith, Python pyRequired); one without a documented value blocks the operation. - One data-driven loop over whole requests in TypeScript and Python; catalog keeps style / explode. The old query-only generator is removed. - Tests: every case leaves the other parameters valid and breaks its own rule; serialization; path safety; gaps; TS/Python parity on the fixture. Demo API: 58 tests in TypeScript and Python, only stats/get/contract fails. Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 31 +-- src/cases/assign.ts | 11 +- src/generate/generate.ts | 18 +- src/generate/negative.ts | 45 +---- src/generate/param-cases.ts | 180 ++++++++++++++++++ src/generate/python.ts | 58 ++++-- src/generate/templates.ts | 55 ++++-- src/spec/catalog.ts | 2 + src/types.ts | 3 + tests/api/_support/generation-manifest.json | 6 +- tests/api/_support/openapi.snapshot.meta.json | 2 +- tests/api/items/get/contract.spec.ts | 10 +- tests/fixtures/coverage/kitchen-sink.yaml | 4 +- tests/unit/core.test.ts | 12 +- tests/unit/param-cases.test.ts | 115 +++++++++++ 15 files changed, 439 insertions(+), 113 deletions(-) create mode 100644 src/generate/param-cases.ts create mode 100644 tests/unit/param-cases.test.ts diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 9b774bf..ed12dcc 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -34,21 +34,26 @@ 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 โœ” | -## Parameters (`src/generate/negative.ts`, `templates.ts`) +## Parameters (`src/generate/param-cases.ts`) -| Target | State | Limits | Stage | +Every case is a valid request (each required query / header / cookie parameter with its documented value) in which exactly one parameter breaks exactly one rule (verified in `tests/unit/param-cases.test.ts` against the parameter schemas). The rules come from the same engine as request bodies. Expected result: a documented 400 / 422 / 4XX. + +| Target | State | Limits / gap | Stage | |---|---|---|---| -| query `required` | ๐ŸŸก | only when the spec gives a valid value | 4 | -| query `type` | ๐ŸŸก | number, integer, boolean | 4 | -| query `minimum` / `maximum` / exclusive | โœ… | | | -| query `minLength` / `maxLength` | โœ… | | | -| query `enum` (invalid value) | ๐ŸŸก | string only | 4 | -| query `const`, `pattern`, `format`, `multipleOf` | โŒ | | 4 | -| query arrays, `style` / `explode` | โŒ | | 4 | -| query boundary-valid values | โŒ | | 4 / 7 | -| path parameter constraints | โŒ | only unknown id โ†’ 404 | 4 | -| header parameters | โŒ | | 4 | -| cookie parameters | โŒ | | 4 | +| required (missing) | โœ… | query, header, cookie; needs the documented value of every required parameter, else `MISSING_VALID_SAMPLE` and no cases | 4 โœ” | +| `type` | โœ… | number, integer, boolean (a string parameter cannot have a wrong type on the wire) | 4 โœ” | +| `enum`, `const` | โœ… | | 4 โœ” | +| `pattern`, `format` | โœ… | as for bodies | 4 โœ” | +| `minimum` / `maximum` / exclusive / `multipleOf` | โœ… | | 4 โœ” | +| `minLength` / `maxLength` | โœ… | | 4 โœ” | +| arrays: `minItems` / `maxItems` / `uniqueItems` | โœ… | query `form` (explode true โ†’ repeated keys, false โ†’ comma), `spaceDelimited`, `pipeDelimited`; header `simple` | 4 โœ” | +| array item / object member constraints in parameters | โ›” | `UNSUPPORTED_SCHEMA_KEYWORD` | 4 โœ” (gap) | +| `deepObject`, object parameters, array cookies | โ›” | `UNSUPPORTED_SCHEMA_KEYWORD` | 4 โœ” (gap) | +| header parameters | โœ… | `Authorization`, `Content-Type`, `Accept` are not parameters (OpenAPI) | 4 โœ” | +| cookie parameters | โœ… | sent in the `Cookie` header | 4 โœ” | +| path parameters | โœ… | type, format, pattern, enum, length; on write operations numeric bounds โ†’ `UNSAFE_LIVE_CHECK` (an out-of-range id could address a real record); other path parameters need documented values (`MISSING_RESOURCE_SOURCE`); not on operations whose body is required | 4 โœ” | +| required header / cookie in every generated call | โœ… | positive, 404, 401, body and parameter cases; a required one without a documented value blocks the operation with its reason | 4 โœ” | +| boundary-valid values | โŒ | | 7 | ## Functional (`functional.spec.ts`) diff --git a/src/cases/assign.ts b/src/cases/assign.ts index 01cd7af..e1e2321 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -25,7 +25,7 @@ export interface ScenarioDefinition { export interface SuiteCaseIds { /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ functional: { success?: string; notFound?: string; unauthorized?: string; variants: string[] }; - contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; query: string[] }; + contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[] }; scenario: { createRead?: string; updateRead?: string; deleteGone?: string }; /** Every case of this operation, by suite, with metadata for cases.json. */ records: Record<'functional' | 'contract' | 'scenario', CaseRecord[]>; @@ -39,7 +39,7 @@ export interface AssignInput { chain?: CrudChain; positive: boolean; bodyCases: NegCase[]; - queryCases: NegCase[]; + paramCases: NegCase[]; notFound?: { param: string }; unauthorized: boolean; scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean }; @@ -61,7 +61,7 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): return id; }; const ok = successStatus(s.op); - const ids: SuiteCaseIds = { functional: { variants: [] }, contract: { body: [], query: [] }, scenario: {}, records, scenarios }; + const ids: SuiteCaseIds = { functional: { variants: [] }, contract: { body: [], params: [] }, scenario: {}, records, scenarios }; const rel = related.length ? { relatedOperationUids: related } : {}; if (s.positive) { @@ -90,9 +90,10 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): const t = c.target; ids.contract.body.push(t?.in === 'body' ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.requestBody(bodyPointer(t.path)), rule: t.rule }) : ''); } - for (const c of s.queryCases) { + for (const c of s.paramCases) { const t = c.target; - ids.contract.query.push(t?.in === 'query' && t.field ? add('contract', { subjectUid: uid, polarity: 'negative', location: location.query(t.field), rule: t.rule }) : ''); + const at = t && t.in !== 'body' && t.field ? { query: location.query, header: location.header, cookie: location.cookie, path: location.path }[t.in](t.field) : undefined; + ids.contract.params.push(at ? add('contract', { subjectUid: uid, polarity: 'negative', location: at, rule: t!.rule }) : ''); } // CRUD scenarios: steps in order; the operation under test is the action. diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 9387e6b..9da86d4 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -13,7 +13,8 @@ import { buildRegistry, canonicalJson, fileHash, readRegistry, resolveOperationU import { headRevision } from '../change/baseline.js'; import { isUrl } from '../change/network.js'; import { bodyCasesDetailed, type CoverageGap } from './body-cases.js'; -import { bodyCases, documentedRejections, nonexistentIdExpr, queryCases } from './negative.js'; +import { paramCasesDetailed, sendable } from './param-cases.js'; +import { bodyCases, documentedRejections, nonexistentIdExpr, type NegCase } from './negative.js'; import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; import { API_BASE, buildApiIndex, renderApiBaseClass, renderApiChildClass, renderApis } from './api-objects.js'; import { PY_FILES, pyName, renderConftest, renderPyContract, renderPyFunctional, renderPyResource, renderPyScenarios, resourceModule } from './python.js'; @@ -242,7 +243,8 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const safe = SAFE_METHODS.includes(op.method); const pathParams = op.params.filter((p) => p.in === 'path'); const unresolvedPath = pathParams.filter((p) => p.knownValue === undefined && p.name !== plan?.chain.param); - const unresolvedQuery = op.params.filter((p) => p.in === 'query' && p.required && p.knownValue === undefined); + // Required query / header / cookie parameters need a documented value, or no valid request exists. + const unresolvedQuery = op.params.filter((p) => p.in !== 'path' && p.required && p.knownValue === undefined && sendable(p)); // --- positive let posReason: string | undefined; @@ -271,7 +273,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp let bCases: ReturnType = []; let bodyGaps: CoverageGap[] = []; let bodyStats: Coverage['bodyCases']; - let qCases: ReturnType = []; + let qCases: NegCase[] = []; let notFound: { idExpr: string; param: string } | undefined; let unauthorized = false; @@ -288,7 +290,11 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp bodyGaps = detailed.gaps; bodyStats = { potential: detailed.potential, generated: detailed.cases.length, dropped: detailed.dropped.length }; } - if (!unresolvedPath.length) qCases = queryCases(op); + // Path parameters: only where an invalid value cannot reach a request body we cannot build. + const allowPath = !op.requestBodyRequired; + const pc = paramCasesDetailed(spec.doc, op, { allowPath, allowOthers: !unresolvedPath.length }); + qCases = pc.cases; + bodyGaps = [...bodyGaps, ...pc.gaps]; if (!bCases.length && !qCases.length) why.push(`${rej.validation.join('/')} is documented but there is no constraint the agent can break safely`); } else why.push('no 400/422 documented'); @@ -305,10 +311,10 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp } // --- suites - const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, queryCases: qCases, notFound, unauthorized }; + const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized }; 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, queryCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants }, uidOf); + const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: bodyGaps, ...(bodyStats ? { bodyCases: bodyStats } : {}) }); diff --git a/src/generate/negative.ts b/src/generate/negative.ts index b27f518..45a11ae 100644 --- a/src/generate/negative.ts +++ b/src/generate/negative.ts @@ -2,6 +2,7 @@ import type { Operation } from '../types.js'; import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; import type { ARRAY } from '../cases/ids.js'; import { bodyCasesDetailed } from './body-cases.js'; +import type { ParamRequest } from './param-cases.js'; /** * Negative cases derived ONLY from what the spec states: @@ -15,19 +16,12 @@ export interface NegCase { data?: unknown; query?: Record; /** What the case breaks, for its case ID: a body field (path from the root; [] = the body) or a parameter, and the rule. */ - target?: { in: 'body'; path: (string | typeof ARRAY)[]; rule: string } | { in: 'query'; field: string | null; rule: string }; + target?: { in: 'body'; path: (string | typeof ARRAY)[]; rule: string } | { in: 'query' | 'header' | 'cookie' | 'path'; field: string | null; rule: string }; + /** Parameter cases: the whole request (valid parameters plus the one under test). */ + request?: ParamRequest; } -/** Derives the target of a query case from its source ("query.."). */ -function withTargets(cases: NegCase[], prefix: string): NegCase[] { - return cases.map((c) => { - const rest = c.source.startsWith(prefix + '.') ? c.source.slice(prefix.length + 1) : c.source; - const dot = rest.lastIndexOf('.'); - return { ...c, target: { in: 'query' as const, field: dot < 0 ? null : rest.slice(0, dot), rule: dot < 0 ? rest : rest.slice(dot + 1) } }; - }); -} -const MAX_CASES = 20; export function documentedRejections(op: Operation): { validation: string[]; notFound: boolean; unauthorized: boolean } { const codes = op.responses.map((r) => r.status.toUpperCase()); @@ -65,37 +59,6 @@ export function bodyCases(doc: OpenApiDoc, rawSchema: any, base: Record p.in === 'query'); - const valid: Record = Object.fromEntries(query.filter((p) => p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); - - for (const p of query) { - const s = p.schema ?? {}; - const t = typeOf(s); - const at = `query.${p.name}`; - const withValue = (v: unknown) => ({ ...valid, [p.name]: v }); - if (p.required && p.name in valid) { - const { [p.name]: _omit, ...rest } = valid; - cases.push({ title: `missing required query "${p.name}"`, source: `${at}.required`, query: rest }); - } - if (t === 'integer' || t === 'number') { - cases.push({ title: `query "${p.name}" is not a number`, source: `${at}.type`, query: withValue('abc') }); - if (typeof s.minimum === 'number') cases.push({ title: `query "${p.name}" below minimum ${s.minimum}`, source: `${at}.minimum`, query: withValue(s.minimum - 1) }); - if (typeof s.maximum === 'number') cases.push({ title: `query "${p.name}" above maximum ${s.maximum}`, source: `${at}.maximum`, query: withValue(s.maximum + 1) }); - } - if (t === 'integer' || t === 'number') { - if (typeof s.exclusiveMinimum === 'number') cases.push({ title: `query "${p.name}" violates exclusiveMinimum ${s.exclusiveMinimum}`, source: `${at}.exclusiveMinimum`, query: withValue(s.exclusiveMinimum) }); - if (typeof s.exclusiveMaximum === 'number') cases.push({ title: `query "${p.name}" violates exclusiveMaximum ${s.exclusiveMaximum}`, source: `${at}.exclusiveMaximum`, query: withValue(s.exclusiveMaximum) }); - } - if (t === 'string' && typeof s.minLength === 'number' && s.minLength > 0) cases.push({ title: `query "${p.name}" shorter than minLength ${s.minLength}`, source: `${at}.minLength`, query: withValue('x'.repeat(s.minLength - 1)) }); - if (t === 'boolean') cases.push({ title: `query "${p.name}" is not a boolean`, source: `${at}.type`, query: withValue('not-a-boolean') }); - if (t === 'string' && Array.isArray(s.enum) && s.enum.length) cases.push({ title: `query "${p.name}" not in enum`, source: `${at}.enum`, query: withValue('__not_in_enum__') }); - if (t === 'string' && typeof s.maxLength === 'number') cases.push({ title: `query "${p.name}" longer than maxLength ${s.maxLength}`, source: `${at}.maxLength`, query: withValue('x'.repeat(s.maxLength + 1)) }); - } - return withTargets(cases.slice(0, MAX_CASES), 'query'); -} /** A runtime expression (TypeScript source) for an id that should not exist, matching the param's schema. */ export function nonexistentIdExpr(schema: any): string { diff --git a/src/generate/param-cases.ts b/src/generate/param-cases.ts new file mode 100644 index 0000000..94d9522 --- /dev/null +++ b/src/generate/param-cases.ts @@ -0,0 +1,180 @@ +import type { OpenApiDoc } from '../spec/loader.js'; +import type { Operation, ParamInfo } from '../types.js'; +import { location } from '../cases/ids.js'; +import { bodyCasesDetailed, type CoverageGap } from './body-cases.js'; +import type { NegCase } from './negative.js'; +import { sampleFromSchema } from './sample.js'; + +/** + * Parameter negative cases for query, header, cookie and path (docs/SUPPORT_MATRIX.md, stage 4). + * Each case is a valid request (every required parameter with its documented value) with exactly one parameter + * breaking exactly one rule. The rules come from the same recursive engine as bodies; what does not make sense on the + * wire is dropped (a string parameter cannot have the wrong type, null cannot be sent), and what cannot be sent + * safely or serialized deterministically is a gap. + */ + +export type ParamIn = 'query' | 'header' | 'cookie' | 'path'; + +export interface ParamRequest { + /** Query as an object, or a serialized string when an array needs its documented style. */ + params?: Record | string; + headers?: Record; + /** Path parameter values by name (only the parameter under test; the others keep their documented values). */ + path?: Record; +} + +/** Headers the spec cannot define as parameters (OpenAPI ignores them) or that credentials own. */ +const RESERVED_HEADERS = new Set(['authorization', 'content-type', 'accept']); +const NUMERIC_RULES = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf']; + +export const sendable = (p: ParamInfo) => !(p.in === 'header' && RESERVED_HEADERS.has(p.name.toLowerCase())); + +/** Required query / header / cookie parameters with their documented values: the valid part of every request. */ +export function requiredRequest(op: Operation): { params: Record; headers: Record; missing: ParamInfo[] } { + const params: Record = {}; + const cookies: string[] = []; + const headers: Record = {}; + const missing: ParamInfo[] = []; + for (const p of op.params.filter((x) => x.required && x.in !== 'path' && sendable(x))) { + if (p.knownValue === undefined || (typeof p.knownValue === 'object' && p.knownValue !== null)) { + missing.push(p); + continue; + } + const v = p.knownValue as string | number | boolean; + if (p.in === 'query') params[p.name] = v; + else if (p.in === 'header') headers[p.name] = String(v); + else if (p.in === 'cookie') cookies.push(`${p.name}=${String(v)}`); + } + if (cookies.length) headers.Cookie = cookies.join('; '); + return { params, headers, missing }; +} + +/** OpenAPI serialization of a query array: form (explode: true โ†’ repeated keys, false โ†’ comma), spaceDelimited, pipeDelimited. */ +function serializeQuery(p: ParamInfo & { style?: string; explode?: boolean }, value: unknown, rest: Record): string | undefined { + const parts = Object.entries(rest).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`); + if (!Array.isArray(value)) return undefined; + if (value.some((v) => v !== null && typeof v === 'object')) return undefined; + const style = p.style ?? 'form'; + const explode = p.explode ?? style === 'form'; + const name = encodeURIComponent(p.name); + if (style === 'form' && explode) parts.push(...value.map((v) => `${name}=${encodeURIComponent(String(v))}`)); + else if (style === 'form') parts.push(`${name}=${value.map((v) => encodeURIComponent(String(v))).join(',')}`); + else if (style === 'spaceDelimited' && !explode) parts.push(`${name}=${value.map((v) => encodeURIComponent(String(v))).join('%20')}`); + else if (style === 'pipeDelimited' && !explode) parts.push(`${name}=${value.map((v) => encodeURIComponent(String(v))).join('|')}`); + else return undefined; + return parts.join('&'); +} + +const locOf = (where: ParamIn, name: string) => + where === 'query' ? location.query(name) : where === 'header' ? location.header(name) : where === 'cookie' ? location.cookie(name) : location.path(name); + +export function paramCasesDetailed(doc: OpenApiDoc, op: Operation, opts: { allowPath: boolean; allowOthers: boolean }): { cases: (NegCase & { request: ParamRequest })[]; gaps: CoverageGap[] } { + const cases: (NegCase & { request: ParamRequest })[] = []; + const gaps: CoverageGap[] = []; + const base = requiredRequest(op); + if (base.missing.length) { + for (const p of base.missing) gaps.push({ code: 'MISSING_VALID_SAMPLE', location: locOf(p.in as ParamIn, p.name), reason: `required ${p.in} "${p.name}" has no documented value, so no valid request can be built` }); + return { cases, gaps }; + } + const isWrite = !['get', 'head', 'options'].includes(op.method); + for (const p of op.params.filter(sendable) as (ParamInfo & { style?: string; explode?: boolean })[]) { + const where = p.in as ParamIn; + const loc = locOf(where, p.name); + const s = p.schema ?? {}; + if (where === 'path' ? !opts.allowPath : !opts.allowOthers) continue; + if (where === 'path' && op.params.some((x) => x.in === 'path' && x !== p && x.knownValue === undefined)) { + gaps.push({ code: 'MISSING_RESOURCE_SOURCE', location: loc, reason: 'another path parameter has no documented value' }); + continue; + } + // A valid value of the parameter under test to start from. + let value: unknown = p.knownValue; + if (value === undefined) { + const sample = sampleFromSchema(doc, s); + if (sample.ok) value = sample.value; + } + if (value === undefined) { + // A scalar optional parameter is not sent in the valid request; its cases set the violating value directly, + // so a placeholder is enough. Arrays need a real element to start from. + const scalar = !['array', 'object'].includes(Array.isArray(s.type) ? s.type.find((x: string) => x !== 'null') : s.type); + if (scalar && !p.required) value = null; + else { + gaps.push({ code: 'MISSING_VALID_SAMPLE', location: loc, reason: `${where} "${p.name}" has no documented or derivable valid value` }); + continue; + } + } + const required = p.required && where !== 'path'; + const holder = { type: 'object', properties: { [p.name]: s }, ...(required ? { required: [p.name] } : {}) }; + const r = bodyCasesDetailed(doc, holder, { [p.name]: value }, where, 1000); + const t = Array.isArray(s.type) ? s.type.find((x: string) => x !== 'null') : s.type; + for (const g of r.gaps) if (g.location !== 'request.body#') gaps.push({ ...g, location: loc }); + for (const c of r.cases) { + const tgt = c.target as { path: (string | symbol)[]; rule: string }; + const rule = tgt.rule; + // On the wire every value is text: a string parameter cannot have a wrong type, null cannot be sent, + // and a single value is a valid one-element array. + if (rule === 'nullable' || (rule === 'type' && (t === 'string' || t === 'array' || t === undefined))) continue; + if (tgt.path.length > 1) { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: `constraints of array items / object members in a ${where} parameter are not derived` }); + continue; + } + if (where === 'path' && isWrite && NUMERIC_RULES.includes(rule)) { + gaps.push({ code: 'UNSAFE_LIVE_CHECK', location: loc, rule, reason: `an out-of-range id could address an existing record of ${op.key}` }); + continue; + } + const data = c.data as Record; + const missing = !(p.name in data); + const v = data[p.name]; + const request: ParamRequest = {}; + const params = { ...base.params }; + const headers = { ...base.headers }; + if (where === 'query') { + delete params[p.name]; + if (missing) request.params = params; + else if (Array.isArray(v)) { + const q = serializeQuery(p, v, params); + if (q === undefined) { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: `style "${p.style ?? 'form'}" / explode ${p.explode ?? '(default)'} is not serialized` }); + continue; + } + request.params = q; + } else if (v !== null && typeof v === 'object') { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'object query parameters are not serialized' }); + continue; + } else request.params = { ...params, [p.name]: v as string | number | boolean }; + } else { + if (Object.keys(params).length) request.params = params; + if (where === 'header') { + for (const k of Object.keys(headers)) if (k.toLowerCase() === p.name.toLowerCase()) delete headers[k]; + if (!missing) { + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'object headers are not serialized' }); + continue; + } + headers[p.name] = Array.isArray(v) ? v.map(String).join(',') : String(v); // style: simple + } + } else if (where === 'cookie') { + const others = (headers.Cookie ?? '').split('; ').filter((x) => x && !x.startsWith(`${p.name}=`)); + if (!missing) { + if (v !== null && typeof v === 'object') { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'array / object cookies are not serialized' }); + continue; + } + others.push(`${p.name}=${String(v)}`); + } + if (others.length) headers.Cookie = others.join('; '); + else delete headers.Cookie; + } else { + if (v !== null && typeof v === 'object') { + gaps.push({ code: 'UNSUPPORTED_SCHEMA_KEYWORD', location: loc, rule, reason: 'array / object path parameters are not serialized' }); + continue; + } + request.path = { [p.name]: String(v) }; + } + } + if (Object.keys(headers).length) request.headers = headers; + const title = c.title.replace(/^"([^"]*)"/, `${where} "$1"`).replace(/^missing required field "([^"]*)"/, `missing required ${where} "$1"`); + cases.push({ title, source: `${where}.${p.name}.${rule}`, request, target: { in: where, field: p.name, rule } }); + } + } + return { cases, gaps }; +} diff --git a/src/generate/python.ts b/src/generate/python.ts index fd57fcf..2452281 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -1,4 +1,5 @@ import type { Operation } from '../types.js'; +import { requiredRequest } from './param-cases.js'; import { hasFill, queryVariants, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; /** @@ -51,6 +52,25 @@ function pathExpr(op: Operation, chainParam?: string, idVar = 'resource_id'): st return `f${str(p)}`; } +/** Keyword arguments with the operation's required query / header / cookie parameters (documented values). */ +function pyRequired(op: Operation, skip: ('params' | 'headers')[] = []): string { + const r = requiredRequest(op); + return [ + Object.keys(r.params).length && !skip.includes('params') ? `, params=${pyLit(r.params, 4)}` : '', + Object.keys(r.headers).length && !skip.includes('headers') ? `, headers=${pyLit(r.headers, 4)}` : '', + ].join(''); +} + +/** Path whose parameters come from the row's "path" values, else their documented values. */ +function pathFromParts(op: Operation): string { + let p = op.path.replace(/^\//, '').replace(/[{}]/g, (c) => c + c); + for (const param of op.params.filter((x) => x.in === 'path')) { + const known = param.knownValue === undefined ? "'unused'" : `'${String(param.knownValue).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`; + p = p.replace(`{{${param.name}}}`, `{quote(str(path.get('${param.name}', ${known})), safe='')}`); + } + return `f${str(p)}`; +} + const header = (kind: string, op: Operation, meta: Meta, extra: string[]) => [ `"""${op.key} ยท ${kind} cases. Generated by api-test-agent ${meta.version}.`, @@ -350,16 +370,14 @@ function pyPositive(s: SuiteInput, name: string, assert: (indent: string) => str const role = roleOf(op, plan); const res = plan ? resourceModule(plan).replace(/_resource$/, '') : ''; if (!role) { - const query = Object.fromEntries(op.params.filter((p) => p.in === 'query' && p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); - const params = Object.keys(query).length ? `, params=${pyLit(query, 4)}` : ''; - return [POS, `def ${name}(api, contract):`, ` res = api.${op.method}(${pathExpr(op)}${params})`, ...assert(' '), '', '']; + return [POS, `def ${name}(api, contract):`, ` res = api.${op.method}(${pathExpr(op)}${pyRequired(op)})`, ...assert(' '), '', '']; } if (role === 'create') { - return [POS, `def ${name}(api, contract, ${res}):`, ` res = api.${op.method}(${pathExpr(op)}, json=${res}.new_create_payload())`, ' try:', ...assert(' '), ' finally:', ` ${res}.remove_if_created(res)`, '', '']; + return [POS, `def ${name}(api, contract, ${res}):`, ` res = api.${op.method}(${pathExpr(op)}, json=${res}.new_create_payload()${pyRequired(op)})`, ' try:', ...assert(' '), ' finally:', ` ${res}.remove_if_created(res)`, '', '']; } const body = role === 'update' ? `, json=${res}.new_update_payload()` : ''; // created_ removes the resource after the test (best effort: a deleted one is already gone). - return [POS, `def ${name}(api, contract, ${res}, created_${res}):`, ` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}${body})`, ...assert(' '), '', '']; + return [POS, `def ${name}(api, contract, ${res}, created_${res}):`, ` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}${body}${pyRequired(op)})`, ...assert(' '), '', '']; } const pyNotFoundId = (idExpr: string) => (idExpr === 'randomUUID()' ? 'str(uuid.uuid4())' : /^\d+$/.test(idExpr) ? `str(${idExpr})` : 'f"nonexistent-{uuid.uuid4().hex}"'); @@ -373,7 +391,7 @@ function pyNotFound(s: SuiteInput, name: string, mark: string, assert: string): mark, `def ${name}(api, contract${body ? `, ${res}` : ''}):`, ` missing_id = ${pyNotFoundId(s.notFound!.idExpr)}`, - ` res = api.${op.method}(${pathExpr(op, chain?.param ?? s.notFound!.param, 'missing_id')}${body ? `, json=${res}.new_update_payload()` : ''})`, + ` res = api.${op.method}(${pathExpr(op, chain?.param ?? s.notFound!.param, 'missing_id')}${body ? `, json=${res}.new_update_payload()` : ''}${pyRequired(op)})`, ` ${assert}`, '', '', @@ -381,7 +399,7 @@ function pyNotFound(s: SuiteInput, name: string, mark: string, assert: string): } function pyAnonymous(s: SuiteInput, name: string, mark: string, assert: string): string[] { - return [mark, `def ${name}(anonymous_api, contract):`, ` res = anonymous_api.${s.op.method}(${pathExpr(s.op, s.plan?.chain.param, '"unused"')})`, ` ${assert}`, '', '']; + return [mark, `def ${name}(anonymous_api, contract):`, ` res = anonymous_api.${s.op.method}(${pathExpr(s.op, s.plan?.chain.param, '"unused"')}${pyRequired(s.op)})`, ` ${assert}`, '', '']; } const statusIs = (op: Operation, code: string) => @@ -415,11 +433,11 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { // One physical test (and case ID) per documented query value, as in the TypeScript suite. const variants = s.positive && !plan && op.method === 'get' ? queryVariants(op) : []; if (variants.length) { - const base = Object.fromEntries(op.params.filter((p) => p.in === 'query' && p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); + const base = requiredRequest(op).params; L.push('QUERY_VALUES = ['); variants.forEach((v, n) => L.push(` pytest.param(${pyLit({ ...base, [v.name]: v.value }, 4)}, id=${str(`${v.name}=${String(v.value)}`)}${paramMarks(s.ids?.functional.variants[n])}),`)); L.push(']', '', '', POS, '@pytest.mark.parametrize("params", QUERY_VALUES)', 'def test_accepts_documented_query_value(api, params):'); - L.push(` res = api.${op.method}(${pathExpr(op)}, params=params)`, ` ${assertSuccess(op)}`, '', ''); + L.push(` res = api.${op.method}(${pathExpr(op)}, params=params${pyRequired(op, ['params'])})`, ` ${assertSuccess(op)}`, '', ''); } if (s.notFound) L.push(...pyNotFound(s, 'test_returns_documented_404_for_unknown_id', withId(NEG, s.ids?.functional.notFound), statusIs(op, '404'))); if (s.unauthorized) L.push(...pyAnonymous(s, 'test_returns_documented_401_without_credentials', withId(NEG, s.ids?.functional.unauthorized), statusIs(op, '401'))); @@ -435,7 +453,7 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { const needsExisting = !!chain && chain.create !== op && op.params.some((p) => p.in === 'path' && p.name === chain.param); const expect = `contract.expect(res, ${str(op.method)}, ${str(op.path)})`; const L = pyHeader('contract', s, meta, ['Checks conformance to the OpenAPI document: the status actually returned is documented and the body matches its schema.', 'Invalid requests break one documented constraint each and must get a documented rejection.']); - if (s.bodyCases.length || s.queryCases.length) L.push(`REJECTION = ${pyLit(s.validation)} # documented in the spec`, '', ''); + if (s.bodyCases.length || s.paramCases.length) L.push(`REJECTION = ${pyLit(s.validation)} # documented in the spec`, '', ''); if (s.positive) L.push(...pyPositive(s, 'test_success_response_matches_contract', (i) => [`${i}${expect}`], s.ids?.contract.success)); if (s.notFound) L.push(...pyNotFound(s, 'test_response_for_unknown_id_matches_contract', withId(POS, s.ids?.contract.notFound), expect)); if (s.unauthorized) L.push(...pyAnonymous(s, 'test_response_without_credentials_matches_contract', withId(POS, s.ids?.contract.unauthorized), expect)); @@ -446,19 +464,25 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { L.push(']', '', '', NEG, '@pytest.mark.parametrize("payload", INVALID_BODIES)'); if (needsExisting) { L.push(`def test_rejects_invalid_body(api, contract, created_${res}, payload):`); - L.push(` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}, json=payload)`); + L.push(` res = api.${op.method}(${pathExpr(op, chain!.param, `created_${res}`)}, json=payload${pyRequired(op)})`); } else { L.push(`def test_rejects_invalid_body(api, contract${isCreate ? `, ${res}` : ''}, payload):`); - L.push(` res = api.${op.method}(${pathExpr(op, chain?.param)}, json=payload)`); + L.push(` res = api.${op.method}(${pathExpr(op, chain?.param)}, json=payload${pyRequired(op)})`); if (isCreate) L.push(` ${res}.remove_if_created(res)`); } L.push(` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, '', ''); } - if (s.queryCases.length) { - L.push('INVALID_QUERIES = ['); - s.queryCases.forEach((c, n) => L.push(` pytest.param(${pyLit(c.query, 4)}, id=${str(c.title)}${paramMarks(s.ids?.contract.query[n])}), # ${c.source}`)); - L.push(']', '', '', NEG, '@pytest.mark.parametrize("params", INVALID_QUERIES)', 'def test_rejects_invalid_query(api, contract, params):'); - L.push(` res = api.${op.method}(${pathExpr(op)}, params=params)`, ` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, '', ''); + if (s.paramCases.length) { + // Each row is a whole request: the valid required parameters plus the one parameter under test. + L.push('INVALID_PARAMETERS = ['); + s.paramCases.forEach((c, n) => { + const r = c.request ?? (c.query ? { params: c.query as Record } : {}); + const parts = Object.fromEntries(Object.entries({ params: r.params, headers: r.headers, path: r.path }).filter(([, v]) => v !== undefined)); + L.push(` pytest.param(${pyLit(parts, 4)}, id=${str(c.title)}${paramMarks(s.ids?.contract.params[n])}), # ${c.source}`); + }); + L.push(']', '', '', NEG, '@pytest.mark.parametrize("parts", INVALID_PARAMETERS)', 'def test_rejects_invalid_parameter(api, contract, parts):'); + L.push(' path = parts.get("path", {})'); + L.push(` res = api.${op.method}(${pathFromParts(op)}, params=parts.get("params"), headers=parts.get("headers"))`, ` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, '', ''); } return finish(L); } diff --git a/src/generate/templates.ts b/src/generate/templates.ts index 3ac912a..c675a24 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -3,6 +3,7 @@ import type { CrudChain } from './graph.js'; import type { NegCase } from './negative.js'; import { apiCall, type ApiRef } from './api-objects.js'; import type { SuiteCaseIds } from '../cases/assign.js'; +import { requiredRequest, type ParamRequest } from './param-cases.js'; /** Payloads and assumptions for one confirmed resource chain. */ export interface ChainPlan { @@ -54,7 +55,21 @@ function expectSuccess(op: Operation, v = 'res') { } function requiredQuery(op: Operation): Record { - return Object.fromEntries(op.params.filter((p) => p.in === 'query' && p.required && p.knownValue !== undefined).map((p) => [p.name, p.knownValue])); + return requiredRequest(op).params; +} + +/** + * Request options with the operation's required query / header / cookie parameters (documented values) merged in. + * `inner` is an options literal such as "{ data: c.data }"; its own params / headers win. + */ +export function optionsWith(op: Operation, inner?: string): string | undefined { + const req = requiredRequest(op); + const body = inner ? inner.trim().replace(/^\{\s*/, '').replace(/\s*\}$/, '') : ''; + const fields: string[] = []; + if (Object.keys(req.params).length && !/\bparams:/.test(body)) fields.push(`params: ${JSON.stringify(req.params)}`); + if (Object.keys(req.headers).length && !/\bheaders:/.test(body)) fields.push(`headers: ${JSON.stringify(req.headers)}`); + if (body) fields.push(body); + return fields.length ? `{ ${fields.join(', ')} }` : undefined; } /** Safe query variations: only values explicitly allowed by the schema. */ @@ -199,7 +214,7 @@ export interface SuiteInput { positive: boolean; // a successful call can be sent safely validation: string[]; // documented validation rejections: 400 / 422 / 4XX bodyCases: NegCase[]; - queryCases: NegCase[]; + paramCases: NegCase[]; notFound?: { idExpr: string; param: string }; unauthorized: boolean; /** Stable case IDs of this operation's tests (Playwright annotation caseId, pytest marker api_case_id). */ @@ -231,7 +246,7 @@ export function suiteCounts(s: SuiteInput): Record { const sc = scenarioCases(s); return { functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0), - contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.queryCases.length, + contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length, scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0), }; } @@ -261,10 +276,9 @@ function positiveTest(s: SuiteInput, title: string, assert: (indent: string) => const chain = plan?.chain; const role = roleOf(op, plan); const ref = refs.get(op)!; - const call = (idVar?: string, options?: string) => apiCall(ref, 'api', pathArgs(op, ref, chain?.param, idVar), options); + const call = (idVar?: string, options?: string) => apiCall(ref, 'api', pathArgs(op, ref, chain?.param, idVar), optionsWith(op, options)); if (!role) { - const query = requiredQuery(op); - const opts = Object.keys(query).length ? `{ params: ${JSON.stringify(query)} }` : undefined; + const opts = optionsWith(op); const fx = apiFixture(op); return [ ` test(${q(title)}, ${POS}, async ({ ${fx} }) => {`, @@ -315,11 +329,11 @@ function notFoundCall(s: SuiteInput, fx: string): string[] { const ref = refs.get(op)!; const chain = plan?.chain; const body = plan?.updatePayload !== undefined && chain?.update === op ? `{ data: resource.newUpdatePayload() }` : undefined; - return [` const missingId = String(${s.notFound!.idExpr});`, ` const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param ?? s.notFound!.param, 'missingId'), body)};`]; + return [` const missingId = String(${s.notFound!.idExpr});`, ` const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param ?? s.notFound!.param, 'missingId'), optionsWith(op, body))};`]; } const anonymousCall = (s: SuiteInput) => { const ref = s.refs.get(s.op)!; - return ` const res = await ${apiCall(ref, 'publicApi', pathArgs(s.op, ref, s.plan?.chain.param, "'unused'"))};`; + return ` const res = await ${apiCall(ref, 'publicApi', pathArgs(s.op, ref, s.plan?.chain.param, "'unused'"), optionsWith(s.op))};`; }; const notFoundNeedsHelpers = (s: SuiteInput) => !!s.notFound && s.plan?.updatePayload !== undefined && s.plan.chain.update === s.op; @@ -359,7 +373,7 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { const params = { ...base, [variant.name]: variant.value }; L.push( ` test(${q(`accepts documented ${variant.name}=${String(variant.value)}`)}, ${testOptions('positive', s.ids?.functional.variants[n])}, async ({ ${fx} }) => {`, - ` const res = await ${apiCall(ref, fx, pathArgs(op, ref), `{ params: ${JSON.stringify(params)} }`)};`, + ` const res = await ${apiCall(ref, fx, pathArgs(op, ref), optionsWith(op, `{ params: ${JSON.stringify(params)} }`))};`, ` ${expectSuccess(op)}`, ` });`, '', @@ -388,7 +402,7 @@ export function renderContract(s: SuiteInput, meta: Meta): string { const ref = s.refs.get(op)!; const isCreate = chain?.create === op; const needsExisting = !!chain && chain.create !== op && op.params.some((p) => p.in === 'path' && p.name === chain.param); - const invalid = s.bodyCases.length + s.queryCases.length > 0; + const invalid = s.bodyCases.length + s.paramCases.length > 0; const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || (s.bodyCases.length > 0 && !!chain && (isCreate || needsExisting)); // Validation cases go through the same fixture as the positive test (anonymous for public operations). const fx = chain ? 'api' : apiFixture(op); @@ -403,7 +417,7 @@ export function renderContract(s: SuiteInput, meta: Meta): string { if (s.notFound) L.push(` test('response for a missing id matches the documented contract', ${testOptions('positive', s.ids?.contract.notFound)}, async ({ ${fx} }) => {`, ...notFoundCall(s, fx), ...contract(' '), ` });`, ''); if (s.unauthorized) L.push(` test('response without credentials matches the documented contract', ${testOptions('positive', s.ids?.contract.unauthorized)}, async ({ publicApi }) => {`, anonymousCall(s), ...contract(' '), ` });`, ''); - const send = (indent: string, options: string) => `${indent}const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param, 'id'), options)};`; + const send = (indent: string, options: string) => `${indent}const res = await ${apiCall(ref, fx, pathArgs(op, ref, chain?.param, 'id'), optionsWith(op, options))};`; if (s.bodyCases.length) { L.push(` const invalidBodies = [`); s.bodyCases.forEach((c, n) => L.push(` { title: ${q(c.title)}, source: ${q(c.source)}, ${caseField(s.ids?.contract.body[n])}data: ${JSON.stringify(c.data)} },`)); @@ -418,11 +432,20 @@ export function renderContract(s: SuiteInput, meta: Meta): string { } L.push(` });`, ` }`, ''); } - if (s.queryCases.length) { - L.push(` const invalidQueries = [`); - s.queryCases.forEach((c, n) => L.push(` { title: ${q(c.title)}, source: ${q(c.source)}, ${caseField(s.ids?.contract.query[n])}params: ${JSON.stringify(c.query)} },`)); - L.push(` ];`, '', ` for (const c of invalidQueries) {`, ` test(\`rejects invalid query: \${c.title}\`, ${loopOptions(s.ids?.contract.query)}, async ({ ${fx} }) => {`); - L.push(` const res = await ${apiCall(ref, fx, pathArgs(op, ref), '{ params: c.params }')};`, ` await expectRejected(res, rejection, '${op.method}', ${q(op.path)});`, ` });`, ` }`, ''); + if (s.paramCases.length) { + // Each row is a whole request: the valid required parameters plus the one parameter under test. + L.push(` const invalidParameters: { title: string; source: string; caseId?: string; params?: Record | string; headers?: Record; path?: Record }[] = [`); + s.paramCases.forEach((c, n) => { + const r: ParamRequest = c.request ?? (c.query ? { params: c.query as ParamRequest['params'] } : {}); + const fields = [r.params !== undefined ? `params: ${JSON.stringify(r.params)}` : '', r.headers ? `headers: ${JSON.stringify(r.headers)}` : '', r.path ? `path: ${JSON.stringify(r.path)}` : ''].filter(Boolean).join(', '); + L.push(` { title: ${q(c.title)}, source: ${q(c.source)}, ${caseField(s.ids?.contract.params[n])}${fields} },`); + }); + const args = ref.pathParams.map((name) => { + const known = op.params.find((x) => x.in === 'path' && x.name === name)?.knownValue; + return `c.path?.[${q(name)}] ?? ${known === undefined ? "'unused'" : q(String(known))}`; + }); + L.push(` ];`, '', ` for (const c of invalidParameters) {`, ` test(\`rejects invalid parameter: \${c.title}\`, ${loopOptions(s.ids?.contract.params)}, async ({ ${fx} }) => {`); + L.push(` const res = await ${apiCall(ref, fx, args, '{ params: c.params, headers: c.headers }')};`, ` await expectRejected(res, rejection, '${op.method}', ${q(op.path)});`, ` });`, ` }`, ''); } return close(L); } diff --git a/src/spec/catalog.ts b/src/spec/catalog.ts index 0bad6d7..c5979eb 100644 --- a/src/spec/catalog.ts +++ b/src/spec/catalog.ts @@ -47,6 +47,8 @@ export function buildCatalog(doc: OpenApiDoc): Operation[] { knownValue: knownValueWithSource(p, schema).value, knownSource: knownValueWithSource(p, schema).source, schema, + ...(p.style ? { style: p.style } : {}), + ...(typeof p.explode === 'boolean' ? { explode: p.explode } : {}), }; }); diff --git a/src/types.ts b/src/types.ts index 4c61bf8..8928673 100644 --- a/src/types.ts +++ b/src/types.ts @@ -15,6 +15,9 @@ export interface ParamInfo { /** Where knownValue came from: an illustrative example, or a value the schema defines (default/enum/const). */ knownSource?: 'example' | 'default' | 'enum' | 'const'; schema?: Record; + /** Serialization as documented (form, simple, spaceDelimited, โ€ฆ); defaults follow OpenAPI. */ + style?: string; + explode?: boolean; } export interface ResponseInfo { diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index ee02fbd..eea03cb 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "211c48082b5b8c39231e13220eef773881f49ea29dcc24370e20cfdb5ff743fb" + "sha256": "b25f9dfc2d7412b7a7a3ce73d2051f0336f68409ab4ac29faf5d97027fb02d35" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -161,7 +161,7 @@ "op_4PIO72ZI3SIY" ], "ownership": "generated", - "sha256": "19cb5063a2ea8c0448d9edb782404e52f9bc249144628963b1a3616ef388e402", + "sha256": "8f23c22db292e30e950f567f4c3a4f3a2264bb8acef45c9537d78a2d2d4bb236", "suiteType": "contract" }, "items/get/functional.spec.ts": { @@ -353,7 +353,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "ca2c522d318de340e5afdbb31c0fa0a6e85f91ff", + "revision": "93b4d144ee116dffa83c091e603b4c385ab916cb", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index fac70ce..e2638ac 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "ca2c522d318de340e5afdbb31c0fa0a6e85f91ff", + "capturedRevision": "93b4d144ee116dffa83c091e603b4c385ab916cb", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/api/items/get/contract.spec.ts b/tests/api/items/get/contract.spec.ts index 3928eee..85af71c 100644 --- a/tests/api/items/get/contract.spec.ts +++ b/tests/api/items/get/contract.spec.ts @@ -16,15 +16,15 @@ test.describe('GET /items ยท contract', { tag: '@contract' }, () => { await expectContract(res, 'get', '/items'); }); - const invalidQueries = [ - { title: 'query "limit" is not a number', source: 'query.limit.type', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:type', params: {"limit":"abc"} }, + const invalidParameters: { title: string; source: string; caseId?: string; params?: Record | string; headers?: Record; path?: Record }[] = [ + { title: 'query "limit" has wrong type (integer expected)', source: 'query.limit.type', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:type', params: {"limit":"not-a-number"} }, { title: 'query "limit" below minimum 1', source: 'query.limit.minimum', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:minimum', params: {"limit":0} }, { title: 'query "limit" above maximum 100', source: 'query.limit.maximum', caseId: 'ata:op_4PIO72ZI3SIY:contract:negative:request.query#/limit:maximum', params: {"limit":101} }, ]; - for (const c of invalidQueries) { - test(`rejects invalid query: ${c.title}`, { tag: '@negative', annotation: { type: 'caseId', description: c.caseId } }, async ({ publicApi }) => { - const res = await publicApi.items.listItems({ params: c.params }); + for (const c of invalidParameters) { + test(`rejects invalid parameter: ${c.title}`, { tag: '@negative', annotation: { type: 'caseId', description: c.caseId } }, async ({ publicApi }) => { + const res = await publicApi.items.listItems({ params: c.params, headers: c.headers }); await expectRejected(res, rejection, 'get', '/items'); }); } diff --git a/tests/fixtures/coverage/kitchen-sink.yaml b/tests/fixtures/coverage/kitchen-sink.yaml index bff4664..812ff23 100644 --- a/tests/fixtures/coverage/kitchen-sink.yaml +++ b/tests/fixtures/coverage/kitchen-sink.yaml @@ -13,7 +13,8 @@ paths: - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 50, multipleOf: 1 } } - { name: code, in: query, schema: { type: string, pattern: '^[A-Z]{3}$' } } - { name: since, in: query, schema: { type: string, format: date } } - - { name: tags, in: query, style: form, explode: false, schema: { type: array, items: { type: string }, maxItems: 3 } } + - { name: tags, in: query, style: form, explode: false, schema: { type: array, items: { type: string }, maxItems: 3, example: [a, b] } } + - { name: ids, in: query, schema: { type: array, items: { type: integer }, uniqueItems: true, example: [1, 2] } } - { name: X-Request-Id, in: header, required: true, schema: { type: string, format: uuid, example: 00000000-0000-4000-8000-000000000001 } } - { name: session, in: cookie, schema: { type: string, minLength: 8 } } responses: @@ -55,6 +56,7 @@ paths: content: application/json: schema: { $ref: '#/components/schemas/Order' } + '400': { description: invalid id } '404': { description: missing } delete: operationId: deleteOrder diff --git a/tests/unit/core.test.ts b/tests/unit/core.test.ts index b875555..542ff84 100644 --- a/tests/unit/core.test.ts +++ b/tests/unit/core.test.ts @@ -127,7 +127,8 @@ describe('safety helpers', () => { }); import { operationFolder } from '../../src/generate/templates.js'; -import { bodyCases, documentedRejections, queryCases } from '../../src/generate/negative.js'; +import { bodyCases, documentedRejections } from '../../src/generate/negative.js'; +import { paramCasesDetailed } from '../../src/generate/param-cases.js'; describe('test layout', () => { it('puts each operation in /[-by-id]', () => { @@ -150,7 +151,8 @@ describe('negative cases', () => { }); it('derives query cases from parameter bounds', () => { - expect(queryCases(op('GET /items')).map((c) => c.query)).toEqual([{ limit: 'abc' }, { limit: 0 }, { limit: 101 }]); + const r = paramCasesDetailed(demo.doc, op('GET /items'), { allowPath: true, allowOthers: true }); + expect(r.cases.map((c) => c.request?.params)).toEqual([{ limit: 'not-a-number' }, { limit: 0 }, { limit: 101 }]); }); it('breaks exclusive bounds, minItems and query minLength, one rule per case', () => { @@ -172,9 +174,9 @@ describe('negative cases', () => { { name: 'q', in: 'query', required: false, schema: { type: 'string', minLength: 3 } }, ], } as any; - const q = queryCases(search); - expect(q.find((c) => c.source === 'query.page.exclusiveMinimum')?.query).toEqual({ page: 0 }); - expect(q.find((c) => c.source === 'query.q.minLength')?.query).toEqual({ q: 'xx' }); + const q = paramCasesDetailed(demo.doc, search, { allowPath: true, allowOthers: true }).cases; + expect(q.find((c) => c.source === 'query.page.exclusiveMinimum')?.request?.params).toEqual({ page: 0 }); + expect(q.find((c) => c.source === 'query.q.minLength')?.request?.params).toEqual({ q: 'xx' }); }); it('only uses rejections the spec documents', () => { diff --git a/tests/unit/param-cases.test.ts b/tests/unit/param-cases.test.ts new file mode 100644 index 0000000..6333094 --- /dev/null +++ b/tests/unit/param-cases.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { Ajv2020 } from 'ajv/dist/2020.js'; +import * as addFormatsModule from 'ajv-formats'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { paramCasesDetailed, requiredRequest } from '../../src/generate/param-cases.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { operationUid } from '../../src/change/normalize.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { normalizeSpec } from '../../src/change/normalize.js'; +import type { ParamInfo } from '../../src/types.js'; + +/** Stage 4 (docs/SUPPORT_MATRIX.md): query, header, cookie and path parameter cases. */ + +const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; +const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); +const ops = buildCatalog(spec.doc); +const op = (key: string) => ops.find((o) => o.key === key)!; +const ajv = new Ajv2020({ allErrors: true, strict: false, coerceTypes: true }); +addFormats(ajv); + +/** The value each parameter has in a case's request (query object or string, headers, Cookie, path). */ +function valueOf(p: ParamInfo, req: { params?: any; headers?: Record; path?: Record }): unknown { + if (p.in === 'path') return req.path?.[p.name] ?? p.knownValue; + if (p.in === 'header') return Object.entries(req.headers ?? {}).find(([k]) => k.toLowerCase() === p.name.toLowerCase())?.[1]; + if (p.in === 'cookie') return (req.headers?.Cookie ?? '').split('; ').find((c) => c.startsWith(`${p.name}=`))?.slice(p.name.length + 1); + if (typeof req.params === 'string') { + const all = new URLSearchParams(req.params).getAll(p.name); + if (!all.length) return undefined; + // form + explode: false โ†’ one comma-separated value + return (p.schema as any)?.type === 'array' ? (p.explode === false ? all[0].split(',') : all) : all[0]; + } + const v = req.params?.[p.name]; + return (p.schema as any)?.type === 'array' && v !== undefined && !Array.isArray(v) ? [v] : v; +} +const valid = (p: ParamInfo, v: unknown) => (v === undefined ? !p.required : ajv.validate(p.schema ?? {}, Array.isArray(v) ? v.map((x) => (/^-?\d+$/.test(String(x)) ? Number(x) : x)) : /^-?\d+(\.\d+)?$/.test(String(v)) && ['integer', 'number'].includes((p.schema as any)?.type) ? Number(v) : v)); + +describe('stage 4: parameter cases', () => { + const list = op('GET /orders'); + const r = paramCasesDetailed(spec.doc, list, { allowPath: true, allowOthers: true }); + + it('every request is valid except the one parameter under test, which breaks its rule', () => { + expect(r.cases.length).toBeGreaterThan(10); + for (const c of r.cases) { + const t = c.target as { in: string; field: string; rule: string }; + for (const p of list.params) { + const v = valueOf(p, c.request!); + const isTarget = p.in === t.in && p.name === t.field; + if (isTarget) expect(valid(p, v), `${c.title}: ${p.name}=${JSON.stringify(v)} should break ${t.rule}`).toBe(false); + else expect(valid(p, v), `${c.title}: ${p.in} ${p.name}=${JSON.stringify(v)} should stay valid`).toBe(true); + } + } + }); + + it('covers query, header and cookie rules; arrays use the documented style', () => { + const got = new Set(r.cases.map((c) => `${(c.target as any).in}.${(c.target as any).field}:${c.target!.rule}`)); + for (const want of ['query.status:enum', 'query.limit:type', 'query.limit:minimum', 'query.limit:maximum', 'query.code:pattern', 'query.since:format', 'query.tags:maxItems', 'query.ids:uniqueItems', 'header.X-Request-Id:required', 'header.X-Request-Id:format', 'cookie.session:minLength']) { + expect(got, want).toContain(want); + } + const tags = r.cases.find((c) => c.source === 'query.tags.maxItems')!; + expect(tags.request!.params).toBe('tags=a,b,a,b'); // form, explode: false + const ids = r.cases.find((c) => c.source === 'query.ids.uniqueItems')!; + expect(ids.request!.params).toBe('ids=1&ids=1'); // form, explode: true (default) + expect(r.cases.find((c) => c.source === 'header.X-Request-Id.required')!.request!.headers).toBeUndefined(); + expect(r.cases.find((c) => c.source === 'cookie.session.minLength')!.request!.headers).toMatchObject({ Cookie: 'session=xxxxxxx' }); + }); + + it('every case carries the required header with its documented value, except the case that removes it', () => { + expect(requiredRequest(list).headers).toEqual({ 'X-Request-Id': '00000000-0000-4000-8000-000000000001' }); + for (const c of r.cases.filter((x) => x.source !== 'header.X-Request-Id.required' && !x.source.startsWith('header.'))) expect(c.request!.headers?.['X-Request-Id'], c.title).toBe('00000000-0000-4000-8000-000000000001'); + }); + + it('path parameters: invalid format only; an out-of-range id on a write operation is a gap, not a request', () => { + const get = paramCasesDetailed(spec.doc, op('GET /orders/{orderId}'), { allowPath: true, allowOthers: false }); + expect(get.cases.map((c) => [c.source, c.request!.path])).toEqual([['path.orderId.format', { orderId: 'not-a-uuid' }]]); + const numeric = { ...op('DELETE /orders/{orderId}'), params: [{ name: 'orderId', in: 'path', required: true, schema: { type: 'integer', minimum: 1, maximum: 999 }, knownValue: 5 }] } as any; + const del = paramCasesDetailed(spec.doc, numeric, { allowPath: true, allowOthers: true }); + expect(del.cases.map((c) => c.source)).toEqual(['path.orderId.type']); + expect(del.gaps.filter((g) => g.code === 'UNSAFE_LIVE_CHECK').map((g) => g.rule)).toEqual(['minimum', 'maximum']); + }); + + it('a required parameter without a documented value: no cases, a gap', () => { + const missing = { ...list, params: [...list.params, { name: 'tenant', in: 'header', required: true, schema: { type: 'string' } }] } as any; + const m = paramCasesDetailed(spec.doc, missing, { allowPath: true, allowOthers: true }); + expect(m.cases).toEqual([]); + expect(m.gaps).toEqual([expect.objectContaining({ code: 'MISSING_VALID_SAMPLE', location: 'request.header#/tenant' })]); + }); + + it('generated suites: TypeScript and Python carry the same parameter cases; positive calls send the required header', async () => { + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-pc-')); + await generate(spec, ops, { outDir: dir, version: 'test', lang }); + return { dir, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const uid = operationUid('GET', '/orders'); + for (const loc of ['request.header#/x-request-id:required', 'request.cookie#/session:minLength', 'request.query#/tags:maxItems']) expect(ts.reg.cases[`ata:${uid}:contract:negative:${loc}`], loc).toBeDefined(); + expect(ts.reg.cases[`ata:${operationUid('GET', '/orders/{}')}:contract:negative:request.path#/orderId:format`]).toBeDefined(); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + expect(validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('tests/fixtures/coverage/kitchen-sink.yaml', 'utf8'), 'ks')).errors).toEqual([]); + const tsList = await ts.read('orders/get/functional.spec.ts'); + expect(tsList).toContain(`headers: {"X-Request-Id":"00000000-0000-4000-8000-000000000001"}`); + const pyContract = await py.read('orders/get/test_contract.py'); + expect(pyContract).toContain('def test_rejects_invalid_parameter(api, contract, parts):'); + expect(await py.read('orders/get/test_functional.py')).toContain('headers={'); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', join(py.dir, 'orders/get/test_contract.py'), join(py.dir, 'orders/get_by_id/test_contract.py')], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); +}); From ea9aa19720af422a38924d9284f0e7190b6d5337 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:29:57 +0100 Subject: [PATCH 4/8] feat(coverage): stricter response contract, same rules in TS and Python (stage 5) validator.ts and contract.py: - response headers: required ones present, documented ones match their schema (numbers / booleans coerced, arrays comma-separated); - no body expected for 204 / 205 / 304, HEAD and responses without content: a body that arrives is "unexpected-body"; - an empty body where a schema is documented is "empty-body" (an undocumented Content-Type is reported first; JSON null is a body); - text media types with a schema are validated as strings; - writeOnly properties must not appear in a response and are never required in one; - what is not checked (no schema, unsupported media type) is a note: Playwright annotation contract-note, pytest warning. coverage-gaps.json lists MISSING_RESPONSE_SCHEMA and UNSUPPORTED_MEDIA_TYPE per response. tests/unit/validator.test.ts runs one table of 24 cases through both validators and requires identical results. Demo API: no new failures; only stats/get/contract fails. Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 26 +-- src/contract/contract.py | 154 +++++++++++++++--- src/contract/validator.ts | 141 +++++++++++++--- src/generate/generate.ts | 12 +- src/generate/templates.ts | 22 ++- tests/api/_support/contract-assert.ts | 22 ++- tests/api/_support/contract.ts | 141 +++++++++++++--- tests/api/_support/generation-manifest.json | 8 +- tests/api/_support/openapi.snapshot.meta.json | 2 +- tests/unit/validator.test.ts | 118 ++++++++++++++ 10 files changed, 552 insertions(+), 94 deletions(-) create mode 100644 tests/unit/validator.test.ts diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index ed12dcc..ceeab55 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -70,20 +70,26 @@ Every case is a valid request (each required query / header / cookie parameter w | optional-field variants | โŒ | | 7 | | response examples as requirements | โ›” | examples are illustrations unless marked | 7 | -## Response contract (`src/contract/validator.ts`) +## Response contract (`src/contract/validator.ts`, `src/contract/contract.py`) + +The TypeScript and Python validators apply the same rules; `tests/unit/validator.test.ts` runs one table of cases through both and requires identical results. | Check | State | Limits | Stage | |---|---|---|---| | status, `NXX` ranges, `default` | โœ… | | | -| Content-Type of the matched response | โœ… | | | -| JSON schema (3.0 nullable, 3.1 / 2020-12, formats via ajv-formats) | โœ… | | | -| local / bundled `$ref` | โœ… | snapshot is bundled | | -| non-JSON media types | ๐ŸŸก | body not checked; not reported as unchecked | 5 | -| response headers (required, schema) | โŒ | | 5 | -| no body for `204` / `205` / `HEAD` / no `content` | โŒ | an unexpected body is accepted | 5 | -| `readOnly` / `writeOnly` | โŒ | | 5 | -| `discriminator` | ๐ŸŸก | `oneOf` validated, mapping ignored | 5 | -| contract tests exercise | ๐ŸŸก | success, 404 and 401 responses only | 5 / 6 | +| Content-Type of the matched response, media type parameters ignored, `type/*` and `*/*` | โœ… | an undocumented type is reported before an empty body | 5 โœ” | +| JSON schema (3.0 nullable, 3.1 / 3.2 JSON Schema 2020-12, formats) | โœ… | | | +| local / bundled `$ref` | โœ… | the snapshot is bundled | | +| response headers | โœ… | required ones present; documented ones match their schema (integer / number / boolean coerced, arrays comma-separated, style simple); `Content-Type` ignored as OpenAPI says | 5 โœ” | +| no body for `204` / `205` / `304`, `HEAD`, responses without `content` | โœ… | a body that arrives anyway is `unexpected-body` | 5 โœ” | +| empty body where a schema is documented | โœ… | `empty-body` (JSON `null` is a body) | 5 โœ” | +| text media types with a schema | โœ… | the text is validated as a string | 5 โœ” | +| other media types (XML, binary, โ€ฆ) | โ›” | not checked: a note in the test report (Playwright annotation `contract-note`, pytest warning) and `UNSUPPORTED_MEDIA_TYPE` in `coverage-gaps.json` | 5 โœ” (gap) | +| a response without a schema | โ›” | not checked: note + `MISSING_RESPONSE_SCHEMA` | 5 โœ” (gap) | +| `writeOnly` | โœ… | must not appear in a response; never required in a response | 5 โœ” | +| `readOnly` | โœ… | not sent in request cases (stage 3) | 3 โœ” | +| `discriminator` | ๐ŸŸก | `oneOf` validated; the mapping is not used | | +| contract tests exercise | ๐ŸŸก | success, 404 and 401 responses; more in stage 6 | 6 | ## Documented error responses diff --git a/src/contract/contract.py b/src/contract/contract.py index 638d985..2b98c2d 100644 --- a/src/contract/contract.py +++ b/src/contract/contract.py @@ -9,10 +9,11 @@ import json import os import sys +import warnings from pathlib import Path from typing import Any -from jsonschema import Draft7Validator, Draft202012Validator, FormatChecker +from jsonschema import Draft7Validator, Draft202012Validator, FormatChecker, ValidationError, validators _UNPARSEABLE = object() @@ -83,29 +84,101 @@ def read_pointer(body: Any, pointer: str) -> Any: return node -def _body(res: Any) -> tuple[str | None, Any]: +def _body(res: Any) -> tuple[str | None, Any, str]: content_type = res.headers.get("content-type") + raw = res.text if res.content else "" if content_type and "json" in content_type: if not res.content: - return content_type, None + return content_type, None, raw try: - return content_type, res.json() + return content_type, res.json(), raw except ValueError: - return content_type, _UNPARSEABLE - return content_type, res.text + return content_type, _UNPARSEABLE, raw + return content_type, raw, raw + + +# Statuses that never carry a body (RFC 9110). +_NO_BODY_STATUS = {204, 205, 304} + + +def _drop_write_only_from_required(node: Any, seen: set | None = None) -> None: + """Responses only: a writeOnly property is never sent back, so it is never required in a response.""" + seen = seen if seen is not None else set() + if id(node) in seen: + return + if isinstance(node, list): + seen.add(id(node)) + for n in node: + _drop_write_only_from_required(n, seen) + return + if not isinstance(node, dict): + return + seen.add(id(node)) + props = node.get("properties") + if isinstance(node.get("required"), list) and isinstance(props, dict): + node["required"] = [n for n in node["required"] if not (isinstance(props.get(n), dict) and props[n].get("writeOnly") is True)] + for v in node.values(): + _drop_write_only_from_required(v, seen) + + +def _write_only(validator: Any, write_only: Any, instance: Any, schema: Any): + """writeOnly properties must not appear in a response.""" + if write_only is True: + yield ValidationError("is writeOnly and must not appear in a response") + + +def _header_value(schema: Any, value: str) -> Any: + """A header value as its schema expects it: numbers, booleans and comma-separated arrays (style: simple).""" + types = schema.get("type", []) if isinstance(schema, dict) else [] + types = types if isinstance(types, list) else [types] + + def scalar(v: str, t: list) -> Any: + if ("integer" in t or "number" in t) and v.strip(): + try: + n = float(v) + return int(n) if n.is_integer() and "integer" in t else n + except ValueError: + return v + if "boolean" in t and v in ("true", "false"): + return v == "true" + return v + + if "array" in types: + items = schema.get("items") or {} + it = items.get("type", []) if isinstance(items, dict) else [] + it = it if isinstance(it, list) else [it] + return [scalar(x.strip(), it) for x in value.split(",")] + return scalar(value, types) class ContractValidator: def __init__(self, doc: dict) -> None: self.is31 = str(doc.get("openapi", "")).startswith(("3.1", "3.2")) # both use JSON Schema 2020-12 self.doc = copy.deepcopy(doc) if self.is31 else _nullable(doc) + _drop_write_only_from_required(self.doc) + base = Draft202012Validator if self.is31 else Draft7Validator + self._cls = validators.extend(base, {"writeOnly": _write_only}) self._cache: dict[str, Any] = {} + self.notes: list[str] = [] + + def _validator(self, pointer: str) -> Any: + v = self._cache.get(pointer) + if v is None: + # The whole document is the root, so "#/components/..." refs resolve; "$ref" selects the schema. + v = self._cache[pointer] = self._cls({**self.doc, "$ref": "#" + pointer}, format_checker=FormatChecker()) + return v + + @staticmethod + def _messages(validator: Any, instance: Any, prefix: str = "") -> list[str]: + errors = sorted(validator.iter_errors(instance), key=lambda e: list(e.absolute_path)) + return [f"{prefix}/{'/'.join(str(p) for p in e.absolute_path) or '(root)'} {e.message}" for e in errors] @classmethod def from_file(cls, path: str | Path) -> "ContractValidator": return cls(json.loads(Path(path).read_text(encoding="utf-8"))) - def validate(self, method: str, path: str, status: int, content_type: str | None, body: Any) -> tuple[bool, str | None, list[str]]: + def validate(self, method: str, path: str, status: int, content_type: str | None, body: Any, raw_text: str | None = None, headers: Any = None) -> tuple[bool, str | None, list[str]]: + """Same rules as validator.ts. Notes on what was not checked go to self.notes.""" op_ptr = f"/paths/{_esc(path)}/{method.lower()}" responses, _ = _resolve(self.doc, f"{op_ptr}/responses") responses = responses or {} @@ -114,8 +187,37 @@ def validate(self, method: str, path: str, status: int, content_type: str | None if matched is None: return False, "undocumented-status", [f"Status {code} is not documented (documented: {', '.join(responses) or 'none'})"] resp, resp_ptr = _resolve(self.doc, f"{op_ptr}/responses/{_esc(matched)}") - content = (resp or {}).get("content") or {} - if not content: + resp = resp or {} + + # Response headers: required ones present, every documented one matching its schema. + got = {k.lower(): v for k, v in (headers or {}).items()} + header_errors: list[str] = [] + for name, raw_def in (resp.get("headers") or {}).items(): + if name.lower() == "content-type": + continue # OpenAPI: ignored, the media type decides + hdef, hptr = _resolve(self.doc, f"{resp_ptr}/headers/{_esc(name)}") + hdef = hdef or {} + value = got.get(name.lower()) + if value is None: + if hdef.get("required"): + header_errors.append(f'Required response header "{name}" is missing') + continue + if headers is None or not hdef.get("schema"): + continue + schema, _ = _resolve(self.doc, f"{hptr}/schema") + header_errors += self._messages(self._validator(f"{hptr}/schema"), _header_value(schema or {}, value), f'header "{name}" ') + if header_errors: + return False, "header", header_errors + + # Without the raw text, the parsed body stands for it (JSON null is the text "null", not an empty body). + raw = raw_text if raw_text is not None else ("" if body is _UNPARSEABLE else (body if isinstance(body, str) else json.dumps(body))) + content = resp.get("content") or {} + head = method.lower() == "head" + if not content or status in _NO_BODY_STATUS or head: + # No body is documented (or the status / method has none): one that arrives anyway breaks the contract. + if raw.strip() and not head: + why = f"status {code} has no body" if status in _NO_BODY_STATUS else f"no content is documented for {matched}" + return False, "unexpected-body", [f"A body was returned but {why} ({len(raw)} bytes)"] return True, None, [] actual = (content_type or "").split(";")[0].strip().lower() # Compare without parameters: "application/json; v=1.0" documents "application/json". @@ -124,27 +226,35 @@ def validate(self, method: str, path: str, status: int, content_type: str | None if media is None: kind = actual.split("/")[0] media = next((k for k in content if base(k) == f"{kind}/*"), None) or next((k for k in content if base(k) == "*/*"), None) + # A declared but undocumented Content-Type is the more precise problem; an empty body comes next. + if not raw.strip() and (not actual or media is not None): + if any((m or {}).get("schema") for m in content.values()): + return False, "empty-body", [f"The body is empty but {matched} documents {', '.join(content)}"] + return True, None, [] if media is None: return False, "content-type", [f'Content-Type "{actual or "none"}" is not documented for {matched} (documented: {", ".join(content)})'] - if "json" not in media or not (content.get(media) or {}).get("schema"): + schema_ptr = f"{resp_ptr}/content/{_esc(media)}/schema" + if not (content.get(media) or {}).get("schema"): + self.notes.append(f"{matched} {media}: no schema documented, body not checked") + return True, None, [] + if base(media).startswith("text/"): + msgs = self._messages(self._validator(schema_ptr), raw) + return not msgs, ("schema" if msgs else None), msgs + if "json" not in base(media): + self.notes.append(f"{matched} {media}: media type not supported by the validator, body not checked") return True, None, [] if body is _UNPARSEABLE: return False, "unparseable-body", ["Body is not valid JSON"] - schema_ptr = f"{resp_ptr}/content/{_esc(media)}/schema" - validator = self._cache.get(schema_ptr) - if validator is None: - # The whole document is the root, so "#/components/..." refs resolve; "$ref" selects the response schema. - root = {**self.doc, "$ref": "#" + schema_ptr} - cls = Draft202012Validator if self.is31 else Draft7Validator - validator = self._cache[schema_ptr] = cls(root, format_checker=FormatChecker()) - errors = sorted(validator.iter_errors(body), key=lambda e: list(e.absolute_path)) - msgs = [f"/{'/'.join(str(p) for p in e.absolute_path) or '(root)'} {e.message}" for e in errors] + msgs = self._messages(self._validator(schema_ptr), body) return not msgs, ("schema" if msgs else None), msgs def expect(self, res: Any, method: str, path: str) -> Any: - """Status, content type and body must match the spec. Failures are tagged CONTRACT_MISMATCH.""" - content_type, body = _body(res) - ok, kind, errors = self.validate(method, path, res.status_code, content_type, body) + """Status, headers, content type and body must match the spec. Failures are tagged CONTRACT_MISMATCH.""" + content_type, body, raw = _body(res) + self.notes = [] + ok, kind, errors = self.validate(method, path, res.status_code, content_type, body, raw, dict(res.headers)) + for note in self.notes: + warnings.warn(f"contract note: {note}", stacklevel=2) assert ok, f"CONTRACT_MISMATCH {method.upper()} {path} ({kind}): {'; '.join(errors)}" return None if body is _UNPARSEABLE else body diff --git a/src/contract/validator.ts b/src/contract/validator.ts index c74357c..9d5da94 100644 --- a/src/contract/validator.ts +++ b/src/contract/validator.ts @@ -4,6 +4,7 @@ * This file is deliberately self-contained (no imports from the agent): `generate` * copies it verbatim into tests/generated/_support/ so generated tests run without * the agent installed. Keep it dependency-light: ajv + ajv-formats only. + * src/contract/contract.py is its Python twin: keep the rules identical. */ import { Ajv, type ValidateFunction } from 'ajv'; import { Ajv2020 } from 'ajv/dist/2020.js'; @@ -11,7 +12,7 @@ import addFormatsModule from 'ajv-formats'; const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; -export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body'; +export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body' | 'empty-body' | 'unexpected-body' | 'header'; export interface ContractResult { ok: boolean; @@ -20,9 +21,26 @@ export interface ContractResult { kind?: ContractProblemKind; errors: string[]; matchedStatus?: string; + /** What was not checked and why (e.g. a media type without a supported schema). Never a failure. */ + notes?: string[]; +} + +export interface ResponseInput { + method: string; + path: string; + status: number; + contentType?: string | null; + /** Parsed JSON for JSON media types, the text otherwise; undefined when JSON could not be parsed. */ + body: unknown; + /** The raw response text: decides "empty" and "unexpected body". */ + rawText?: string; + /** Response headers (any case). */ + headers?: Record; } const DOC_ID = 'openapi.json'; +/** Statuses that never carry a body (RFC 9110). */ +const NO_BODY_STATUS = new Set([204, 205, 304]); export class ContractValidator { private readonly ajv: Ajv; @@ -31,14 +49,33 @@ export class ContractValidator { constructor(doc: any) { const is31 = /^3\.[12]\./.test(String(doc.openapi ?? '')); // 3.1 and 3.2: JSON Schema 2020-12 - this.doc = is31 ? structuredClone(doc) : nullableToJsonSchema(structuredClone(doc)); + const copy = structuredClone(doc); + // Responses only: a writeOnly property is never sent back, so it is never required in a response. + dropWriteOnlyFromRequired(copy); + this.doc = is31 ? copy : nullableToJsonSchema(copy); const opts = { strict: false, allErrors: true, validateSchema: false } as const; this.ajv = (is31 ? new Ajv2020(opts) : new Ajv(opts)) as Ajv; addFormats(this.ajv); + // writeOnly properties must not appear in a response. + this.ajv.removeKeyword('writeOnly'); // ajv knows it as an annotation; redefine it as a check + this.ajv.addKeyword({ keyword: 'writeOnly', schemaType: 'boolean', validate: (writeOnly: boolean) => !writeOnly, errors: false }); this.ajv.addSchema(this.doc, DOC_ID); } - validateResponse(input: { method: string; path: string; status: number; contentType?: string | null; body: unknown }): ContractResult { + private compile(pointer: string): ValidateFunction { + let validate = this.cache.get(pointer); + if (!validate) { + validate = this.ajv.compile({ $ref: `${DOC_ID}#${pointer}` }); + this.cache.set(pointer, validate); + } + return validate; + } + + private messages(validate: ValidateFunction, prefix = ''): string[] { + return (validate.errors ?? []).map((e) => `${prefix}${e.instancePath || '(root)'} ${e.keyword === 'writeOnly' ? 'is writeOnly and must not appear in a response' : e.message}`); + } + + validateResponse(input: ResponseInput): ContractResult { const opPtr = `/paths/${esc(input.path)}/${input.method.toLowerCase()}`; const responses = resolve(this.doc, `${opPtr}/responses`).node ?? {}; const code = String(input.status); @@ -52,11 +89,33 @@ export class ContractValidator { }; } const resp = resolve(this.doc, `${opPtr}/responses/${esc(matched)}`); + const notes: string[] = []; + + // Response headers: required ones present, every documented one matching its schema. + const headerErrors = this.checkHeaders(resp.node?.headers ?? {}, `${resp.pointer}/headers`, input.headers); + if (headerErrors.length) return { ok: false, bodyChecked: false, kind: 'header', matchedStatus: matched, errors: headerErrors }; + + // Without the raw text, the parsed body stands for it (JSON null is the text "null", not an empty body). + const raw = input.rawText ?? (typeof input.body === 'string' ? input.body : input.body === undefined ? '' : JSON.stringify(input.body)); const content = resp.node?.content; - if (!content || !Object.keys(content).length) return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const head = input.method.toLowerCase() === 'head'; + if (!content || !Object.keys(content).length || NO_BODY_STATUS.has(input.status) || head) { + // No body is documented (or the status / method has none): one that arrives anyway breaks the contract. + if (raw.trim().length && !head) { + const why = NO_BODY_STATUS.has(input.status) ? `status ${code} has no body` : `no content is documented for ${matched}`; + return { ok: false, bodyChecked: true, kind: 'unexpected-body', matchedStatus: matched, errors: [`A body was returned but ${why} (${raw.length} bytes)`] }; + } + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, ...(notes.length ? { notes } : {}) }; + } const actual = (input.contentType ?? '').split(';')[0].trim().toLowerCase(); const mediaKey = pickMedia(Object.keys(content), actual); + // A declared but undocumented Content-Type is the more precise problem; an empty body comes next. + if (!raw.trim().length && (!actual || mediaKey)) { + const hasSchema = Object.values(content).some((m) => m?.schema); + if (hasSchema) return { ok: false, bodyChecked: true, kind: 'empty-body', matchedStatus: matched, errors: [`The body is empty but ${matched} documents ${Object.keys(content).join(', ')}`] }; + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + } if (!mediaKey) { return { ok: false, @@ -66,28 +125,72 @@ export class ContractValidator { errors: [`Content-Type "${actual || 'none'}" is not documented for ${matched} (documented: ${Object.keys(content).join(', ')})`], }; } - if (!content[mediaKey]?.schema || !mediaKey.includes('json')) { - return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; + if (!content[mediaKey]?.schema) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: no schema documented, body not checked`] }; + } + if (baseMedia(mediaKey).startsWith('text/')) { + // Text bodies with a schema: the text is the (string) instance. + const validate = this.compile(schemaPtr); + const ok = validate(raw) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } + if (!baseMedia(mediaKey).includes('json')) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: media type not supported by the validator, body not checked`] }; } if (input.body === undefined) { return { ok: false, bodyChecked: true, kind: 'unparseable-body', matchedStatus: matched, errors: ['Body is not valid JSON'] }; } + const validate = this.compile(schemaPtr); + const ok = validate(input.body) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } - const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; - let validate = this.cache.get(schemaPtr); - if (!validate) { - validate = this.ajv.compile({ $ref: `${DOC_ID}#${schemaPtr}` }); - this.cache.set(schemaPtr, validate); + private checkHeaders(defs: Record, pointer: string, actual?: Record): string[] { + const errors: string[] = []; + const got = Object.fromEntries(Object.entries(actual ?? {}).map(([k, v]) => [k.toLowerCase(), v])); + for (const [name, raw] of Object.entries(defs)) { + if (name.toLowerCase() === 'content-type') continue; // OpenAPI: ignored, the media type decides + const def = raw?.$ref ? resolve(this.doc, raw.$ref.slice(1)).node : raw; + const value = got[name.toLowerCase()]; + if (value === undefined) { + if (def?.required) errors.push(`Required response header "${name}" is missing`); + continue; + } + if (!def?.schema || actual === undefined) continue; + const validate = this.compile(`${pointer}/${esc(name)}/schema`); + if (!(validate(headerValue(def.schema, value, this.doc)) as boolean)) errors.push(...this.messages(validate, `header "${name}" `)); } - const ok = validate(input.body) as boolean; - return { - ok, - bodyChecked: true, - kind: ok ? undefined : 'schema', - matchedStatus: matched, - errors: ok ? [] : (validate.errors ?? []).map((e) => `${e.instancePath || '(root)'} ${e.message}`), - }; + return errors; + } +} + +/** A header value as its schema expects it: numbers, booleans and comma-separated arrays (style: simple). */ +function headerValue(schemaRaw: any, value: string, doc: any): unknown { + const schema = schemaRaw?.$ref ? resolve(doc, schemaRaw.$ref.slice(1)).node : schemaRaw; + const types: string[] = schema?.type === undefined ? [] : Array.isArray(schema.type) ? schema.type : [schema.type]; + const scalar = (v: string, t: string[]) => { + if ((t.includes('integer') || t.includes('number')) && v.trim() !== '' && !Number.isNaN(Number(v))) return Number(v); + if (t.includes('boolean') && (v === 'true' || v === 'false')) return v === 'true'; + return v; + }; + if (types.includes('array')) { + const items = schema.items?.$ref ? resolve(doc, schema.items.$ref.slice(1)).node : schema.items; + const it: string[] = items?.type === undefined ? [] : Array.isArray(items.type) ? items.type : [items.type]; + return value.split(',').map((v) => scalar(v.trim(), it)); + } + return scalar(value, types); +} + +/** Removes writeOnly properties from every `required` list (they are never part of a response). */ +function dropWriteOnlyFromRequired(node: any, seen = new Set()): void { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node)) return node.forEach((n) => dropWriteOnlyFromRequired(n, seen)); + if (Array.isArray(node.required) && node.properties && typeof node.properties === 'object') { + node.required = node.required.filter((name: string) => node.properties[name]?.writeOnly !== true); } + for (const v of Object.values(node)) dropWriteOnlyFromRequired(v, seen); } /** Media types are compared without parameters: "application/json; v=1.0" documents "application/json". */ diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 9da86d4..60880cf 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -317,7 +317,17 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. - coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: bodyGaps, ...(bodyStats ? { bodyCases: bodyStats } : {}) }); + // Response bodies the validator cannot check: said explicitly, never passed silently. + const responseGaps: CoverageGap[] = op.responses.flatMap((resp) => + resp.contentTypes.flatMap((ct): CoverageGap[] => { + const media = ct.split(';')[0].trim().toLowerCase(); + const loc = `response.content-type#/${media.replace(/~/g, '~0').replace(/\//g, '~1')}`; + if (!resp.hasSchema) return [{ code: 'MISSING_RESPONSE_SCHEMA', location: loc, reason: `${resp.status} ${media}: no schema documented, the body is not checked` }]; + if (!media.includes('json') && !media.startsWith('text/')) return [{ code: 'UNSUPPORTED_MEDIA_TYPE', location: loc, reason: `${resp.status} ${media}: the validator checks JSON and text bodies only` }]; + return []; + }), + ); + coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: [...bodyGaps, ...responseGaps], ...(bodyStats ? { bodyCases: bodyStats } : {}) }); const render: Record string> = py ? { functional: renderPyFunctional, contract: renderPyContract, scenario: renderPyScenarios } : { functional: renderFunctional, contract: renderContract, scenario: renderScenarios }; diff --git a/src/generate/templates.ts b/src/generate/templates.ts index c675a24..fa4b6b6 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -528,7 +528,7 @@ function close(L: string[]): string { export const CONTRACT_ASSERT = `// Generated by api-test-agent. Bridges Playwright responses to the OpenAPI contract. import { appendFileSync } from 'node:fs'; -import { expect, type APIResponse } from '@playwright/test'; +import { expect, test, type APIResponse } from '@playwright/test'; import { ContractValidator } from './contract.js'; import { spec } from './openapi.snapshot.js'; @@ -544,24 +544,28 @@ export function reportCleanupFailure(operation: string, id: string, status: numb else console.warn(\`cleanup failed: \${operation} \${id} โ†’ \${status} (test data left on the target)\`); } -async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown }> { +async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown; rawText: string }> { const contentType = res.headers()['content-type'] ?? null; - const text = await res.text(); - let body: unknown = text; + const rawText = await res.text(); + let body: unknown = rawText; if (contentType?.includes('json')) { try { - body = text.length ? JSON.parse(text) : null; + body = rawText.length ? JSON.parse(rawText) : null; } catch { body = undefined; } } - return { contentType, body }; + return { contentType, body, rawText }; } -/** Validates status, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. */ +/** + * Validates status, headers, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. + * What could not be checked (e.g. a media type without a schema) is added to the test report as a note. + */ export async function expectContract(res: APIResponse, method: string, path: string): Promise { - const { contentType, body } = await readBody(res); - const r = validator.validateResponse({ method, path, status: res.status(), contentType, body }); + const { contentType, body, rawText } = await readBody(res); + const r = validator.validateResponse({ method, path, status: res.status(), contentType, body, rawText, headers: res.headers() }); + for (const note of r.notes ?? []) test.info().annotations.push({ type: 'contract-note', description: note }); expect(r.ok, \`CONTRACT_MISMATCH \${method.toUpperCase()} \${path} (\${r.kind}): \${r.errors.join('; ')}\`).toBe(true); return body; } diff --git a/tests/api/_support/contract-assert.ts b/tests/api/_support/contract-assert.ts index 0e4122a..d935a82 100644 --- a/tests/api/_support/contract-assert.ts +++ b/tests/api/_support/contract-assert.ts @@ -1,6 +1,6 @@ // Generated by api-test-agent. Bridges Playwright responses to the OpenAPI contract. import { appendFileSync } from 'node:fs'; -import { expect, type APIResponse } from '@playwright/test'; +import { expect, test, type APIResponse } from '@playwright/test'; import { ContractValidator } from './contract.js'; import { spec } from './openapi.snapshot.js'; @@ -16,24 +16,28 @@ export function reportCleanupFailure(operation: string, id: string, status: numb else console.warn(`cleanup failed: ${operation} ${id} โ†’ ${status} (test data left on the target)`); } -async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown }> { +async function readBody(res: APIResponse): Promise<{ contentType: string | null; body: unknown; rawText: string }> { const contentType = res.headers()['content-type'] ?? null; - const text = await res.text(); - let body: unknown = text; + const rawText = await res.text(); + let body: unknown = rawText; if (contentType?.includes('json')) { try { - body = text.length ? JSON.parse(text) : null; + body = rawText.length ? JSON.parse(rawText) : null; } catch { body = undefined; } } - return { contentType, body }; + return { contentType, body, rawText }; } -/** Validates status, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. */ +/** + * Validates status, headers, content type and body against the spec. Failures are tagged CONTRACT_MISMATCH. + * What could not be checked (e.g. a media type without a schema) is added to the test report as a note. + */ export async function expectContract(res: APIResponse, method: string, path: string): Promise { - const { contentType, body } = await readBody(res); - const r = validator.validateResponse({ method, path, status: res.status(), contentType, body }); + const { contentType, body, rawText } = await readBody(res); + const r = validator.validateResponse({ method, path, status: res.status(), contentType, body, rawText, headers: res.headers() }); + for (const note of r.notes ?? []) test.info().annotations.push({ type: 'contract-note', description: note }); expect(r.ok, `CONTRACT_MISMATCH ${method.toUpperCase()} ${path} (${r.kind}): ${r.errors.join('; ')}`).toBe(true); return body; } diff --git a/tests/api/_support/contract.ts b/tests/api/_support/contract.ts index c74357c..9d5da94 100644 --- a/tests/api/_support/contract.ts +++ b/tests/api/_support/contract.ts @@ -4,6 +4,7 @@ * This file is deliberately self-contained (no imports from the agent): `generate` * copies it verbatim into tests/generated/_support/ so generated tests run without * the agent installed. Keep it dependency-light: ajv + ajv-formats only. + * src/contract/contract.py is its Python twin: keep the rules identical. */ import { Ajv, type ValidateFunction } from 'ajv'; import { Ajv2020 } from 'ajv/dist/2020.js'; @@ -11,7 +12,7 @@ import addFormatsModule from 'ajv-formats'; const addFormats = ((addFormatsModule as any).default ?? addFormatsModule) as (ajv: any) => void; -export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body'; +export type ContractProblemKind = 'undocumented-status' | 'content-type' | 'schema' | 'unparseable-body' | 'empty-body' | 'unexpected-body' | 'header'; export interface ContractResult { ok: boolean; @@ -20,9 +21,26 @@ export interface ContractResult { kind?: ContractProblemKind; errors: string[]; matchedStatus?: string; + /** What was not checked and why (e.g. a media type without a supported schema). Never a failure. */ + notes?: string[]; +} + +export interface ResponseInput { + method: string; + path: string; + status: number; + contentType?: string | null; + /** Parsed JSON for JSON media types, the text otherwise; undefined when JSON could not be parsed. */ + body: unknown; + /** The raw response text: decides "empty" and "unexpected body". */ + rawText?: string; + /** Response headers (any case). */ + headers?: Record; } const DOC_ID = 'openapi.json'; +/** Statuses that never carry a body (RFC 9110). */ +const NO_BODY_STATUS = new Set([204, 205, 304]); export class ContractValidator { private readonly ajv: Ajv; @@ -31,14 +49,33 @@ export class ContractValidator { constructor(doc: any) { const is31 = /^3\.[12]\./.test(String(doc.openapi ?? '')); // 3.1 and 3.2: JSON Schema 2020-12 - this.doc = is31 ? structuredClone(doc) : nullableToJsonSchema(structuredClone(doc)); + const copy = structuredClone(doc); + // Responses only: a writeOnly property is never sent back, so it is never required in a response. + dropWriteOnlyFromRequired(copy); + this.doc = is31 ? copy : nullableToJsonSchema(copy); const opts = { strict: false, allErrors: true, validateSchema: false } as const; this.ajv = (is31 ? new Ajv2020(opts) : new Ajv(opts)) as Ajv; addFormats(this.ajv); + // writeOnly properties must not appear in a response. + this.ajv.removeKeyword('writeOnly'); // ajv knows it as an annotation; redefine it as a check + this.ajv.addKeyword({ keyword: 'writeOnly', schemaType: 'boolean', validate: (writeOnly: boolean) => !writeOnly, errors: false }); this.ajv.addSchema(this.doc, DOC_ID); } - validateResponse(input: { method: string; path: string; status: number; contentType?: string | null; body: unknown }): ContractResult { + private compile(pointer: string): ValidateFunction { + let validate = this.cache.get(pointer); + if (!validate) { + validate = this.ajv.compile({ $ref: `${DOC_ID}#${pointer}` }); + this.cache.set(pointer, validate); + } + return validate; + } + + private messages(validate: ValidateFunction, prefix = ''): string[] { + return (validate.errors ?? []).map((e) => `${prefix}${e.instancePath || '(root)'} ${e.keyword === 'writeOnly' ? 'is writeOnly and must not appear in a response' : e.message}`); + } + + validateResponse(input: ResponseInput): ContractResult { const opPtr = `/paths/${esc(input.path)}/${input.method.toLowerCase()}`; const responses = resolve(this.doc, `${opPtr}/responses`).node ?? {}; const code = String(input.status); @@ -52,11 +89,33 @@ export class ContractValidator { }; } const resp = resolve(this.doc, `${opPtr}/responses/${esc(matched)}`); + const notes: string[] = []; + + // Response headers: required ones present, every documented one matching its schema. + const headerErrors = this.checkHeaders(resp.node?.headers ?? {}, `${resp.pointer}/headers`, input.headers); + if (headerErrors.length) return { ok: false, bodyChecked: false, kind: 'header', matchedStatus: matched, errors: headerErrors }; + + // Without the raw text, the parsed body stands for it (JSON null is the text "null", not an empty body). + const raw = input.rawText ?? (typeof input.body === 'string' ? input.body : input.body === undefined ? '' : JSON.stringify(input.body)); const content = resp.node?.content; - if (!content || !Object.keys(content).length) return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const head = input.method.toLowerCase() === 'head'; + if (!content || !Object.keys(content).length || NO_BODY_STATUS.has(input.status) || head) { + // No body is documented (or the status / method has none): one that arrives anyway breaks the contract. + if (raw.trim().length && !head) { + const why = NO_BODY_STATUS.has(input.status) ? `status ${code} has no body` : `no content is documented for ${matched}`; + return { ok: false, bodyChecked: true, kind: 'unexpected-body', matchedStatus: matched, errors: [`A body was returned but ${why} (${raw.length} bytes)`] }; + } + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, ...(notes.length ? { notes } : {}) }; + } const actual = (input.contentType ?? '').split(';')[0].trim().toLowerCase(); const mediaKey = pickMedia(Object.keys(content), actual); + // A declared but undocumented Content-Type is the more precise problem; an empty body comes next. + if (!raw.trim().length && (!actual || mediaKey)) { + const hasSchema = Object.values(content).some((m) => m?.schema); + if (hasSchema) return { ok: false, bodyChecked: true, kind: 'empty-body', matchedStatus: matched, errors: [`The body is empty but ${matched} documents ${Object.keys(content).join(', ')}`] }; + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + } if (!mediaKey) { return { ok: false, @@ -66,28 +125,72 @@ export class ContractValidator { errors: [`Content-Type "${actual || 'none'}" is not documented for ${matched} (documented: ${Object.keys(content).join(', ')})`], }; } - if (!content[mediaKey]?.schema || !mediaKey.includes('json')) { - return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched }; + const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; + if (!content[mediaKey]?.schema) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: no schema documented, body not checked`] }; + } + if (baseMedia(mediaKey).startsWith('text/')) { + // Text bodies with a schema: the text is the (string) instance. + const validate = this.compile(schemaPtr); + const ok = validate(raw) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } + if (!baseMedia(mediaKey).includes('json')) { + return { ok: true, bodyChecked: false, errors: [], matchedStatus: matched, notes: [`${matched} ${mediaKey}: media type not supported by the validator, body not checked`] }; } if (input.body === undefined) { return { ok: false, bodyChecked: true, kind: 'unparseable-body', matchedStatus: matched, errors: ['Body is not valid JSON'] }; } + const validate = this.compile(schemaPtr); + const ok = validate(input.body) as boolean; + return { ok, bodyChecked: true, kind: ok ? undefined : 'schema', matchedStatus: matched, errors: ok ? [] : this.messages(validate) }; + } - const schemaPtr = `${resp.pointer}/content/${esc(mediaKey)}/schema`; - let validate = this.cache.get(schemaPtr); - if (!validate) { - validate = this.ajv.compile({ $ref: `${DOC_ID}#${schemaPtr}` }); - this.cache.set(schemaPtr, validate); + private checkHeaders(defs: Record, pointer: string, actual?: Record): string[] { + const errors: string[] = []; + const got = Object.fromEntries(Object.entries(actual ?? {}).map(([k, v]) => [k.toLowerCase(), v])); + for (const [name, raw] of Object.entries(defs)) { + if (name.toLowerCase() === 'content-type') continue; // OpenAPI: ignored, the media type decides + const def = raw?.$ref ? resolve(this.doc, raw.$ref.slice(1)).node : raw; + const value = got[name.toLowerCase()]; + if (value === undefined) { + if (def?.required) errors.push(`Required response header "${name}" is missing`); + continue; + } + if (!def?.schema || actual === undefined) continue; + const validate = this.compile(`${pointer}/${esc(name)}/schema`); + if (!(validate(headerValue(def.schema, value, this.doc)) as boolean)) errors.push(...this.messages(validate, `header "${name}" `)); } - const ok = validate(input.body) as boolean; - return { - ok, - bodyChecked: true, - kind: ok ? undefined : 'schema', - matchedStatus: matched, - errors: ok ? [] : (validate.errors ?? []).map((e) => `${e.instancePath || '(root)'} ${e.message}`), - }; + return errors; + } +} + +/** A header value as its schema expects it: numbers, booleans and comma-separated arrays (style: simple). */ +function headerValue(schemaRaw: any, value: string, doc: any): unknown { + const schema = schemaRaw?.$ref ? resolve(doc, schemaRaw.$ref.slice(1)).node : schemaRaw; + const types: string[] = schema?.type === undefined ? [] : Array.isArray(schema.type) ? schema.type : [schema.type]; + const scalar = (v: string, t: string[]) => { + if ((t.includes('integer') || t.includes('number')) && v.trim() !== '' && !Number.isNaN(Number(v))) return Number(v); + if (t.includes('boolean') && (v === 'true' || v === 'false')) return v === 'true'; + return v; + }; + if (types.includes('array')) { + const items = schema.items?.$ref ? resolve(doc, schema.items.$ref.slice(1)).node : schema.items; + const it: string[] = items?.type === undefined ? [] : Array.isArray(items.type) ? items.type : [items.type]; + return value.split(',').map((v) => scalar(v.trim(), it)); + } + return scalar(value, types); +} + +/** Removes writeOnly properties from every `required` list (they are never part of a response). */ +function dropWriteOnlyFromRequired(node: any, seen = new Set()): void { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node)) return node.forEach((n) => dropWriteOnlyFromRequired(n, seen)); + if (Array.isArray(node.required) && node.properties && typeof node.properties === 'object') { + node.required = node.required.filter((name: string) => node.properties[name]?.writeOnly !== true); } + for (const v of Object.values(node)) dropWriteOnlyFromRequired(v, seen); } /** Media types are compared without parameters: "application/json; v=1.0" documents "application/json". */ diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index eea03cb..e93ee40 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -39,11 +39,11 @@ }, "_support/contract-assert.ts": { "ownership": "generated", - "sha256": "fbbd168c9255903b3c1499dd88f007806846b2e14e3c42e7b01e17361ba60d78" + "sha256": "78f7d10c5e3b5e16fc2589da1beaec473034391b3fca2ab20254b6992245729a" }, "_support/contract.ts": { "ownership": "generated", - "sha256": "8593fa68484c84f12c84803c30ef474dc1718750ef102647014c7e99e0b166aa" + "sha256": "e3984cc678d6fa6afb72a849e65f103f1b7c42a6dcedcf2074719396714ae7a7" }, "_support/fixtures.ts": { "ownership": "generated", @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "b25f9dfc2d7412b7a7a3ce73d2051f0336f68409ab4ac29faf5d97027fb02d35" + "sha256": "da2e6eb7ce782763af79669ad4f51564631e99a56233733d3b52e5ed6a69314c" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -353,7 +353,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "93b4d144ee116dffa83c091e603b4c385ab916cb", + "revision": "9142b4bfc92cba8ebcfaecd302af395090aac8c6", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index e2638ac..7f60940 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "93b4d144ee116dffa83c091e603b4c385ab916cb", + "capturedRevision": "9142b4bfc92cba8ebcfaecd302af395090aac8c6", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/unit/validator.test.ts b/tests/unit/validator.test.ts new file mode 100644 index 0000000..e580388 --- /dev/null +++ b/tests/unit/validator.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { ContractValidator, type ResponseInput } from '../../src/contract/validator.js'; +import { findPython } from '../../src/generate/generate.js'; + +/** Stage 5 (docs/SUPPORT_MATRIX.md): response contract rules, identical in validator.ts and contract.py. */ + +const doc = { + openapi: '3.1.0', + info: { title: 'v', version: '1' }, + paths: { + '/users': { + get: { + responses: { + '200': { + description: 'ok', + headers: { + 'X-Total-Count': { required: true, schema: { type: 'integer', minimum: 0 } }, + 'X-Flags': { schema: { type: 'array', items: { type: 'boolean' } } }, + 'Content-Type': { required: true, schema: { type: 'string' } }, + }, + content: { 'application/json': { schema: { $ref: '#/components/schemas/User' } } }, + }, + default: { description: 'error', content: { 'application/json': { schema: { type: 'object', required: ['message'], properties: { message: { type: 'string' } } } } } }, + }, + }, + delete: { responses: { '204': { description: 'gone' }, '4XX': { description: 'client error' } } }, + head: { responses: { '200': { description: 'ok', content: { 'application/json': { schema: { type: 'object' } } } } } }, + }, + '/text': { get: { responses: { '200': { description: 'ok', content: { 'text/plain': { schema: { type: 'string', pattern: '^OK' } } } } } } }, + '/xml': { get: { responses: { '200': { description: 'ok', content: { 'application/xml': { schema: { type: 'object' } } } } } } }, + '/free': { get: { responses: { '200': { description: 'ok', content: { 'application/json': {} } } } } }, + }, + components: { + schemas: { + User: { + type: 'object', + required: ['id', 'password'], + properties: { id: { type: 'string', format: 'uuid' }, password: { type: 'string', writeOnly: true }, nickname: { type: ['string', 'null'] } }, + }, + }, + }, +}; + +const user = { id: '00000000-0000-4000-8000-000000000001', nickname: null }; +const json = (body: unknown) => ({ contentType: 'application/json', body, rawText: JSON.stringify(body) }); +const okHeaders = { 'x-total-count': '3', 'content-type': 'application/json' }; + +/** [name, input, expected ok, expected kind] */ +const CASES: [string, ResponseInput, boolean, string | undefined][] = [ + ['valid body and headers', { method: 'get', path: '/users', status: 200, ...json(user), headers: okHeaders }, true, undefined], + ['writeOnly property not required in a response', { method: 'get', path: '/users', status: 200, ...json(user), headers: okHeaders }, true, undefined], + ['writeOnly property present in a response', { method: 'get', path: '/users', status: 200, ...json({ ...user, password: 'x' }), headers: okHeaders }, false, 'schema'], + ['format checked', { method: 'get', path: '/users', status: 200, ...json({ id: 'nope' }), headers: okHeaders }, false, 'schema'], + ['required response header missing', { method: 'get', path: '/users', status: 200, ...json(user), headers: { 'content-type': 'application/json' } }, false, 'header'], + ['header schema (integer, minimum)', { method: 'get', path: '/users', status: 200, ...json(user), headers: { ...okHeaders, 'x-total-count': '-1' } }, false, 'header'], + ['header array of booleans (style simple)', { method: 'get', path: '/users', status: 200, ...json(user), headers: { ...okHeaders, 'x-flags': 'true,false' } }, true, undefined], + ['header array with a bad item', { method: 'get', path: '/users', status: 200, ...json(user), headers: { ...okHeaders, 'x-flags': 'true,maybe' } }, false, 'header'], + ['default response matches its schema', { method: 'get', path: '/users', status: 503, ...json({ message: 'down' }) }, true, undefined], + ['default response breaks its schema', { method: 'get', path: '/users', status: 503, ...json({}) }, false, 'schema'], + ['empty body where a schema is documented', { method: 'get', path: '/users', status: 200, contentType: 'application/json', body: null, rawText: '', headers: okHeaders }, false, 'empty-body'], + ['204 without a body', { method: 'delete', path: '/users', status: 204, contentType: null, body: '', rawText: '' }, true, undefined], + ['204 with a body', { method: 'delete', path: '/users', status: 204, ...json({ deleted: true }) }, false, 'unexpected-body'], + ['4XX range without content, body returned', { method: 'delete', path: '/users', status: 409, ...json({ message: 'conflict' }) }, false, 'unexpected-body'], + ['HEAD: no body is expected', { method: 'head', path: '/users', status: 200, contentType: 'application/json', body: '', rawText: '' }, true, undefined], + ['text/plain matches its string schema', { method: 'get', path: '/text', status: 200, contentType: 'text/plain', body: 'OK fine', rawText: 'OK fine' }, true, undefined], + ['text/plain breaks its pattern', { method: 'get', path: '/text', status: 200, contentType: 'text/plain', body: 'bad', rawText: 'bad' }, false, 'schema'], + ['undocumented content type', { method: 'get', path: '/text', status: 200, contentType: 'application/json', body: {}, rawText: '{}' }, false, 'content-type'], + ['undocumented status', { method: 'get', path: '/text', status: 500, contentType: 'text/plain', body: 'x', rawText: 'x' }, false, 'undocumented-status'], + ['unparseable JSON', { method: 'get', path: '/users', status: 200, contentType: 'application/json', body: undefined, rawText: '{oops', headers: okHeaders }, false, 'unparseable-body'], + ['empty body with an undocumented Content-Type: the type is the problem', { method: 'get', path: '/users', status: 200, contentType: 'text/html', body: '', rawText: '', headers: okHeaders }, false, 'content-type'], + ['JSON null without raw text is a body, not an empty one', { method: 'get', path: '/users', status: 200, contentType: 'application/json', body: null, headers: okHeaders }, false, 'schema'], + ['xml: not checked, with a note', { method: 'get', path: '/xml', status: 200, contentType: 'application/xml', body: '', rawText: '' }, true, undefined], + ['json without a schema: not checked, with a note', { method: 'get', path: '/free', status: 200, ...json({ any: 1 }) }, true, undefined], +]; + +describe('stage 5: response contract', () => { + const v = new ContractValidator(doc); + + for (const [name, input, ok, kind] of CASES) { + it(`TypeScript: ${name}`, () => { + const r = v.validateResponse(input); + expect({ ok: r.ok, kind: r.kind }, r.errors.join('; ')).toEqual({ ok, kind }); + }); + } + + it('notes say what was not checked', () => { + expect(v.validateResponse(CASES.find((c) => c[0].startsWith('xml'))![1]).notes).toEqual(['200 application/xml: media type not supported by the validator, body not checked']); + expect(v.validateResponse(CASES.find((c) => c[0].startsWith('json without'))![1]).notes).toEqual(['200 application/json: no schema documented, body not checked']); + }); + + it('Python (contract.py) gives the same result for every case', async () => { + const python = findPython(); + if (spawnSync(python, ['-c', 'import jsonschema'], { encoding: 'utf8' }).status !== 0) return; // no jsonschema here: CI runs it + const dir = await mkdtemp(join(tmpdir(), 'ata-val-')); + await writeFile(join(dir, 'doc.json'), JSON.stringify(doc)); + await writeFile(join(dir, 'cases.json'), JSON.stringify(CASES.map(([name, i]) => ({ name, ...i, body: i.body === undefined ? '__UNPARSEABLE__' : i.body })))); + const script = ` +import json, sys +sys.path.insert(0, ${JSON.stringify(resolve('src/contract'))}) +import contract +v = contract.ContractValidator(json.load(open(${JSON.stringify(join(dir, 'doc.json'))}))) +out = [] +for c in json.load(open(${JSON.stringify(join(dir, 'cases.json'))})): + body = contract._UNPARSEABLE if c["body"] == "__UNPARSEABLE__" else c["body"] + ok, kind, errors = v.validate(c["method"], c["path"], c["status"], c.get("contentType"), body, c.get("rawText"), c.get("headers")) + out.append({"name": c["name"], "ok": ok, "kind": kind}) +print(json.dumps(out)) +`; + const r = spawnSync(python, ['-I', '-c', script], { encoding: 'utf8' }); + expect(r.status, r.stderr).toBe(0); + const py = JSON.parse(r.stdout); + expect(py).toEqual(CASES.map(([name, , ok, kind]) => ({ name, ok, kind: kind ?? null }))); + }); +}); From c0234b4bfb54752c38970fe2107b785bb796dc89 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:37:22 +0100 Subject: [PATCH 5/8] feat(coverage): documented error responses with safe triggers (stage 6) src/generate/error-cases.ts plans, per operation, the documented errors that can be triggered safely; the rest are gaps with codes. - 401 invalid credentials per security scheme (bearer / OAuth2 / OIDC, basic, API key in header / query / cookie), sent without real ones. - 405: a GET to a path that defines no GET, one case per path; a path with GET is UNSAFE_LIVE_CHECK. - 409: create twice with the same payload, only with a reviewed deps "conflictOn"; business scenario, both records removed in finally; otherwise UNCONFIRMED_BUSINESS_RULE. - 412: non-matching If-Match / If-Unmodified-Since on the test's own record. - 415: the documented body as text/plain, with confirmed cleanup. - 403 / 429 / other 4xx: gaps (UNCONFIRMED_BUSINESS_RULE, UNSAFE_LIVE_CHECK, UNREACHABLE_RESPONSE_STATUS). - Vocabulary v2: invalid-credentials, method-not-allowed, precondition-failed. TypeScript and Python render the same cases. - CI: the synthetic fixture (now with security, 405, 412, 415, 409, 403, 429, 418) is generated in both languages and must compile (tsc, py_compile) with a valid registry. Demo API: 59 tests per language (401 with an invalid token on GET /me passes live); only stats/get/contract fails. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 11 ++ docs/SUPPORT_MATRIX.md | 28 +++-- src/cases/assign.ts | 25 +++- src/cases/ids.ts | 9 +- src/generate/error-cases.ts | 105 ++++++++++++++++ src/generate/generate.ts | 13 +- src/generate/graph.ts | 5 + src/generate/python.ts | 77 +++++++++++- src/generate/templates.ts | 114 ++++++++++++++++-- tests/api/_support/cases.json | 7 ++ tests/api/_support/generation-manifest.json | 11 +- tests/api/_support/openapi.snapshot.meta.json | 2 +- tests/api/me/get/functional.spec.ts | 5 + .../fixtures/coverage/kitchen-sink.deps.json | 13 ++ tests/fixtures/coverage/kitchen-sink.yaml | 35 ++++++ tests/unit/error-cases.test.ts | 87 +++++++++++++ 16 files changed, 509 insertions(+), 38 deletions(-) create mode 100644 src/generate/error-cases.ts create mode 100644 tests/fixtures/coverage/kitchen-sink.deps.json create mode 100644 tests/unit/error-cases.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 619888c..5702811 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,17 @@ jobs: - run: npm run build - run: npm test + - name: Generated code for the synthetic fixture compiles (TypeScript and Python) + # tests/fixtures/coverage/kitchen-sink.yaml exercises every template: nested bodies, all parameter + # kinds, error responses, scenarios. Generated, never run (no server), but it must compile. + run: | + npx tsx src/cli.ts generate tests/fixtures/coverage/kitchen-sink.yaml --deps tests/fixtures/coverage/kitchen-sink.deps.json --tests-dir tests/api-ks --max-cases 500 -o reports/ks --fail-on never + npx tsc --noEmit + npx tsx src/cli.ts generate tests/fixtures/coverage/kitchen-sink.yaml --deps tests/fixtures/coverage/kitchen-sink.deps.json --tests-dir tests/api-ks-python --lang python --max-cases 500 -o reports/ks-python --fail-on never + python -m py_compile $(find tests/api-ks-python -name '*.py') + npx tsx src/cli.ts registry validate tests/api-ks/_support/cases.json --spec tests/fixtures/coverage/kitchen-sink.yaml --require-spec > /dev/null + rm -rf tests/api-ks tests/api-ks-python + - name: Start demo API run: | nohup npm run demo > demo-api.log 2>&1 & diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index ceeab55..2259c6e 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -91,20 +91,24 @@ The TypeScript and Python validators apply the same rules; `tests/unit/validator | `discriminator` | ๐ŸŸก | `oneOf` validated; the mapping is not used | | | contract tests exercise | ๐ŸŸก | success, 404 and 401 responses; more in stage 6 | 6 | -## Documented error responses +## Documented error responses (`src/generate/error-cases.ts`) -| Status | State | Limits | Stage | +A case is generated only when the request that triggers the error is safe and the error is documented for the operation; everything else is a gap in `coverage-gaps.json` at `response.status#/`. + +| Status | State | How / gap | Stage | |---|---|---|---| -| 400 / 422 (invalid input) | โœ… | body + query | | -| 401 (no credentials) | โœ… | | | -| 401 (invalid token / API key) | โŒ | | 6 | +| 400 / 422 (invalid input) | โœ… | body and parameter cases | 3โ€“4 โœ” | +| 401 (no credentials) | โœ… | `publicApi` / `anonymous_api` | | +| 401 (invalid credentials) | โœ… | a certainly invalid credential of the operation's scheme: HTTP bearer / OAuth2 / OpenID Connect (`Bearer api-agent-invalid-token`), HTTP basic, API key in header / query / cookie; an unknown scheme โ†’ `UNSUPPORTED_SCHEMA_KEYWORD` | 6 โœ” | +| 401 (expired token) | โ›” | needs a configured expired token | 6 (gap) | +| 403 (scope / role) | โ›” | `UNCONFIRMED_BUSINESS_RULE`: needs a reviewed account that must be refused | 6 โœ” (gap) | | 404 (unknown id) | โœ… | single trailing path parameter | | -| 403 (scope / role) | โ›” | needs a reviewed role configuration | 6 | -| 405 | โŒ | | 6 | -| 409 (conflict) | โŒ | unique suffix only prevents it | 6 | -| 412 (precondition) | โŒ | | 6 | -| 415 (wrong Content-Type) | โŒ | | 6 | -| 429 (rate limit) | โ›” | opt-in only | 6 | +| 405 | โœ… | a GET to a path that defines no GET (one case per path); a path with GET โ†’ `UNSAFE_LIVE_CHECK` (any other undocumented method could change data) | 6 โœ” | +| 409 (conflict) | โœ… | create twice with the same payload, only when the deps file names `conflictOn` fields (a reviewed business rule); both records removed in `finally`; otherwise `UNCONFIRMED_BUSINESS_RULE` | 6 โœ” | +| 412 (precondition) | โœ… | a non-matching `If-Match` / `If-Unmodified-Since` header (when documented) on a resource the test creates and removes; no such header โ†’ `UNCONFIRMED_BUSINESS_RULE` | 6 โœ” | +| 415 (wrong Content-Type) | โœ… | the documented body as `text/plain`, create / update with confirmed cleanup; otherwise `MISSING_CLEANUP` | 6 โœ” | +| 429 (rate limit) | โ›” | `UNSAFE_LIVE_CHECK`: never exercised (opt-in with a request budget is not implemented) | 6 โœ” (gap) | +| other documented 4xx | โ›” | `UNREACHABLE_RESPONSE_STATUS` | 6 โœ” (gap) | ## Scenarios (`scenarios.spec.ts`) @@ -114,7 +118,7 @@ The TypeScript and Python validators apply the same rules; `tests/unit/validator | create โ†’ update โ†’ read | โœ… (marked ASSUMPTION) | | | create โ†’ delete โ†’ read 404 | โœ… | | | create โ†’ list / search / filter | โŒ | 8 | -| create โ†’ duplicate create โ†’ 409 | โŒ | 6 / 8 | +| create โ†’ duplicate create โ†’ 409 | โœ… (deps `conflictOn`) | 6 โœ” | | repeated delete, update / delete unknown | โŒ | 8 | | login / refresh โ†’ authorized request | โŒ | 8 | | parent โ†’ child, state transitions, idempotency key, bounded polling | โ›” | need the reviewed scenario file | 8 | diff --git a/src/cases/assign.ts b/src/cases/assign.ts index e1e2321..152524d 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -2,6 +2,7 @@ import type { Operation } from '../types.js'; import type { CrudChain } from '../generate/graph.js'; import type { NegCase } from '../generate/negative.js'; import { bodyPointer, caseId, location, scenarioUid, type CaseParts, type Phase, type ScenarioStep } from './ids.js'; +import type { ErrorPlan } from '../generate/error-cases.js'; /** * Case IDs of the tests the generator writes for one operation (docs/OPENAPI_CHANGE_TRIGGER.md, "Stable IDs"). @@ -24,9 +25,9 @@ export interface ScenarioDefinition { export interface SuiteCaseIds { /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ - functional: { success?: string; notFound?: string; unauthorized?: string; variants: string[] }; - contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[] }; - scenario: { createRead?: string; updateRead?: string; deleteGone?: string }; + functional: { success?: string; notFound?: string; unauthorized?: string; variants: string[]; invalidCredentials?: string; methodNotAllowed?: string; preconditionFailed?: string }; + contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[]; unsupportedMediaType?: string }; + scenario: { createRead?: string; updateRead?: string; deleteGone?: string; conflict?: string }; /** Every case of this operation, by suite, with metadata for cases.json. */ records: Record<'functional' | 'contract' | 'scenario', CaseRecord[]>; scenarios: Record; @@ -42,7 +43,9 @@ export interface AssignInput { paramCases: NegCase[]; notFound?: { param: string }; unauthorized: boolean; - scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean }; + scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict?: boolean }; + /** Documented error responses with a safe trigger (stage 6). */ + errors?: ErrorPlan; /** Documented query values the suite sends one by one (functional positive), each its own physical test. */ queryVariants?: { name: string; value: string | number | boolean }[]; } @@ -96,6 +99,13 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): ids.contract.params.push(at ? add('contract', { subjectUid: uid, polarity: 'negative', location: at, rule: t!.rule }) : ''); } + // Documented error responses (stage 6). + const e = s.errors; + if (e?.invalidCredentials) ids.functional.invalidCredentials = add('functional', { subjectUid: uid, polarity: 'negative', location: location.security(), rule: 'invalid-credentials' }); + if (e?.methodNotAllowed) ids.functional.methodNotAllowed = add('functional', { subjectUid: uid, polarity: 'negative', location: location.operation(), rule: 'method-not-allowed' }); + if (e?.preconditionFailed && chain) ids.functional.preconditionFailed = add('functional', { subjectUid: uid, polarity: 'negative', location: location.header(e.preconditionFailed.header), rule: 'precondition-failed' }, rel); + if (e?.unsupportedMediaType && chain) ids.contract.unsupportedMediaType = add('contract', { subjectUid: uid, polarity: 'negative', location: location.requestContentType(), rule: 'content-type' }, rel); + // CRUD scenarios: steps in order; the operation under test is the action. if (chain) { const step = (o: Operation | undefined, phase: Phase): ScenarioStep[] => (o ? [{ operationUid: uidOf(o), phase }] : []); @@ -111,6 +121,13 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): scenarios[sUid] = def; return add('scenario', { subjectUid: sUid, polarity: 'positive', location: location.lifecycle(), rule: 'crud' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uid))] }); }; + if (s.scenarios.conflict) { + // A business rule confirmed by the deps file: the same create twice conflicts. Business scenarios have no roles. + const steps = [...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.delete, 'cleanup')]; + const sUid = scenarioUid('business', steps); + scenarios[sUid] = { scenarioType: 'business', primaryOperationUid: uid, steps }; + ids.scenario.conflict = add('scenario', { subjectUid: sUid, polarity: 'negative', location: location.lifecycle(), rule: 'business-rule' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uid))] }); + } if (s.scenarios.createRead) ids.scenario.createRead = define([...step(chain.create, 'action'), ...step(chain.read, 'assertion'), ...step(chain.delete, 'cleanup')]); if (s.scenarios.updateRead) ids.scenario.updateRead = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion'), ...step(chain.delete, 'cleanup')]); if (s.scenarios.deleteGone) ids.scenario.deleteGone = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion')]); diff --git a/src/cases/ids.ts b/src/cases/ids.ts index ac716a0..81c65d8 100644 --- a/src/cases/ids.ts +++ b/src/cases/ids.ts @@ -10,7 +10,10 @@ import { base32 } from '../change/normalize.js'; export type SuiteType = 'functional' | 'contract' | 'scenario'; export type Polarity = 'positive' | 'negative'; -/** v2 adds functional/positive `accepted-value` (one case per documented parameter value). Registries of v1 stay readable. */ +/** + * v2 adds functional/positive `accepted-value` (one case per documented parameter value) and functional/negative + * `invalid-credentials`, `method-not-allowed`, `precondition-failed`. Registries of v1 stay readable. + */ export const CASE_RULE_VOCABULARY_VERSION = 2; const CONSTRAINT_RULES = [ @@ -21,7 +24,7 @@ const CONSTRAINT_RULES = [ /** Built-in vocabulary v1, by suiteType/polarity. */ export const VOCABULARY_V1: Record = { 'functional/positive': ['documented-success', 'accepted-value'], - 'functional/negative': ['not-found', 'unauthorized', 'forbidden'], + 'functional/negative': ['not-found', 'unauthorized', 'forbidden', 'invalid-credentials', 'method-not-allowed', 'precondition-failed'], 'contract/positive': ['documented', 'schema'], 'contract/negative': [...CONSTRAINT_RULES, 'content-type'], 'scenario/positive': ['crud', 'business-rule'], @@ -120,6 +123,8 @@ export function checkCombination(p: CaseParts): CaseIdError | undefined { return loc === 'operation' ? undefined : bad(`documented-success is checked on "operation", not "${loc}"`); case 'functional/negative': if (p.rule === 'not-found') return /^request\.path#\/[^/]*$/.test(loc) ? undefined : bad('not-found is checked on a path parameter'); + if (p.rule === 'method-not-allowed') return loc === 'operation' ? undefined : bad('method-not-allowed is checked on "operation"'); + if (p.rule === 'precondition-failed') return /^request\.header#\/[^/]*$/.test(loc) ? undefined : bad('precondition-failed is checked on a precondition header'); return loc === 'request.security' ? undefined : bad(`${p.rule} is checked on "request.security"`); case 'contract/positive': if (p.rule === 'schema') return loc.startsWith('response.body#') ? undefined : bad('schema is checked on a response body location'); diff --git a/src/generate/error-cases.ts b/src/generate/error-cases.ts new file mode 100644 index 0000000..0ffd7bd --- /dev/null +++ b/src/generate/error-cases.ts @@ -0,0 +1,105 @@ +import type { OpenApiDoc } from '../spec/loader.js'; +import type { Operation } from '../types.js'; +import type { CrudChain } from './graph.js'; +import type { CoverageGap } from './body-cases.js'; + +/** + * Documented error responses beyond 400 / 401 (missing credentials) / 404 / 422 (docs/SUPPORT_MATRIX.md, stage 6). + * A case is generated only when the request that triggers the error is safe and its expectation is documented; + * everything else is a gap with its reason. Nothing here guesses business rules. + */ + +export interface ErrorPlan { + /** 401 with a credential that is certainly invalid (per security scheme), sent without the real ones. */ + invalidCredentials?: { headers: Record; params: Record }; + /** 405: a GET to a path that defines no GET (the only method that is safe to send to an unknown route). */ + methodNotAllowed?: { method: 'get' }; + /** 415: the documented body sent as text/plain (create / update with confirmed cleanup). */ + unsupportedMediaType?: true; + /** 412: a precondition header that cannot match, on a resource the test created. */ + preconditionFailed?: { header: string; value: string }; + /** 409: the same create payload twice, on fields a reviewed deps file names (conflictOn). */ + conflict?: { fields: string[] }; + gaps: CoverageGap[]; +} + +const INVALID_TOKEN = 'api-agent-invalid-token'; +const PRECONDITION_VALUES: Record = { + 'if-match': '"api-agent-no-such-etag"', + 'if-unmodified-since': 'Thu, 01 Jan 1970 00:00:00 GMT', +}; +/** Statuses with a handler in this module or elsewhere in the generator. */ +const HANDLED = new Set(['400', '401', '403', '404', '405', '409', '412', '415', '422', '429', '4XX']); + +export interface ErrorInput { + doc: OpenApiDoc; + op: Operation; + ops: Operation[]; + chain?: CrudChain; + role?: 'create' | 'read' | 'update' | 'delete'; + hasUpdatePayload: boolean; + /** Write requests may be sent only with a confirmed cleanup (or for safe methods). */ + reachable: boolean; + /** The operation is the first one of its path documenting 405 (one case per path). */ + firstWith405: boolean; +} + +export function errorPlan(i: ErrorInput): ErrorPlan { + const { doc, op } = i; + const plan: ErrorPlan = { gaps: [] }; + const codes = new Set(op.responses.map((r) => r.status.toUpperCase())); + const gap = (code: string, status: string, reason: string) => plan.gaps.push({ code, location: `response.status#/${status}`, reason }); + + // 401: an invalid credential of the scheme the operation uses. + if (codes.has('401') && i.reachable && op.security.length && !op.security.some((a) => a.length === 0)) { + const schemes = (doc as any).components?.securitySchemes ?? {}; + const headers: Record = {}; + const params: Record = {}; + let unknown: string | undefined; + for (const name of op.security[0]) { + const s = schemes[name]; + const type = String(s?.type ?? '').toLowerCase(); + if (type === 'http' && String(s.scheme).toLowerCase() === 'basic') headers.Authorization = `Basic ${Buffer.from('api-agent:invalid').toString('base64')}`; + else if (type === 'http' || type === 'oauth2' || type === 'openidconnect') headers.Authorization = `Bearer ${INVALID_TOKEN}`; + else if (type === 'apikey' && s.in === 'header') headers[s.name] = 'api-agent-invalid-key'; + else if (type === 'apikey' && s.in === 'query') params[s.name] = 'api-agent-invalid-key'; + else if (type === 'apikey' && s.in === 'cookie') headers.Cookie = `${s.name}=api-agent-invalid-key`; + else unknown = name; + } + if (unknown) gap('UNSUPPORTED_SCHEMA_KEYWORD', '401', `security scheme "${unknown}" has no known invalid credential`); + else plan.invalidCredentials = { headers, params }; + } + + // 405: only a GET may be sent to an undocumented method of a path. + if (codes.has('405') && i.firstWith405) { + const defined = new Set(i.ops.filter((o) => o.path === op.path).map((o) => o.method)); + if (!defined.has('get')) plan.methodNotAllowed = { method: 'get' }; + else gap('UNSAFE_LIVE_CHECK', '405', `every undocumented method of ${op.path} could change data if the API implements it`); + } + + // 415: the body as text/plain, where a created resource can be cleaned up. + if (codes.has('415')) { + if (!op.hasRequestBody) gap('UNREACHABLE_RESPONSE_STATUS', '415', 'the operation has no request body'); + else if (i.role === 'create' || (i.role === 'update' && i.hasUpdatePayload)) plan.unsupportedMediaType = true; + else gap('MISSING_CLEANUP', '415', 'a write without a confirmed precondition and cleanup is not sent'); + } + + // 412: a precondition header that cannot match, on the test's own resource. + if (codes.has('412')) { + const header = op.params.find((p) => p.in === 'header' && PRECONDITION_VALUES[p.name.toLowerCase()]); + if (!header) gap('UNCONFIRMED_BUSINESS_RULE', '412', 'no If-Match / If-Unmodified-Since header is documented to trigger it'); + else if ((i.role === 'update' && i.hasUpdatePayload) || i.role === 'delete') plan.preconditionFailed = { header: header.name, value: PRECONDITION_VALUES[header.name.toLowerCase()] }; + else gap('MISSING_CLEANUP', '412', 'needs a resource the test creates and removes (a confirmed update / delete chain)'); + } + + // 409: duplicate create, only on fields a reviewed deps file names. + if (codes.has('409')) { + if (i.role === 'create' && i.chain?.conflictOn?.length) plan.conflict = { fields: i.chain.conflictOn }; + else gap('UNCONFIRMED_BUSINESS_RULE', '409', i.role === 'create' ? 'which fields conflict is not confirmed: add "conflictOn" to the deps file' : 'what makes this operation conflict is not documented'); + } + + if (codes.has('403')) gap('UNCONFIRMED_BUSINESS_RULE', '403', 'needs a reviewed role / scope configuration (an account that must be refused)'); + if (codes.has('429')) gap('UNSAFE_LIVE_CHECK', '429', 'rate limiting is not exercised (it would load the target)'); + for (const c of codes) if (/^4\d\d$/.test(c) && !HANDLED.has(c)) gap('UNREACHABLE_RESPONSE_STATUS', c, `no deterministic request triggers ${c}`); + return plan; +} diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 60880cf..ddf3b34 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -14,6 +14,7 @@ import { headRevision } from '../change/baseline.js'; import { isUrl } from '../change/network.js'; import { bodyCasesDetailed, type CoverageGap } from './body-cases.js'; import { paramCasesDetailed, sendable } from './param-cases.js'; +import { errorPlan } from './error-cases.js'; import { bodyCases, documentedRejections, nonexistentIdExpr, type NegCase } from './negative.js'; import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; import { API_BASE, buildApiIndex, renderApiBaseClass, renderApiChildClass, renderApis } from './api-objects.js'; @@ -228,6 +229,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp // 2. Per operation: //{functional,contract,scenarios}.spec.ts, each only when it has a case. // Polarity (positive/negative) is a tag inside the files, not a file of its own. const used = new Set(); + const paths405 = new Set(); // one 405 case per path for (const op of ops) { let { resource, action } = operationFolder(op); if (py) { @@ -311,10 +313,15 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp } // --- suites - const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized }; + // Documented error responses with a safe trigger; the rest are gaps (stage 6). + const errRole = !plan ? undefined : plan.chain.create === op ? 'create' : plan.chain.read === op ? 'read' : plan.chain.update === op ? 'update' : plan.chain.delete === op ? 'delete' : undefined; + const firstWith405 = op.responses.some((r) => r.status === '405') && !paths405.has(op.path); + if (firstWith405) paths405.add(op.path); + const errors = op.deprecated ? { gaps: [] } : errorPlan({ doc: spec.doc, op, ops, chain: plan?.chain, role: errRole, hasUpdatePayload: plan?.updatePayload !== undefined, reachable, firstWith405 }); + const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors }; 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 }, uidOf); + const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants, errors }, uidOf); input.ids = ids; // Explicit per-operation coverage and gaps, independent of test execution status. // Response bodies the validator cannot check: said explicitly, never passed silently. @@ -327,7 +334,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp return []; }), ); - coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: [...bodyGaps, ...responseGaps], ...(bodyStats ? { bodyCases: bodyStats } : {}) }); + coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: [...bodyGaps, ...errors.gaps, ...responseGaps], ...(bodyStats ? { bodyCases: bodyStats } : {}) }); const render: Record string> = py ? { functional: renderPyFunctional, contract: renderPyContract, scenario: renderPyScenarios } : { functional: renderFunctional, contract: renderContract, scenario: renderScenarios }; diff --git a/src/generate/graph.ts b/src/generate/graph.ts index 3506823..0c65978 100644 --- a/src/generate/graph.ts +++ b/src/generate/graph.ts @@ -19,6 +19,8 @@ export interface CrudChain { source: string; /** Body fields of create taken from existing data at run time (deps file "fill"), never created by the test. */ fill?: FillRule[]; + /** Create body fields a reviewed deps file names as unique: the same values twice must give the documented 409. */ + conflictOn?: string[]; } export interface FillRule { @@ -46,6 +48,8 @@ export interface DepsFile { delete?: string; /** field โ†’ where its value comes from at run time: { "product_id": { "from": "getProducts", "pointer": "/data/0/id" } } */ fill?: Record; + /** Fields whose repeated values make create answer 409 (a reviewed business rule). */ + conflictOn?: string[]; }[]; } @@ -69,6 +73,7 @@ export function findChains(doc: OpenApiDoc, ops: Operation[], deps?: DepsFile): delete: s.delete ? byId.get(s.delete) : undefined, source: 'deps file (human-confirmed)', ...(s.fill ? { fill: Object.entries(s.fill).map(([field, f]) => ({ field, fromId: f?.from, from: byId.get(f?.from), pointer: f?.pointer })) } : {}), + ...(Array.isArray(s.conflictOn) && s.conflictOn.length ? { conflictOn: s.conflictOn.map(String) } : {}), }); } diff --git a/src/generate/python.ts b/src/generate/python.ts index 2452281..ec4bb27 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -359,7 +359,7 @@ function pyHeader(suite: SuiteType, s: SuiteInput, meta: Meta, extra: string[]): const lines = [...extra]; if (s.plan) lines.unshift(`Preconditions and cleanup: ${s.plan.chain.source}`); lines.push('Polarity is a marker: run one side with -m positive or -m negative.'); - return [header(suite, s.op, meta, lines), 'import uuid # noqa: F401', 'from urllib.parse import quote # noqa: F401', '', 'import pytest', '', 'from contract import read_pointer # noqa: F401', '', `pytestmark = pytest.mark.${suite}`, '', '']; + return [header(suite, s.op, meta, lines), 'import json # noqa: F401', 'import uuid # noqa: F401', 'from urllib.parse import quote # noqa: F401', '', 'import pytest', '', 'from contract import read_pointer # noqa: F401', '', `pytestmark = pytest.mark.${suite}`, '', '']; } /** The successful call with its precondition (fixtures) and cleanup; `assert` returns the assertion lines. */ @@ -441,9 +441,52 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { } if (s.notFound) L.push(...pyNotFound(s, 'test_returns_documented_404_for_unknown_id', withId(NEG, s.ids?.functional.notFound), statusIs(op, '404'))); if (s.unauthorized) L.push(...pyAnonymous(s, 'test_returns_documented_401_without_credentials', withId(NEG, s.ids?.functional.unauthorized), statusIs(op, '401'))); + L.push(...pyErrorTests(s)); return finish(L); } +/** Documented error responses with a safe trigger (stage 6), as in the TypeScript suite. */ +function pyErrorTests(s: SuiteInput): string[] { + const { op, plan } = s; + const e = s.errors; + if (!e) return []; + const req = requiredRequest(op); + const L: string[] = []; + if (e.invalidCredentials) { + const params = { ...req.params, ...e.invalidCredentials.params }; + const headers = { ...req.headers, ...e.invalidCredentials.headers }; + // anonymous_api carries no credentials of its own: only the invalid one is sent. + L.push( + withId(NEG, s.ids?.functional.invalidCredentials), + 'def test_returns_documented_401_for_invalid_credentials(anonymous_api):', + ` res = anonymous_api.${op.method}(${pathExpr(op, plan?.chain.param, '"unused"')}${Object.keys(params).length ? `, params=${pyLit(params, 4)}` : ''}, headers=${pyLit(headers, 4)})`, + ` ${statusIs(op, '401')}`, + '', + '', + ); + } + if (e.methodNotAllowed) { + const path = op.path.replace(/^\//, '').replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(String(op.params.find((p) => p.in === 'path' && p.name === name)?.knownValue ?? 'unused'))); + // GET is the only method that is safe to send to a route the spec does not define. + L.push(withId(NEG, s.ids?.functional.methodNotAllowed), 'def test_answers_documented_405_to_a_method_the_path_does_not_define(api):', ` res = api.get(${str(path)})`, ` ${statusIs(op, '405')}`, '', ''); + } + if (e.preconditionFailed && plan) { + const res = resourceModule(plan).replace(/_resource$/, ''); + const headers = { ...req.headers, [e.preconditionFailed.header]: e.preconditionFailed.value }; + const data = plan.chain.update === op ? `, json=${res}.new_update_payload()` : ''; + const params = Object.keys(req.params).length ? `, params=${pyLit(req.params, 4)}` : ''; + L.push( + withId(NEG, s.ids?.functional.preconditionFailed), + `def test_returns_documented_412_when_precondition_does_not_match(api, ${res}, created_${res}):`, + ` res = api.${op.method}(${pathExpr(op, plan.chain.param, `created_${res}`)}${data}${params}, headers=${pyLit(headers, 4)})`, + ` ${statusIs(op, '412')}`, + '', + '', + ); + } + return L; +} + /** test_contract.py: responses match OpenAPI; invalid requests are rejected as documented. */ export function renderPyContract(s: SuiteInput, meta: Meta): string { const { op, plan } = s; @@ -484,6 +527,19 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { L.push(' path = parts.get("path", {})'); L.push(` res = api.${op.method}(${pathFromParts(op)}, params=parts.get("params"), headers=parts.get("headers"))`, ` contract.expect_rejected(res, REJECTION, ${str(op.method)}, ${str(op.path)})`, '', ''); } + if (s.errors?.unsupportedMediaType && chain) { + // 415: the documented body, but declared as text/plain. Anything the API wrongly creates is removed. + const req = requiredRequest(op); + const headers = pyLit({ ...req.headers, 'content-type': 'text/plain' }, 4); + const params = Object.keys(req.params).length ? `, params=${pyLit(req.params, 4)}` : ''; + L.push(withId(NEG, s.ids?.contract.unsupportedMediaType)); + if (isCreate) { + L.push(`def test_rejects_a_body_sent_as_text_plain(api, contract, ${res}):`, ` res = api.${op.method}(${pathExpr(op)}, data=json.dumps(${res}.new_create_payload())${params}, headers=${headers})`, ` ${res}.remove_if_created(res)`); + } else { + L.push(`def test_rejects_a_body_sent_as_text_plain(api, contract, ${res}, created_${res}):`, ` res = api.${op.method}(${pathExpr(op, chain.param, `created_${res}`)}, data=json.dumps(${res}.new_update_payload())${params}, headers=${headers})`); + } + L.push(` contract.expect_rejected(res, ["415"], ${str(op.method)}, ${str(op.path)})`, '', ''); + } return finish(L); } @@ -498,6 +554,25 @@ export function renderPyScenarios(s: SuiteInput, meta: Meta): string { if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = pyHeader('scenario', s, meta, extra); const id = `created_${res}`; + if (sc.conflict) { + // 409 on the fields a reviewed deps file names: the same payload twice. Both records are removed. + L.push( + withId(NEG, s.ids?.scenario.conflict), + `def test_second_create_with_the_same_fields_conflicts(api, ${res}):`, + ` payload = ${res}.new_create_payload()`, + ` first_id, _ = ${res}.create(payload)`, + ' try:', + ` res = api.${op.method}(${pathExpr(op)}, json=payload${pyRequired(op)})`, + ' try:', + ` ${statusIs(op, '409')}`, + ' finally:', + ` ${res}.remove_if_created(res)`, + ' finally:', + ` ${res}.remove(first_id)`, + '', + '', + ); + } if (sc.createRead) { L.push( withId(POS, s.ids?.scenario.createRead), diff --git a/src/generate/templates.ts b/src/generate/templates.ts index fa4b6b6..12def32 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -4,6 +4,7 @@ import type { NegCase } from './negative.js'; import { apiCall, type ApiRef } from './api-objects.js'; import type { SuiteCaseIds } from '../cases/assign.js'; import { requiredRequest, type ParamRequest } from './param-cases.js'; +import type { ErrorPlan } from './error-cases.js'; /** Payloads and assumptions for one confirmed resource chain. */ export interface ChainPlan { @@ -219,6 +220,8 @@ export interface SuiteInput { unauthorized: boolean; /** Stable case IDs of this operation's tests (Playwright annotation caseId, pytest marker api_case_id). */ ids?: SuiteCaseIds; + /** Documented error responses with a safe trigger (stage 6). */ + errors?: ErrorPlan; } export type Role = 'create' | 'read' | 'update' | 'delete'; @@ -230,10 +233,11 @@ export function roleOf(op: Operation, plan?: ChainPlan): Role | undefined { } /** Multi-request scenarios whose primary operation is `op` (the action under test, never the setup step). */ -export function scenarioCases(s: Pick): { createRead: boolean; updateRead: boolean; deleteGone: boolean } { +export function scenarioCases(s: Pick): { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict: boolean } { const role = roleOf(s.op, s.plan); const read = s.plan?.chain.read; return { + conflict: s.positive && role === 'create' && !!s.errors?.conflict, createRead: s.positive && role === 'create' && !!read, updateRead: s.positive && role === 'update' && !!read && s.plan!.updatePayload !== undefined, deleteGone: s.positive && role === 'delete' && !!read && read.responses.some((r) => r.status === '404'), @@ -244,10 +248,11 @@ export function scenarioCases(s: Pick): export function suiteCounts(s: SuiteInput): Record { const extra = (s.notFound ? 1 : 0) + (s.unauthorized ? 1 : 0); const sc = scenarioCases(s); + const e = s.errors; return { - functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0), - contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length, - scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0), + functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0) + (e?.invalidCredentials ? 1 : 0) + (e?.methodNotAllowed ? 1 : 0) + (e?.preconditionFailed && s.plan ? 1 : 0), + contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length + (e?.unsupportedMediaType && s.plan ? 1 : 0), + scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0) + (sc.conflict ? 1 : 0), }; } @@ -343,8 +348,9 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { const chain = plan?.chain; const role = roleOf(op, plan); const fx = chain ? 'api' : apiFixture(op); - const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s); - const names = ['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized ? ['expectStatus'] : [])]; + const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan); + const errorStatus = !!(s.errors?.invalidCredentials || s.errors?.methodNotAllowed || s.errors?.preconditionFailed); + const names = ['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : [])]; const L = suiteHeader('functional', s, meta, ['Checks the behavior of the endpoint: status and result. The response schema is checked in contract.spec.ts.']); L.push(...imports(s, names, usesHelpers), '', `test.describe('${op.key} ยท functional', { tag: '@functional' }, () => {`); @@ -387,9 +393,62 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { // publicApi sends no credentials at all (not even the project's static token). L.push(` test('returns documented 401 without credentials', ${testOptions('negative', s.ids?.functional.unauthorized)}, async ({ publicApi }) => {`, anonymousCall(s), ` expectStatus(res, ['401'], '${op.method}', ${q(op.path)});`, ` });`, ''); } + L.push(...errorTests(s)); return close(L); } +/** Documented error responses with a safe trigger (stage 6): invalid credentials, 405, 412. */ +function errorTests(s: SuiteInput): string[] { + const { op, plan } = s; + const e = s.errors; + if (!e) return []; + const ref = s.refs.get(op)!; + const req = requiredRequest(op); + const L: string[] = []; + if (e.invalidCredentials) { + const params = { ...req.params, ...e.invalidCredentials.params }; + const headers = { ...req.headers, ...e.invalidCredentials.headers }; + const opts = [Object.keys(params).length ? `params: ${JSON.stringify(params)}` : '', `headers: ${JSON.stringify(headers)}`].filter(Boolean).join(', '); + // publicApi carries no credentials of its own: only the invalid one is sent. + L.push( + ` test('returns documented 401 for invalid credentials', ${testOptions('negative', s.ids?.functional.invalidCredentials)}, async ({ publicApi }) => {`, + ` const res = await ${apiCall(ref, 'publicApi', pathArgs(op, ref, plan?.chain.param, "'unused'"), `{ ${opts} }`)};`, + ` expectStatus(res, ['401'], '${op.method}', ${q(op.path)});`, + ` });`, + '', + ); + } + if (e.methodNotAllowed) { + const path = op.path.replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(String(op.params.find((p) => p.in === 'path' && p.name === name)?.knownValue ?? 'unused'))); + // GET is the only method that is safe to send to a route the spec does not define. + L.push( + ` test('answers documented 405 to a method the path does not define (GET)', ${testOptions('negative', s.ids?.functional.methodNotAllowed)}, async ({ request }) => {`, + ` const res = await request.get(${q(path.replace(/^\//, ''))});`, + ` expectStatus(res, ['405'], '${op.method}', ${q(op.path)});`, + ` });`, + '', + ); + } + if (e.preconditionFailed && plan) { + const headers = { ...req.headers, [e.preconditionFailed.header]: e.preconditionFailed.value }; + const data = plan.chain.update === op ? ', data: resource.newUpdatePayload()' : ''; + const params = Object.keys(req.params).length ? `params: ${JSON.stringify(req.params)}, ` : ''; + L.push( + ` test('returns documented 412 when ${e.preconditionFailed.header} does not match', ${testOptions('negative', s.ids?.functional.preconditionFailed)}, async ({ api }) => {`, + ` const { id } = await resource.create(api);`, + ` try {`, + ` const res = await ${apiCall(ref, 'api', pathArgs(op, ref, plan.chain.param, 'id'), `{ ${params}headers: ${JSON.stringify(headers)}${data} }`)};`, + ` expectStatus(res, ['412'], '${op.method}', ${q(op.path)});`, + ` } finally {`, + ` await resource.remove(api, id);`, + ` }`, + ` });`, + '', + ); + } + return L; +} + const caseField = (id?: string) => (id ? `caseId: ${q(id)}, ` : ''); /** A data-driven test: the case ID comes from the row when every row has one. */ const loopOptions = (ids?: string[]) => (ids?.length && ids.every(Boolean) ? `{ tag: '@negative', annotation: { type: 'caseId', description: c.caseId } }` : NEG); @@ -402,14 +461,15 @@ export function renderContract(s: SuiteInput, meta: Meta): string { const ref = s.refs.get(op)!; const isCreate = chain?.create === op; const needsExisting = !!chain && chain.create !== op && op.params.some((p) => p.in === 'path' && p.name === chain.param); - const invalid = s.bodyCases.length + s.paramCases.length > 0; - const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || (s.bodyCases.length > 0 && !!chain && (isCreate || needsExisting)); + const wrongMedia = !!(s.errors?.unsupportedMediaType && chain); + const invalid = s.bodyCases.length + s.paramCases.length > 0 || wrongMedia; + const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || (s.bodyCases.length > 0 && !!chain && (isCreate || needsExisting)) || wrongMedia; // Validation cases go through the same fixture as the positive test (anonymous for public operations). const fx = chain ? 'api' : apiFixture(op); const names = [...(s.positive || s.notFound || s.unauthorized ? ['expectContract'] : []), ...(invalid ? ['expectRejected'] : [])]; const L = suiteHeader('contract', s, meta, ['Checks conformance to the OpenAPI document: the status actually returned is documented and the body matches its schema.', 'Invalid requests break one documented constraint each and must get a documented rejection.']); L.push(...imports(s, names, usesHelpers)); - if (invalid) L.push('', `const rejection = ${JSON.stringify(s.validation)}; // documented in the spec`); + if (s.bodyCases.length + s.paramCases.length > 0) L.push('', `const rejection = ${JSON.stringify(s.validation)}; // documented in the spec`); L.push('', `test.describe('${op.key} ยท contract', { tag: '@contract' }, () => {`); const contract = (i: string, v = 'res') => [`${i}await expectContract(${v}, '${op.method}', ${q(op.path)});`]; @@ -447,6 +507,18 @@ export function renderContract(s: SuiteInput, meta: Meta): string { L.push(` ];`, '', ` for (const c of invalidParameters) {`, ` test(\`rejects invalid parameter: \${c.title}\`, ${loopOptions(s.ids?.contract.params)}, async ({ ${fx} }) => {`); L.push(` const res = await ${apiCall(ref, fx, args, '{ params: c.params, headers: c.headers }')};`, ` await expectRejected(res, rejection, '${op.method}', ${q(op.path)});`, ` });`, ` }`, ''); } + if (wrongMedia) { + // 415: the documented body, but declared as text/plain. Anything the API wrongly creates is removed. + const req = requiredRequest(op); + const headers = JSON.stringify({ ...req.headers, 'content-type': 'text/plain' }); + const params = Object.keys(req.params).length ? `params: ${JSON.stringify(req.params)}, ` : ''; + const payload = isCreate ? (hasFill(plan) ? 'await resource.newCreatePayload(api)' : 'resource.newCreatePayload()') : 'resource.newUpdatePayload()'; + const opts = `{ ${params}headers: ${headers}, data: JSON.stringify(${payload}) }`; + L.push(` test('rejects a body sent as text/plain with documented 415', ${testOptions('negative', s.ids?.contract.unsupportedMediaType)}, async ({ api }) => {`); + if (isCreate) L.push(` const res = await ${apiCall(ref, 'api', pathArgs(op, ref), opts)};`, ` await resource.removeIfCreated(api, res);`, ` await expectRejected(res, ['415'], '${op.method}', ${q(op.path)});`); + else L.push(` const { id } = await resource.create(api);`, ` try {`, ` const res = await ${apiCall(ref, 'api', pathArgs(op, ref, chain!.param, 'id'), opts)};`, ` await expectRejected(res, ['415'], '${op.method}', ${q(op.path)});`, ` } finally {`, ` await resource.remove(api, id);`, ` }`); + L.push(` });`, ''); + } return close(L); } @@ -463,7 +535,29 @@ export function renderScenarios(s: SuiteInput, meta: Meta): string { const extra = ['Each scenario: setup (create) โ†’ action (this operation) โ†’ assertion (read) โ†’ cleanup (delete).']; if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = suiteHeader('scenario', s, meta, extra); - L.push(...imports(s, ['expect', ...(sc.createRead ? ['readPointer'] : [])], true, false), '', `test.describe('${op.key} ยท scenarios', { tag: '@scenario' }, () => {`); + L.push(...imports(s, ['expect', ...(sc.createRead ? ['readPointer'] : []), ...(sc.conflict ? ['expectStatus'] : [])], true, false), '', `test.describe('${op.key} ยท scenarios', { tag: '@scenario' }, () => {`); + if (sc.conflict) { + // 409 on the fields a reviewed deps file names: the same payload twice. Both records are removed. + const fields = s.errors!.conflict!.fields; + const payload = hasFill(plan) ? 'await resource.newCreatePayload(api)' : 'resource.newCreatePayload()'; + L.push( + ` test(${q(`a second create with the same ${fields.join(', ')} gets the documented 409`)}, ${testOptions('negative', s.ids?.scenario.conflict)}, async ({ api }) => {`, + ` const payload = ${payload};`, + ` const first = await resource.create(api, payload);`, + ` try {`, + ` const res = await ${call(op, optionsWith(op, '{ data: payload }'))};`, + ` try {`, + ` expectStatus(res, ['409'], '${op.method}', ${q(op.path)});`, + ` } finally {`, + ` await resource.removeIfCreated(api, res);`, + ` }`, + ` } finally {`, + ` await resource.remove(api, first.id);`, + ` }`, + ` });`, + '', + ); + } if (sc.createRead) { L.push( ` test('the created resource can be retrieved by ${r.operationId ?? r.key}', ${testOptions('positive', s.ids?.scenario.createRead)}, async ({ api }) => {`, diff --git a/tests/api/_support/cases.json b/tests/api/_support/cases.json index 3c1fb90..91f1646 100644 --- a/tests/api/_support/cases.json +++ b/tests/api/_support/cases.json @@ -339,6 +339,13 @@ "subjectUid": "op_WRZHS7HTMVON", "suiteType": "contract" }, + "ata:op_WRZHS7HTMVON:functional:negative:request.security:invalid-credentials": { + "location": "request.security", + "polarity": "negative", + "rule": "invalid-credentials", + "subjectUid": "op_WRZHS7HTMVON", + "suiteType": "functional" + }, "ata:op_WRZHS7HTMVON:functional:negative:request.security:unauthorized": { "location": "request.security", "polarity": "negative", diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index e93ee40..752226c 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -1,5 +1,5 @@ { - "caseRegistryHash": "8b7eb6331738126984b0de2b2ae737f245b0f9fcd294de32cb8e5d1a91e976c8", + "caseRegistryHash": "51f82bffa7438b9e1f7595daf8ca206bbf944b446f15c35a87d78b4f3310b879", "files": { "_support/api/generated/AdminApiBase.ts": { "ownership": "generated", @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "da2e6eb7ce782763af79669ad4f51564631e99a56233733d3b52e5ed6a69314c" + "sha256": "02321c2de281b2ca60e29bca3a07b8ce21294ad4fe4a77491c43f0b397091cf9" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -295,13 +295,14 @@ "me/get/functional.spec.ts": { "caseIds": [ "ata:op_WRZHS7HTMVON:functional:positive:operation:documented-success", - "ata:op_WRZHS7HTMVON:functional:negative:request.security:unauthorized" + "ata:op_WRZHS7HTMVON:functional:negative:request.security:unauthorized", + "ata:op_WRZHS7HTMVON:functional:negative:request.security:invalid-credentials" ], "operationUids": [ "op_WRZHS7HTMVON" ], "ownership": "generated", - "sha256": "7889879405c221505474de9f4e3048b77dc1be70ab2b1399ade88fd629ce018d", + "sha256": "0078147e5f0ab275165ebf21e15f534439352c5af45fe5d3a82596070546326b", "suiteType": "functional" }, "reports/get-by-id/contract.spec.ts": { @@ -353,7 +354,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "9142b4bfc92cba8ebcfaecd302af395090aac8c6", + "revision": "ea9aa19720af422a38924d9284f0e7190b6d5337", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index 7f60940..320485a 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "9142b4bfc92cba8ebcfaecd302af395090aac8c6", + "capturedRevision": "ea9aa19720af422a38924d9284f0e7190b6d5337", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/api/me/get/functional.spec.ts b/tests/api/me/get/functional.spec.ts index 36dca0a..7928cbc 100644 --- a/tests/api/me/get/functional.spec.ts +++ b/tests/api/me/get/functional.spec.ts @@ -16,4 +16,9 @@ test.describe('GET /me ยท functional', { tag: '@functional' }, () => { const res = await publicApi.me.getMe(); expectStatus(res, ['401'], 'get', '/me'); }); + + test('returns documented 401 for invalid credentials', { tag: '@negative', annotation: { type: 'caseId', description: 'ata:op_WRZHS7HTMVON:functional:negative:request.security:invalid-credentials' } }, async ({ publicApi }) => { + const res = await publicApi.me.getMe({ headers: {"Authorization":"Bearer api-agent-invalid-token"} }); + expectStatus(res, ['401'], 'get', '/me'); + }); }); diff --git a/tests/fixtures/coverage/kitchen-sink.deps.json b/tests/fixtures/coverage/kitchen-sink.deps.json new file mode 100644 index 0000000..cb6ed57 --- /dev/null +++ b/tests/fixtures/coverage/kitchen-sink.deps.json @@ -0,0 +1,13 @@ +{ + "scenarios": [ + { + "create": "createOrder", + "idFrom": "/id", + "param": "orderId", + "read": "getOrder", + "update": "updateOrder", + "delete": "deleteOrder", + "conflictOn": ["customer"] + } + ] +} diff --git a/tests/fixtures/coverage/kitchen-sink.yaml b/tests/fixtures/coverage/kitchen-sink.yaml index 812ff23..03864a3 100644 --- a/tests/fixtures/coverage/kitchen-sink.yaml +++ b/tests/fixtures/coverage/kitchen-sink.yaml @@ -4,6 +4,8 @@ openapi: 3.1.0 info: title: Kitchen sink version: '1.0' +security: + - bearer: [] paths: /orders: get: @@ -26,6 +28,9 @@ paths: application/json: schema: { type: array, items: { $ref: '#/components/schemas/Order' } } '400': { description: invalid } + '401': { description: no or invalid token } + '403': { description: not allowed } + '429': { description: slow down } post: operationId: createOrder requestBody: @@ -42,6 +47,7 @@ paths: links: GetOrder: { operationId: getOrder, parameters: { orderId: '$response.body#/id' } } DeleteOrder: { operationId: deleteOrder, parameters: { orderId: '$response.body#/id' } } + UpdateOrder: { operationId: updateOrder, parameters: { orderId: '$response.body#/id' } } '400': { description: invalid } '409': { description: duplicate } '415': { description: unsupported media type } @@ -58,12 +64,41 @@ paths: schema: { $ref: '#/components/schemas/Order' } '400': { description: invalid id } '404': { description: missing } + put: + operationId: updateOrder + parameters: + - { name: If-Match, in: header, schema: { type: string } } + requestBody: + required: true + content: + application/json: + schema: { $ref: '#/components/schemas/OrderInput' } + responses: + '200': + description: updated + content: + application/json: + schema: { $ref: '#/components/schemas/Order' } + '404': { description: missing } + '412': { description: etag mismatch } + '415': { description: unsupported media type } + '418': { description: teapot } delete: operationId: deleteOrder responses: '204': { description: deleted } '404': { description: missing } + /orders/{orderId}/cancel: + parameters: + - { name: orderId, in: path, required: true, schema: { type: string, format: uuid, example: 00000000-0000-4000-8000-000000000009 } } + post: + operationId: cancelOrder + responses: + '202': { description: accepted } + '405': { description: method not allowed } components: + securitySchemes: + bearer: { type: http, scheme: bearer } schemas: OrderInput: type: object diff --git a/tests/unit/error-cases.test.ts b/tests/unit/error-cases.test.ts new file mode 100644 index 0000000..c4a3b71 --- /dev/null +++ b/tests/unit/error-cases.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { errorPlan } from '../../src/generate/error-cases.js'; +import { operationUid, normalizeSpec } from '../../src/change/normalize.js'; +import { validateRegistry } from '../../src/cases/validate.js'; + +/** Stage 6 (docs/SUPPORT_MATRIX.md): documented error responses. */ + +const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); +const ops = buildCatalog(spec.doc); +const op = (key: string) => ops.find((o) => o.key === key)!; +const deps = { scenarios: [{ create: 'createOrder', idFrom: '/id', param: 'orderId', read: 'getOrder', update: 'updateOrder', delete: 'deleteOrder', conflictOn: ['customer'] }] }; + +describe('stage 6: documented error responses', () => { + it('plans only safe triggers; the rest are gaps with codes', () => { + const list = errorPlan({ doc: spec.doc, op: op('GET /orders'), ops, reachable: true, hasUpdatePayload: false, firstWith405: false }); + expect(list.invalidCredentials).toEqual({ headers: { Authorization: 'Bearer api-agent-invalid-token' }, params: {} }); + expect(list.gaps.map((g) => `${g.code} ${g.location}`)).toEqual(['UNCONFIRMED_BUSINESS_RULE response.status#/403', 'UNSAFE_LIVE_CHECK response.status#/429']); + + const cancel = errorPlan({ doc: spec.doc, op: op('POST /orders/{orderId}/cancel'), ops, reachable: false, hasUpdatePayload: false, firstWith405: true }); + expect(cancel.methodNotAllowed).toEqual({ method: 'get' }); // the path defines no GET + + const create = errorPlan({ doc: spec.doc, op: op('POST /orders'), ops, reachable: true, hasUpdatePayload: false, firstWith405: false, role: 'create' }); + expect(create.unsupportedMediaType).toBe(true); + expect(create.conflict).toBeUndefined(); // no conflictOn in a reviewed deps file + expect(create.gaps).toContainEqual(expect.objectContaining({ code: 'UNCONFIRMED_BUSINESS_RULE', location: 'response.status#/409' })); + + const update = errorPlan({ doc: spec.doc, op: op('PUT /orders/{orderId}'), ops, reachable: true, hasUpdatePayload: true, firstWith405: false, role: 'update' }); + expect(update.preconditionFailed).toEqual({ header: 'If-Match', value: '"api-agent-no-such-etag"' }); + expect(update.gaps).toContainEqual(expect.objectContaining({ code: 'UNREACHABLE_RESPONSE_STATUS', location: 'response.status#/418' })); + }); + + it('405 is never sent as an unsafe method: a path with GET gets a gap', () => { + const del = { ...op('DELETE /orders/{orderId}'), responses: [...op('DELETE /orders/{orderId}').responses, { status: '405', contentTypes: [], hasSchema: false }] }; + const r = errorPlan({ doc: spec.doc, op: del, ops, reachable: true, hasUpdatePayload: false, firstWith405: true }); + expect(r.methodNotAllowed).toBeUndefined(); + expect(r.gaps).toContainEqual(expect.objectContaining({ code: 'UNSAFE_LIVE_CHECK', location: 'response.status#/405' })); + }); + + it('generated suites: the same error cases in TypeScript and Python, each with its own ID; cleanup in finally', async () => { + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-err-')); + const res = await generate(spec, ops, { outDir: dir, version: 'test', lang, deps }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const list = operationUid('GET', '/orders'); + const put = operationUid('PUT', '/orders/{}'); + const post = operationUid('POST', '/orders'); + const cancel = operationUid('POST', '/orders/{}/cancel'); + for (const id of [ + `ata:${list}:functional:negative:request.security:invalid-credentials`, + `ata:${cancel}:functional:negative:operation:method-not-allowed`, + `ata:${put}:functional:negative:request.header#/if-match:precondition-failed`, + `ata:${post}:contract:negative:request.content-type:content-type`, + `ata:${put}:contract:negative:request.content-type:content-type`, + ]) expect(ts.reg.cases[id], id).toBeDefined(); + const conflict = Object.entries(ts.reg.cases).find(([id, c]) => c.rule === 'business-rule' && c.polarity === 'negative'); + expect(conflict, 'conflict scenario').toBeDefined(); + expect(ts.reg.scenarios[conflict![1].subjectUid]).toMatchObject({ scenarioType: 'business', primaryOperationUid: post }); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + expect(validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('tests/fixtures/coverage/kitchen-sink.yaml', 'utf8'), 'ks')).errors).toEqual([]); + + const scenario = await ts.read('orders/post/scenarios.spec.ts'); + expect(scenario).toMatch(/const first = await resource\.create\(api, payload\);[\s\S]*expectStatus\(res, \['409'\][\s\S]*finally \{\s*await resource\.removeIfCreated\(api, res\);[\s\S]*finally \{\s*await resource\.remove\(api, first\.id\);/); + expect(await ts.read('orders/get/functional.spec.ts')).toContain(`"Authorization":"Bearer api-agent-invalid-token"`); + const cancelFile = await ts.read('orders-cancel/post/functional.spec.ts'); + expect(cancelFile).toContain(`await request.get('orders/00000000-0000-4000-8000-000000000009/cancel')`); + expect(cancelFile).toContain(`expectStatus(res, ['405']`); + expect(cancelFile).not.toMatch(/request\.(post|put|patch|delete)\(/); // never an unsafe method + const cov = ts.res.coverage.find((c) => c.operation === 'GET /orders')!; + expect(cov.gaps.map((g) => g.code)).toEqual(expect.arrayContaining(['UNCONFIRMED_BUSINESS_RULE', 'UNSAFE_LIVE_CHECK'])); + + const pyFiles = py.res.files.filter((f) => f.endsWith('.py')); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', ...pyFiles], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + expect(await py.read('orders/post/test_scenarios.py')).toContain('def test_second_create_with_the_same_fields_conflicts(api, orders):'); + }); +}); From 7f59010131f3bf9c27829bdc7e056c17a38dc803 Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:43:32 +0100 Subject: [PATCH 6/8] feat(coverage): boundary-valid values, confirmed echoes, sampler fixes (stage 7) - Boundary-valid query values (minimum / maximum inside exclusive bounds and on multipleOf, shortest / longest string without pattern / format): one test and one accepted-value case ID each, TypeScript and Python; registry validation accepts these values (shared boundaries.ts). - deps "echoes": the create test asserts that the named fields come back as sent (only with this reviewed mapping; the spec does not state it). - Sampler: smallest multipleOf inside the bounds; 3.0 boolean and 3.1 numeric exclusive bounds combined with minimum; distinct elements for uniqueItems (or blocked with the reason). - oneOf / anyOf in a sent payload: the branches not exercised are UNCOVERED_VARIANT gaps at their location. Demo API: 61 tests per language (limit=1 and limit=100 pass live); only stats/get/contract fails. Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 34 +++++----- src/cases/validate.ts | 5 +- src/generate/body-cases.ts | 21 ++++++ src/generate/boundaries.ts | 29 +++++++++ src/generate/generate.ts | 8 ++- src/generate/graph.ts | 5 ++ src/generate/python.ts | 8 ++- src/generate/sample.ts | 33 ++++++++-- src/generate/templates.ts | 18 ++++-- tests/api/_support/cases.json | 14 ++++ tests/api/_support/generation-manifest.json | 16 +++-- tests/api/_support/openapi.snapshot.meta.json | 2 +- tests/api/items/get/functional.spec.ts | 10 +++ tests/api/items/post/contract.spec.ts | 3 +- tests/api/items/post/functional.spec.ts | 6 +- .../fixtures/coverage/kitchen-sink.deps.json | 3 +- tests/unit/core.test.ts | 6 +- tests/unit/functional-variants.test.ts | 64 +++++++++++++++++++ 18 files changed, 237 insertions(+), 48 deletions(-) create mode 100644 src/generate/boundaries.ts create mode 100644 tests/unit/functional-variants.test.ts diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 2259c6e..070e1f8 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -62,13 +62,14 @@ Every case is a valid request (each required query / header / cookie parameter w | documented success status | โœ… | | | | create returns an id | โœ… | confirmed chain | | | read returns the created resource (same id) | โœ… | | | -| create response echoes sent fields | โŒ | | 7 | -| GET with each documented query `enum` value | โœ… | one test and one `accepted-value` case ID per value (`request.query#//`), TypeScript and Python; values equal as strings are sent once; max 5 per parameter, 15 per operation | 2 โœ” | -| list contains the created resource | โŒ | | 7 / 8 | -| filter / search / pagination / sort | โ›” | need a confirmed mapping (deps / scenario config) | 7 / 8 | -| boundary-valid values accepted | โŒ | | 7 | -| optional-field variants | โŒ | | 7 | -| response examples as requirements | โ›” | examples are illustrations unless marked | 7 | +| create response returns sent fields | โœ… | only the fields a reviewed deps file names (`echoes`): the spec does not state it | 7 โœ” | +| update โ†’ read returns the new values | โœ… | scenario, marked ASSUMPTION | | +| delete โ†’ read 404 | โœ… | scenario | | +| GET with each documented query `enum` value | โœ… | one test and one `accepted-value` case ID per value | 2 โœ” | +| boundary-valid query values accepted | โœ… | minimum / maximum (inside exclusive bounds, on `multipleOf`), shortest / longest string (no pattern / format, โ‰ค 64 chars); one test and case ID each | 7 โœ” | +| list contains the created resource, filter / search / pagination / sort | โ›” | need a confirmed mapping of list fields and parameters (not in the spec) | 8 (gap) | +| optional-field variants of a create payload | โŒ | | | +| response examples as requirements | โ›” | examples are illustrations, never asserted | | ## Response contract (`src/contract/validator.ts`, `src/contract/contract.py`) @@ -128,16 +129,17 @@ A case is generated only when the request that triggers the error is safe and th | Keyword | State | Limits | Stage | |---|---|---|---| -| `example`, `default`, `enum`, `const` | ๐ŸŸก | first value only | 7 | -| `examples` | ๐ŸŸก | first only | 7 | -| `oneOf` / `anyOf` | ๐ŸŸก | **first variant chosen silently** | 3 / 7 | -| `discriminator` | ๐ŸŸก | blocked (explicit) | 7 | -| `pattern` | ๐ŸŸก | blocked without an example (explicit) | 7 | -| `multipleOf` | โŒ | minimum used, may not be a multiple | 7 | -| formats | ๐ŸŸก | uuid, email, date-time, date, uri, url, hostname, ipv4 | 7 | +| `example`, `default`, `enum`, `const` | ๐ŸŸก | first value only | | +| `examples` | ๐ŸŸก | first only | | +| `oneOf` / `anyOf` | ๐ŸŸก | one branch is sent (the example's, else the first); the others are `UNCOVERED_VARIANT` gaps at their location | 7 โœ” (gap) | +| `discriminator` | ๐ŸŸก | blocked with an explicit reason | | +| `pattern` | ๐ŸŸก | blocked without an example (explicit reason) | | +| `multipleOf` | โœ… | the smallest multiple inside the bounds | 7 โœ” | +| exclusive bounds | โœ… | 3.1 numeric and 3.0 boolean form, combined with `minimum` | 7 โœ” | +| formats | ๐ŸŸก | uuid, email, date-time, date, uri, url, hostname, ipv4 | | | `minItems`, nested objects / arrays | โœ… | | | -| `uniqueItems` | โŒ | copies one value `minItems` times | 7 | -| boundary-valid, optional-field, nullable variants | โŒ | | 7 | +| `uniqueItems` | โœ… | distinct elements (enum values, suffixed strings, stepped numbers); otherwise blocked with the reason | 7 โœ” | +| unique values on a documented 409 | โœ… | suffix that respects enum / const / format / pattern / maxLength | | ## Reporting and CI diff --git a/src/cases/validate.ts b/src/cases/validate.ts index 46fbb68..ec1aedb 100644 --- a/src/cases/validate.ts +++ b/src/cases/validate.ts @@ -4,6 +4,7 @@ import { dirname, join } from 'node:path'; import { normalizePath, type NormOp, type NormSpec } from '../change/normalize.js'; import { CASE_RULE_VOCABULARY_VERSION, parseCaseId } from './ids.js'; import { canonicalJson, fileHash, type Registry } from './registry.js'; +import { boundaryValues } from '../generate/boundaries.js'; /** `registry validate` / `manifest validate` (docs/OPENAPI_CHANGE_TRIGGER.md, "Registry validation"). */ @@ -197,8 +198,8 @@ function checkLocation(o: NormOp, loc: string, rule: string): Finding | undefine if (rawValue !== undefined) { // accepted-value: the value must be one the spec documents for this parameter. const value = String(decodeSegment(rawValue)); - const allowed = Array.isArray(p.schema?.enum) ? p.schema.enum.map(String) : p.schema?.const !== undefined ? [String(p.schema.const)] : []; - return allowed.includes(value) ? undefined : bad(`"${value}" is not a documented value of ${m[1]} "${name}"`); + const allowed = Array.isArray(p.schema?.enum) ? p.schema.enum.map(String) : p.schema?.const !== undefined ? [String(p.schema.const)] : boundaryValues(p.schema).map(String); + return allowed.includes(value) ? undefined : bad(`"${value}" is not a documented value or valid limit of ${m[1]} "${name}"`); } if (rule !== 'required' && rule !== 'not-found' && !ruleFits(p.schema, rule)) return { code: 'INVALID_CASE_RULE_FOR_SCHEMA', pointer: '', reason: `${o.key}: "${rule}" does not apply to ${m[1]} "${name}"` }; return undefined; diff --git a/src/generate/body-cases.ts b/src/generate/body-cases.ts index 4eb4e47..8eb647f 100644 --- a/src/generate/body-cases.ts +++ b/src/generate/body-cases.ts @@ -284,6 +284,27 @@ export function bodyCasesDetailed(doc: OpenApiDoc, rawSchema: any, base: unknown return { cases: kept, gaps, potential, dropped }; } +/** + * oneOf / anyOf in a payload that is sent: one branch is exercised (the example's, or the first), the others are + * reported as UNCOVERED_VARIANT, never dropped silently. + */ +export function compositionGaps(doc: OpenApiDoc, rawSchema: any, value: unknown, path: PathSeg[] = [], depth = 0): CoverageGap[] { + if (depth > 12) return []; + const s = merged(doc, rawSchema); + if (!s || typeof s !== 'object') return []; + const out: CoverageGap[] = []; + for (const k of ['oneOf', 'anyOf']) { + if (Array.isArray(s[k]) && s[k].length > 1) { + out.push({ code: 'UNCOVERED_VARIANT', location: `request.body#${bodyPointer(path)}`, rule: k, reason: `${k}: one of ${s[k].length} branches is sent; ${s[k].length - 1} other(s) are not exercised` }); + } + } + if (Array.isArray(value) && s.items && value.length) out.push(...compositionGaps(doc, s.items, value[0], [...path, ARRAY], depth + 1)); + else if (value && typeof value === 'object' && !Array.isArray(value) && s.properties) { + for (const [prop, sub] of Object.entries(s.properties)) if (prop in (value as object)) out.push(...compositionGaps(doc, sub, (value as any)[prop], [...path, prop], depth + 1)); + } + return out; +} + function isMultipleOf(v: number, m: number): boolean { return Math.abs(v / m - Math.round(v / m)) < 1e-9; } diff --git a/src/generate/boundaries.ts b/src/generate/boundaries.ts new file mode 100644 index 0000000..c813baf --- /dev/null +++ b/src/generate/boundaries.ts @@ -0,0 +1,29 @@ +/** Boundary-valid values shared by the generator (accepted-value cases) and registry validation. */ + +/** + * The valid limits of a scalar schema: minimum / maximum (inside exclusive bounds, on multipleOf) and the shortest / + * longest string (strings without pattern / format, at most 64 characters so the case ID stays readable). + */ +export function boundaryValues(schema: any): (string | number)[] { + const t = Array.isArray(schema?.type) ? schema.type.find((x: string) => x !== 'null') : schema?.type; + const out: (string | number)[] = []; + if (t === 'integer' || t === 'number') { + const m = typeof schema.multipleOf === 'number' && schema.multipleOf > 0 ? schema.multipleOf : t === 'integer' ? 1 : undefined; + const fits = (v: number) => + (t !== 'integer' || Number.isInteger(v)) && + (m === undefined || Math.abs(v / m - Math.round(v / m)) < 1e-9) && + (typeof schema.minimum !== 'number' || v >= schema.minimum) && + (typeof schema.maximum !== 'number' || v <= schema.maximum) && + (typeof schema.exclusiveMinimum !== 'number' || v > schema.exclusiveMinimum) && + (typeof schema.exclusiveMaximum !== 'number' || v < schema.exclusiveMaximum) && + !(schema.exclusiveMinimum === true && v === schema.minimum) && + !(schema.exclusiveMaximum === true && v === schema.maximum); + const lo = typeof schema.minimum === 'number' ? schema.minimum : typeof schema.exclusiveMinimum === 'number' && m ? Math.floor(schema.exclusiveMinimum / m + 1) * m : undefined; + const hi = typeof schema.maximum === 'number' ? schema.maximum : typeof schema.exclusiveMaximum === 'number' && m ? Math.ceil(schema.exclusiveMaximum / m - 1) * m : undefined; + for (const v of [lo, hi]) if (v !== undefined && fits(v) && !out.includes(v)) out.push(v); + } + if (t === 'string' && !schema.pattern && !schema.format) { + for (const n of [schema.minLength, schema.maxLength]) if (typeof n === 'number' && n > 0 && n <= 64 && !out.includes('x'.repeat(n))) out.push('x'.repeat(n)); + } + return out; +} diff --git a/src/generate/generate.ts b/src/generate/generate.ts index ddf3b34..926be40 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -12,7 +12,7 @@ import { assignCaseIds, type CaseRecord, type ScenarioDefinition } from '../case import { buildRegistry, canonicalJson, fileHash, readRegistry, resolveOperationUids } from '../cases/registry.js'; import { headRevision } from '../change/baseline.js'; import { isUrl } from '../change/network.js'; -import { bodyCasesDetailed, type CoverageGap } from './body-cases.js'; +import { bodyCasesDetailed, compositionGaps, type CoverageGap } from './body-cases.js'; import { paramCasesDetailed, sendable } from './param-cases.js'; import { errorPlan } from './error-cases.js'; import { bodyCases, documentedRejections, nonexistentIdExpr, type NegCase } from './negative.js'; @@ -324,6 +324,10 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const ids = assignCaseIds({ op, chain: plan?.chain, positive: input.positive, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, scenarios: scenarioCases(input), queryVariants: variants, errors }, 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) : []; // Response bodies the validator cannot check: said explicitly, never passed silently. const responseGaps: CoverageGap[] = op.responses.flatMap((resp) => resp.contentTypes.flatMap((ct): CoverageGap[] => { @@ -334,7 +338,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp return []; }), ); - coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: [...bodyGaps, ...errors.gaps, ...responseGaps], ...(bodyStats ? { bodyCases: bodyStats } : {}) }); + coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps], ...(bodyStats ? { bodyCases: bodyStats } : {}) }); const render: Record string> = py ? { functional: renderPyFunctional, contract: renderPyContract, scenario: renderPyScenarios } : { functional: renderFunctional, contract: renderContract, scenario: renderScenarios }; diff --git a/src/generate/graph.ts b/src/generate/graph.ts index 0c65978..8becfcc 100644 --- a/src/generate/graph.ts +++ b/src/generate/graph.ts @@ -21,6 +21,8 @@ export interface CrudChain { fill?: FillRule[]; /** Create body fields a reviewed deps file names as unique: the same values twice must give the documented 409. */ conflictOn?: string[]; + /** Create body fields the create response returns unchanged (a reviewed mapping): asserted in the create test. */ + echoes?: string[]; } export interface FillRule { @@ -50,6 +52,8 @@ export interface DepsFile { fill?: Record; /** Fields whose repeated values make create answer 409 (a reviewed business rule). */ conflictOn?: string[]; + /** Fields the create response returns as sent. */ + echoes?: string[]; }[]; } @@ -74,6 +78,7 @@ export function findChains(doc: OpenApiDoc, ops: Operation[], deps?: DepsFile): source: 'deps file (human-confirmed)', ...(s.fill ? { fill: Object.entries(s.fill).map(([field, f]) => ({ field, fromId: f?.from, from: byId.get(f?.from), pointer: f?.pointer })) } : {}), ...(Array.isArray(s.conflictOn) && s.conflictOn.length ? { conflictOn: s.conflictOn.map(String) } : {}), + ...(Array.isArray(s.echoes) && s.echoes.length ? { echoes: s.echoes.map(String) } : {}), }); } diff --git a/src/generate/python.ts b/src/generate/python.ts index ec4bb27..5238808 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -373,7 +373,7 @@ function pyPositive(s: SuiteInput, name: string, assert: (indent: string) => str return [POS, `def ${name}(api, contract):`, ` res = api.${op.method}(${pathExpr(op)}${pyRequired(op)})`, ...assert(' '), '', '']; } if (role === 'create') { - return [POS, `def ${name}(api, contract, ${res}):`, ` res = api.${op.method}(${pathExpr(op)}, json=${res}.new_create_payload()${pyRequired(op)})`, ' try:', ...assert(' '), ' finally:', ` ${res}.remove_if_created(res)`, '', '']; + return [POS, `def ${name}(api, contract, ${res}):`, ` payload = ${res}.new_create_payload()`, ` res = api.${op.method}(${pathExpr(op)}, json=payload${pyRequired(op)})`, ' try:', ...assert(' '), ' finally:', ` ${res}.remove_if_created(res)`, '', '']; } const body = role === 'update' ? `, json=${res}.new_update_payload()` : ''; // created_ removes the resource after the test (best effort: a deleted one is already gone). @@ -424,7 +424,11 @@ export function renderPyFunctional(s: SuiteInput, meta: Meta): string { L.push( ...pyPositive(s, names[role ?? 'none'], (i) => { const a = [`${i}${assertSuccess(op)}`]; - if (role === 'create') a.push(`${i}assert read_pointer(res.json(), ${ptr}) not in (None, ""), "identifier at $response.body#${plan!.chain.idPointer}"`); + if (role === 'create') { + a.push(`${i}assert read_pointer(res.json(), ${ptr}) not in (None, ""), "identifier at $response.body#${plan!.chain.idPointer}"`); + // Fields a reviewed deps file says the create response returns as sent. + for (const field of plan!.chain.echoes ?? []) a.push(`${i}assert read_pointer(res.json(), ${str('/' + field.replace(/~/g, '~0').replace(/\//g, '~1'))}) == payload[${str(field)}], ${str(`${field} returned as sent`)}`); + } if (role === 'read') a.push(`${i}assert str(read_pointer(res.json(), ${ptr})) == created_${res}, "same resource"`); return a; }, s.ids?.functional.success), diff --git a/src/generate/sample.ts b/src/generate/sample.ts index 6b4d20f..2cc8fff 100644 --- a/src/generate/sample.ts +++ b/src/generate/sample.ts @@ -49,7 +49,8 @@ export function sampleFromSchema(doc: OpenApiDoc, schema: any, path = '$', depth const alt = schema.oneOf ?? schema.anyOf; if (Array.isArray(alt)) { if (schema.discriminator) return { ok: false, reason: `${path}: polymorphic body with discriminator, choose the variant explicitly` }; - return sampleFromSchema(doc, alt[0], `${path}(variant 0)`, depth + 1); + // The first variant is used; the others are not silently dropped: the source names how many stay uncovered. + return sampleFromSchema(doc, alt[0], `${path}(variant 0 of ${alt.length})`, depth + 1); } const type = Array.isArray(schema.type) ? schema.type.find((t: string) => t !== 'null') : schema.type ?? (schema.properties ? 'object' : undefined); @@ -80,7 +81,20 @@ export function sampleFromSchema(doc: OpenApiDoc, schema: any, path = '$', depth const min = schema.minItems ?? 0; if (!min) return { ok: true, value: [], sources: [`${path}: empty array (no minItems)`] }; const r = sampleFromSchema(doc, schema.items, `${path}[]`, depth + 1); - return r.ok ? { ok: true, value: Array.from({ length: min }, () => r.value), sources: r.sources } : r; + if (!r.ok) return r; + if (!schema.uniqueItems || min < 2) return { ok: true, value: Array.from({ length: min }, () => r.value), sources: r.sources }; + // uniqueItems: distinct elements, derived only where it cannot break the item's own constraints. + const item = schema.items?.$ref ? resolvePointer(doc, schema.items.$ref.slice(1)).node : schema.items; + const values: unknown[] = []; + if (Array.isArray(item?.enum) && item.enum.length >= min) values.push(...item.enum.slice(0, min)); + else if (typeof r.value === 'string' && !item?.pattern && !item?.format && !item?.enum && (item?.maxLength ?? Infinity) >= String(r.value).length + 3) { + for (let i = 0; i < min; i++) values.push(i ? `${r.value}-${i}` : r.value); + } else if (typeof r.value === 'number' && !item?.enum) { + const step = typeof item?.multipleOf === 'number' ? item.multipleOf : 1; + for (let i = 0; i < min; i++) values.push((r.value as number) + i * step); + if (typeof item?.maximum === 'number' && (values[min - 1] as number) > item.maximum) return { ok: false, reason: `${path}: ${min} unique items do not fit under maximum ${item.maximum}` }; + } else return { ok: false, reason: `${path}: cannot derive ${min} distinct items (uniqueItems)` }; + return { ok: true, value: values, sources: [...r.sources, `${path}: ${min} distinct items (uniqueItems)`] }; } case 'string': { if (schema.format && FORMAT_VALUES[schema.format] !== undefined) return { ok: true, value: FORMAT_VALUES[schema.format], sources: [`${path}: format ${schema.format}`] }; @@ -93,10 +107,17 @@ export function sampleFromSchema(doc: OpenApiDoc, schema: any, path = '$', depth } case 'integer': case 'number': { - const lo = schema.minimum ?? (schema.exclusiveMinimum !== undefined ? Number(schema.exclusiveMinimum) + 1 : 1); - const hi = schema.maximum ?? Infinity; - if (lo > hi) return { ok: false, reason: `${path}: minimum > maximum` }; - return { ok: true, value: type === 'integer' ? Math.ceil(lo) : lo, sources: [`${path}: minimal number`] }; + // 3.1: exclusiveMinimum is a number; 3.0: a boolean that makes the minimum itself invalid. + const bounds = [ + ...(typeof schema.minimum === 'number' ? [schema.minimum + (schema.exclusiveMinimum === true ? 1 : 0)] : []), + ...(typeof schema.exclusiveMinimum === 'number' ? [schema.exclusiveMinimum + 1] : []), + ]; + let lo = bounds.length ? Math.max(...bounds) : 1; + if (type === 'integer') lo = Math.ceil(lo); + if (typeof schema.multipleOf === 'number' && schema.multipleOf > 0) lo = Math.ceil(lo / schema.multipleOf - 1e-9) * schema.multipleOf; + const hi = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum - Number.EPSILON : schema.exclusiveMaximum === true ? schema.maximum - Number.EPSILON : schema.maximum ?? Infinity; + if (lo > hi) return { ok: false, reason: `${path}: no ${type} satisfies the bounds${schema.multipleOf ? ` and multipleOf ${schema.multipleOf}` : ''}` }; + return { ok: true, value: lo, sources: [`${path}: minimal ${type}${schema.multipleOf ? ` (multiple of ${schema.multipleOf})` : ''}`] }; } case 'boolean': return { ok: true, value: false, sources: [`${path}: boolean false`] }; diff --git a/src/generate/templates.ts b/src/generate/templates.ts index 12def32..6a537c0 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -5,6 +5,7 @@ import { apiCall, type ApiRef } from './api-objects.js'; import type { SuiteCaseIds } from '../cases/assign.js'; import { requiredRequest, type ParamRequest } from './param-cases.js'; import type { ErrorPlan } from './error-cases.js'; +import { boundaryValues } from './boundaries.js'; /** Payloads and assumptions for one confirmed resource chain. */ export interface ChainPlan { @@ -73,12 +74,14 @@ export function optionsWith(op: Operation, inner?: string): string | undefined { return fields.length ? `{ ${fields.join(', ')} }` : undefined; } -/** Safe query variations: only values explicitly allowed by the schema. */ +/** Safe query variations: only values explicitly allowed by the schema (enum values, else the valid limits). */ export function queryVariants(op: Operation): Array<{ name: string; value: string | number | boolean }> { if (op.method !== 'get') return []; return op.params.filter((p) => p.in === 'query' && !p.required).flatMap((p) => { - const schema = p.schema ?? {}; - const values = Array.isArray(schema.enum) ? schema.enum : []; + const schema: any = p.schema ?? {}; + const values: unknown[] = Array.isArray(schema.enum) ? [...schema.enum] : []; + // Boundary-valid values: the documented limits themselves must be accepted. + if (!values.length) values.push(...boundaryValues(schema)); const kept = values.filter((v): v is string | number | boolean => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'); // One physical test per value, each with its own case ID: values equal as strings would share an ID. const unique = kept.filter((v, i) => kept.findIndex((x) => String(x) === String(v)) === i); @@ -295,7 +298,8 @@ function positiveTest(s: SuiteInput, title: string, assert: (indent: string) => if (role === 'create') { return [ ` test(${q(title)}, ${POS}, async ({ api }) => {`, - ` const res = await ${call('id', hasFill(plan) ? '{ data: await resource.newCreatePayload(api) }' : '{ data: resource.newCreatePayload() }')};`, + ` const payload = ${hasFill(plan) ? 'await resource.newCreatePayload(api)' : 'resource.newCreatePayload()'};`, + ` const res = await ${call('id', '{ data: payload }')};`, ` try {`, ...assert(' '), ` } finally {`, @@ -365,7 +369,11 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { L.push( ...positiveTest(s, titles[role ?? 'none'], (i) => { const a = [`${i}${expectSuccess(op)}`]; - if (role === 'create') a.push(`${i}const id = readPointer(await res.json().catch(() => undefined), ${q(chain!.idPointer)});`, `${i}expect(String(id ?? ''), 'identifier at $response.body#${chain!.idPointer}').not.toBe('');`); + if (role === 'create') { + a.push(`${i}const created = await res.json().catch(() => undefined);`, `${i}const id = readPointer(created, ${q(chain!.idPointer)});`, `${i}expect(String(id ?? ''), 'identifier at $response.body#${chain!.idPointer}').not.toBe('');`); + // Fields a reviewed deps file says the create response returns as sent. + for (const field of chain!.echoes ?? []) a.push(`${i}expect(readPointer(created, ${q('/' + field.replace(/~/g, '~0').replace(/\//g, '~1'))}), ${q(`${field} returned as sent`)}).toEqual((payload as Record)[${q(field)}]);`); + } if (role === 'read') a.push(`${i}expect(String(readPointer(await res.json().catch(() => undefined), ${q(chain!.idPointer)})), 'same resource').toBe(id);`); return a; }, s.ids?.functional.success), diff --git a/tests/api/_support/cases.json b/tests/api/_support/cases.json index 91f1646..71e8866 100644 --- a/tests/api/_support/cases.json +++ b/tests/api/_support/cases.json @@ -40,6 +40,20 @@ "subjectUid": "op_4PIO72ZI3SIY", "suiteType": "functional" }, + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/100:accepted-value": { + "location": "request.query#/limit/100", + "polarity": "positive", + "rule": "accepted-value", + "subjectUid": "op_4PIO72ZI3SIY", + "suiteType": "functional" + }, + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/1:accepted-value": { + "location": "request.query#/limit/1", + "polarity": "positive", + "rule": "accepted-value", + "subjectUid": "op_4PIO72ZI3SIY", + "suiteType": "functional" + }, "ata:op_7P2UH7UKQRHC:contract:positive:response.body#:schema": { "covers": [ "contract:positive:response.content-type#/application~1json:documented", diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index 752226c..a95fcdf 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -1,5 +1,5 @@ { - "caseRegistryHash": "51f82bffa7438b9e1f7595daf8ca206bbf944b446f15c35a87d78b4f3310b879", + "caseRegistryHash": "132c3ea625d3120236f76ce24950359b96d5a04047a9aa10b24fe127144680bd", "files": { "_support/api/generated/AdminApiBase.ts": { "ownership": "generated", @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "02321c2de281b2ca60e29bca3a07b8ce21294ad4fe4a77491c43f0b397091cf9" + "sha256": "dbc27d1b465c4c9fffd068d92bc28b15bde50e5f192ba77c9e6d8e8fe91c51bb" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -166,13 +166,15 @@ }, "items/get/functional.spec.ts": { "caseIds": [ - "ata:op_4PIO72ZI3SIY:functional:positive:operation:documented-success" + "ata:op_4PIO72ZI3SIY:functional:positive:operation:documented-success", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/1:accepted-value", + "ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/100:accepted-value" ], "operationUids": [ "op_4PIO72ZI3SIY" ], "ownership": "generated", - "sha256": "107a7657f2b7af3b2f0393ad86507cc5645d16e0d09812b30afedb849edf7d99", + "sha256": "5e1cb6b000284b6bfcf733bea1a1d3a451fc435107ebf490279a09b14ec190ff", "suiteType": "functional" }, "items/patch-by-id/contract.spec.ts": { @@ -252,7 +254,7 @@ "op_EDRRXKOK26ZL" ], "ownership": "generated", - "sha256": "c14bca7ba83da65165b9631315895ad5e9323a98af6283aaf043697d783c738b", + "sha256": "55aa00d7008175ecca10ec2966419c00b4b988eb7e32daec3dc6d6942c68e719", "suiteType": "contract" }, "items/post/functional.spec.ts": { @@ -264,7 +266,7 @@ "op_EDRRXKOK26ZL" ], "ownership": "generated", - "sha256": "e1ceb3800a680333b4a45c29980c36d1245b705c8da20fb3dc3de0ae2fef5def", + "sha256": "12e7382980e8ed311af492b7662241d72acf59e4c321ee91266899029447b9b0", "suiteType": "functional" }, "items/post/scenarios.spec.ts": { @@ -354,7 +356,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "ea9aa19720af422a38924d9284f0e7190b6d5337", + "revision": "c0234b4bfb54752c38970fe2107b785bb796dc89", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index 320485a..c7d0810 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "ea9aa19720af422a38924d9284f0e7190b6d5337", + "capturedRevision": "c0234b4bfb54752c38970fe2107b785bb796dc89", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/api/items/get/functional.spec.ts b/tests/api/items/get/functional.spec.ts index f9ff2ea..506750a 100644 --- a/tests/api/items/get/functional.spec.ts +++ b/tests/api/items/get/functional.spec.ts @@ -11,4 +11,14 @@ test.describe('GET /items ยท functional', { tag: '@functional' }, () => { const res = await publicApi.items.listItems(); expect(res.status(), 'documented success status of listItems').toBe(200); }); + + test('accepts documented limit=1', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/1:accepted-value' } }, async ({ publicApi }) => { + const res = await publicApi.items.listItems({ params: {"limit":1} }); + expect(res.status(), 'documented success status of listItems').toBe(200); + }); + + test('accepts documented limit=100', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_4PIO72ZI3SIY:functional:positive:request.query#/limit/100:accepted-value' } }, async ({ publicApi }) => { + const res = await publicApi.items.listItems({ params: {"limit":100} }); + expect(res.status(), 'documented success status of listItems').toBe(200); + }); }); diff --git a/tests/api/items/post/contract.spec.ts b/tests/api/items/post/contract.spec.ts index a66c5cb..902c529 100644 --- a/tests/api/items/post/contract.spec.ts +++ b/tests/api/items/post/contract.spec.ts @@ -13,7 +13,8 @@ const rejection = ["400"]; // documented in the spec test.describe('POST /items ยท contract', { tag: '@contract' }, () => { test('success response matches the documented contract', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_UPN7JLUXYUZ7:contract:positive:response.body#:schema' } }, async ({ api }) => { - const res = await api.items.createItem({ data: resource.newCreatePayload() }); + const payload = resource.newCreatePayload(); + const res = await api.items.createItem({ data: payload }); try { await expectContract(res, 'post', '/items'); } finally { diff --git a/tests/api/items/post/functional.spec.ts b/tests/api/items/post/functional.spec.ts index 66a6f56..c7cdb82 100644 --- a/tests/api/items/post/functional.spec.ts +++ b/tests/api/items/post/functional.spec.ts @@ -10,10 +10,12 @@ import * as resource from '../../_support/items.resource.js'; test.describe('POST /items ยท functional', { tag: '@functional' }, () => { test('creates a resource from the documented example payload', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:op_UPN7JLUXYUZ7:functional:positive:operation:documented-success' } }, async ({ api }) => { - const res = await api.items.createItem({ data: resource.newCreatePayload() }); + const payload = resource.newCreatePayload(); + const res = await api.items.createItem({ data: payload }); try { expect(res.status(), 'documented success status of createItem').toBe(201); - const id = readPointer(await res.json().catch(() => undefined), '/id'); + const created = await res.json().catch(() => undefined); + const id = readPointer(created, '/id'); expect(String(id ?? ''), 'identifier at $response.body#/id').not.toBe(''); } finally { await resource.removeIfCreated(api, res); diff --git a/tests/fixtures/coverage/kitchen-sink.deps.json b/tests/fixtures/coverage/kitchen-sink.deps.json index cb6ed57..e28e8f3 100644 --- a/tests/fixtures/coverage/kitchen-sink.deps.json +++ b/tests/fixtures/coverage/kitchen-sink.deps.json @@ -7,7 +7,8 @@ "read": "getOrder", "update": "updateOrder", "delete": "deleteOrder", - "conflictOn": ["customer"] + "conflictOn": ["customer"], + "echoes": ["total", "status"] } ] } diff --git a/tests/unit/core.test.ts b/tests/unit/core.test.ts index 542ff84..cdad314 100644 --- a/tests/unit/core.test.ts +++ b/tests/unit/core.test.ts @@ -396,7 +396,7 @@ describe('unique values for operations that document 409', () => { expect(helper).toContain('POST /items documents 409 (conflict): name get a unique suffix'); expect(helper).toContain('export const newCreatePayload = () => unique(createPayload, {"name":100});'); expect(helper).toContain('data: unknown = newCreatePayload()'); - expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('{ data: resource.newCreatePayload() }'); + expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('const payload = resource.newCreatePayload();'); const scenario = await readFileP(joinP(dir, 'items/patch-by-id/scenarios.spec.ts'), 'utf8'); expect(scenario).toMatch(/const payload = resource\.newUpdatePayload\(\);[\s\S]*toMatchObject\(payload\);/); @@ -404,7 +404,7 @@ describe('unique values for operations that document 409', () => { await generate({ ...demo, doc: d } as any, buildCatalog(d), { outDir: py, version: 'test', lang: 'python' }); const pyHelper = await readFileP(joinP(py, '_support/items_resource.py'), 'utf8'); expect(pyHelper).toContain('UNIQUE_CREATE = {\n "name": 100,\n}'); - expect(await readFileP(joinP(py, 'items/post/test_functional.py'), 'utf8')).toContain('json=items.new_create_payload()'); + expect(await readFileP(joinP(py, 'items/post/test_functional.py'), 'utf8')).toContain('payload = items.new_create_payload()'); }); }); @@ -490,7 +490,7 @@ describe('deps "fill": values from existing data', () => { expect(helper).toContain("payload['name'] = readPointer(await source0.json(), '/status');"); expect(helper).toContain('unique(createPayload, {})'); // name is filled, not suffixed, despite the documented 409 expect(helper).toContain('data ??= await newCreatePayload(api);'); - expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('{ data: await resource.newCreatePayload(api) }'); + expect(await readFileP(joinP(dir, 'items/post/functional.spec.ts'), 'utf8')).toContain('const payload = await resource.newCreatePayload(api);'); const py = await mkdtemp(joinP(tmpdir(), 'ata-fill-py-')); await generate(spec, buildCatalog(d), { outDir: py, version: 'test', lang: 'python', deps: deps({ name: { from: 'getHealth', pointer: '/status' } }) }); diff --git a/tests/unit/functional-variants.test.ts b/tests/unit/functional-variants.test.ts new file mode 100644 index 0000000..9e8e5d8 --- /dev/null +++ b/tests/unit/functional-variants.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { boundaryValues } from '../../src/generate/boundaries.js'; +import { sampleFromSchema } from '../../src/generate/sample.js'; +import { operationUid } from '../../src/change/normalize.js'; + +/** Stage 7 (docs/SUPPORT_MATRIX.md): functional assertions and valid-data variants. */ + +const spec = await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml'); +const ops = buildCatalog(spec.doc); +const deps = JSON.parse(await readFile('tests/fixtures/coverage/kitchen-sink.deps.json', 'utf8')); + +describe('stage 7: valid limits, sampler fixes, confirmed functional assertions', () => { + it('boundary-valid values respect exclusive bounds, multipleOf and lengths', () => { + expect(boundaryValues({ type: 'integer', minimum: 1, maximum: 50 })).toEqual([1, 50]); + expect(boundaryValues({ type: 'integer', exclusiveMinimum: 0, exclusiveMaximum: 10 })).toEqual([1, 9]); + expect(boundaryValues({ type: 'number', minimum: 0.5, maximum: 10, multipleOf: 0.5 })).toEqual([0.5, 10]); + expect(boundaryValues({ type: 'integer', minimum: 1, maximum: 10, multipleOf: 4 })).toEqual([]); // no limit is itself a multiple + expect(boundaryValues({ type: 'string', minLength: 2, maxLength: 5 })).toEqual(['xx', 'xxxxx']); + expect(boundaryValues({ type: 'string', minLength: 2, pattern: '^a+$' })).toEqual([]); // never break a pattern + expect(boundaryValues({ type: 'string', maxLength: 500 })).toEqual([]); // too long for a readable case ID + }); + + it('sampler: multipleOf, exclusive bounds (3.0 and 3.1), distinct items for uniqueItems', () => { + const s = (schema: any) => (sampleFromSchema({}, schema) as any).value; + expect(s({ type: 'number', minimum: 1, multipleOf: 0.75 })).toBe(1.5); + expect(s({ type: 'integer', minimum: 3, exclusiveMinimum: true })).toBe(4); + expect(s({ type: 'integer', minimum: 1, exclusiveMinimum: 5 })).toBe(6); + expect(s({ type: 'array', minItems: 3, uniqueItems: true, items: { type: 'string' } })).toEqual(['api-agent', 'api-agent-1', 'api-agent-2']); + expect(s({ type: 'array', minItems: 2, uniqueItems: true, items: { type: 'integer', minimum: 5 } })).toEqual([5, 6]); + expect(sampleFromSchema({}, { type: 'array', minItems: 3, uniqueItems: true, items: { type: 'boolean' } }).ok).toBe(false); + expect((sampleFromSchema({}, { type: 'integer', minimum: 1, maximum: 3, multipleOf: 5 }) as any).ok).toBe(false); + }); + + it('generated: one accepted-value test per limit, echoes from the deps file, the uncovered oneOf variant as a gap; TS and Python agree', async () => { + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-fv-')); + const res = await generate(spec, ops, { outDir: dir, version: 'test', lang, deps, maxCases: 500 }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const list = operationUid('GET', '/orders'); + for (const v of ['1', '50']) expect(ts.reg.cases[`ata:${list}:functional:positive:request.query#/limit/${v}:accepted-value`], v).toBeDefined(); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + + const create = await ts.read('orders/post/functional.spec.ts'); + expect(create).toContain(`expect(readPointer(created, '/total'), 'total returned as sent').toEqual((payload as Record)['total']);`); + expect(create).toContain(`expect(readPointer(created, '/status'), 'status returned as sent')`); + expect(await py.read('orders/post/test_functional.py')).toContain(`assert read_pointer(res.json(), "/total") == payload["total"], "total returned as sent"`); + + const cov = ts.res.coverage.find((c) => c.operation === 'POST /orders')!; + expect(cov.gaps).toContainEqual(expect.objectContaining({ code: 'UNCOVERED_VARIANT', location: 'request.body#/payment' })); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', ...py.res.files.filter((f) => f.endsWith('.py'))], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); +}); From 91b54559edf4b02cafec7503f06277ea1ce7a21f Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:50:22 +0100 Subject: [PATCH 7/8] feat(coverage): reviewed business scenarios and repeated delete (stage 8) - src/scenarios/dsl.ts + schemas/scenarios.schema.json: a reviewed scenarios file (--scenarios): steps with phases, path / query params and bodies with {var} values saved by earlier steps (JSON pointers), the documented status each step must get, cleanup steps. - Strict validation (also `scenarios validate --spec`): operations and parameters exist, statuses documented, variables saved before use, a writing scenario has cleanup, the primary is an action, unique IDs. - Generated in the primary operation's scenarios file, TypeScript and Python: steps in order, cleanup in finally with failures reported. The scenarioUid comes from the external id (never the title); registry definition with steps and externalId. - CRUD: deleting the same resource twice gets the documented 404. - demo-api/scenarios.json (positive and negative) runs in CI in both languages. Demo API: 64 tests per language, both scenarios pass live, nothing left behind; only stats/get/contract fails. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 4 +- demo-api/scenarios.json | 27 ++++ docs/SUPPORT_MATRIX.md | 27 ++-- schemas/scenarios.schema.json | 40 ++++++ src/cases/assign.ts | 23 ++- src/cli.ts | 30 +++- src/contract/contract.py | 16 +++ src/generate/generate.ts | 7 +- src/generate/python.ts | 89 +++++++++++- src/generate/templates.ts | 100 ++++++++++++- src/scenarios/dsl.ts | 133 ++++++++++++++++++ tests/api/_support/cases.json | 98 +++++++++++++ tests/api/_support/contract-assert.ts | 15 ++ tests/api/_support/generation-manifest.json | 25 +++- tests/api/_support/openapi.snapshot.meta.json | 2 +- .../api/items/delete-by-id/scenarios.spec.ts | 13 ++ tests/api/items/get-by-id/scenarios.spec.ts | 53 +++++++ tests/unit/error-cases.test.ts | 2 +- tests/unit/scenarios.test.ts | 80 +++++++++++ 19 files changed, 745 insertions(+), 39 deletions(-) create mode 100644 demo-api/scenarios.json create mode 100644 schemas/scenarios.schema.json create mode 100644 src/scenarios/dsl.ts create mode 100644 tests/api/items/get-by-id/scenarios.spec.ts create mode 100644 tests/unit/scenarios.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5702811..6271c87 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,7 +64,7 @@ jobs: ' - name: Generate tests (resource/method/functional|contract|scenarios) and run them once - run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --allow-write --run -o reports/generate --fail-on never + run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run -o reports/generate --fail-on never - name: Self-check - generated suite fails only on the known defect run: | @@ -89,7 +89,7 @@ jobs: - name: Generate Python tests (pytest + requests) and run them once run: | pip install pytest requests jsonschema - npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never + npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never node -e ' const r = require("./reports/generate-python/report.json"); const bad = r.generated.scenarios.filter(s => s.status === "CONTRACT_MISMATCH" || s.status === "TEST_FAILURE").map(s => s.name); diff --git a/demo-api/scenarios.json b/demo-api/scenarios.json new file mode 100644 index 0000000..e5c1af5 --- /dev/null +++ b/demo-api/scenarios.json @@ -0,0 +1,27 @@ +{ + "scenarios": [ + { + "id": "items.read-created", + "title": "an item that was just created can be read by its id", + "polarity": "positive", + "primary": "read", + "steps": [ + { "name": "create", "operationId": "createItem", "phase": "setup", "body": { "name": "Scenario item", "price": 5, "tags": ["scenario"] }, "expect": "201", "save": { "itemId": "/id" } }, + { "name": "read", "operationId": "getItem", "phase": "action", "params": { "itemId": "{itemId}" }, "expect": "200" }, + { "operationId": "deleteItem", "phase": "cleanup", "params": { "itemId": "{itemId}" } } + ] + }, + { + "id": "items.gone-after-delete", + "title": "an item that was deleted cannot be read any more", + "polarity": "negative", + "primary": "read", + "steps": [ + { "name": "create", "operationId": "createItem", "phase": "setup", "body": { "name": "Scenario item", "price": 5 }, "expect": "201", "save": { "itemId": "/id" } }, + { "name": "delete", "operationId": "deleteItem", "phase": "setup", "params": { "itemId": "{itemId}" }, "expect": "204" }, + { "name": "read", "operationId": "getItem", "phase": "action", "params": { "itemId": "{itemId}" }, "expect": "404" }, + { "operationId": "deleteItem", "phase": "cleanup", "params": { "itemId": "{itemId}" } } + ] + } + ] +} diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 070e1f8..ee6aa0f 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -111,19 +111,22 @@ A case is generated only when the request that triggers the error is safe and th | 429 (rate limit) | โ›” | `UNSAFE_LIVE_CHECK`: never exercised (opt-in with a request budget is not implemented) | 6 โœ” (gap) | | other documented 4xx | โ›” | `UNREACHABLE_RESPONSE_STATUS` | 6 โœ” (gap) | -## Scenarios (`scenarios.spec.ts`) +## Scenarios (`scenarios.spec.ts`, `src/scenarios/dsl.ts`) -| Flow | State | Stage | -|---|---|---| -| create โ†’ read | โœ… | | -| create โ†’ update โ†’ read | โœ… (marked ASSUMPTION) | | -| create โ†’ delete โ†’ read 404 | โœ… | | -| create โ†’ list / search / filter | โŒ | 8 | -| create โ†’ duplicate create โ†’ 409 | โœ… (deps `conflictOn`) | 6 โœ” | -| repeated delete, update / delete unknown | โŒ | 8 | -| login / refresh โ†’ authorized request | โŒ | 8 | -| parent โ†’ child, state transitions, idempotency key, bounded polling | โ›” | need the reviewed scenario file | 8 | -| business scenario config with schema validation | โŒ | 8 | +CRUD flows come from confirmed dependencies (OpenAPI links or the deps file). Business flows are never guessed from paths: they come from a reviewed scenarios file (`--scenarios`, JSON Schema `schemas/scenarios.schema.json`, `scenarios validate --spec`): steps in order with phases, parameters and bodies with `{var}` values saved by earlier steps, the documented status each step must get, and cleanup steps run in `finally` (failures reported). The case ID comes from the scenario's external `id`, never from the title. + +| Flow | State | Source / limits | Stage | +|---|---|---|---| +| create โ†’ read | โœ… | confirmed chain | | +| create โ†’ update โ†’ read | โœ… | confirmed chain; marked ASSUMPTION | | +| create โ†’ delete โ†’ read 404 | โœ… | confirmed chain | | +| delete โ†’ repeated delete โ†’ 404 | โœ… | confirmed chain, delete documents 404 | 8 โœ” | +| create โ†’ duplicate create โ†’ 409 | โœ… | deps `conflictOn` | 6 โœ” | +| update / delete unknown resource โ†’ 404 | โœ… | functional `not-found` cases | | +| business flows (login โ†’ request, parent โ†’ child, state transitions, negative transitions, idempotency key, โ€ฆ) | โœ… | reviewed scenarios file; strict validation: operations exist, parameters exist, every non-cleanup step names a documented status, every `{var}` is saved earlier, a writing scenario has cleanup, the primary is an action, IDs unique | 8 โœ” | +| create โ†’ list / search / filter, pagination, sort | ๐ŸŸก | as a reviewed business scenario; no automatic derivation (list fields and filters are not in the spec) | 8 โœ” | +| eventual consistency with bounded polling | โŒ | the scenario DSL has no retry / polling step yet | | +| refresh token โ†’ request | ๐ŸŸก | as a reviewed scenario with explicit steps | 8 โœ” | ## Valid data (`src/generate/sample.ts`) diff --git a/schemas/scenarios.schema.json b/schemas/scenarios.schema.json new file mode 100644 index 0000000..15967fb --- /dev/null +++ b/schemas/scenarios.schema.json @@ -0,0 +1,40 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://github.com/testomut/api-test-agent/schemas/scenarios.schema.json", + "title": "Reviewed business scenarios", + "description": "Input of `generate --scenarios` and `scenarios validate`. Business flows are never guessed from paths; a human writes and reviews this file. `scenarios validate --spec` also checks it against the spec (operations, parameters, documented statuses, saved values, cleanup).", + "type": "object", + "additionalProperties": false, + "required": ["scenarios"], + "properties": { + "scenarios": { "type": "array", "items": { "$ref": "#/definitions/scenario" } } + }, + "definitions": { + "scenario": { + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "polarity", "primary", "steps"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$", "description": "Stable external ID: the scenarioUid is derived from it, never from the title or the steps." }, + "title": { "type": "string", "minLength": 1 }, + "polarity": { "enum": ["positive", "negative"] }, + "primary": { "type": "string", "description": "Name or operationId of the action step under test." }, + "steps": { "type": "array", "minItems": 2, "items": { "$ref": "#/definitions/step" } } + } + }, + "step": { + "type": "object", + "additionalProperties": false, + "required": ["operationId", "phase"], + "properties": { + "name": { "type": "string" }, + "operationId": { "type": "string" }, + "phase": { "enum": ["setup", "action", "assertion", "cleanup"] }, + "params": { "type": "object", "description": "Path and query parameters by name; \"{var}\" uses a value saved by an earlier step." }, + "body": { "description": "JSON request body; \"{var}\" strings are replaced by saved values." }, + "expect": { "type": "string", "pattern": "^([1-5][0-9][0-9]|[1-5]XX)$", "description": "Documented status the step must get. Required for every phase but cleanup." }, + "save": { "type": "object", "additionalProperties": { "type": "string", "pattern": "^(/.*)?$" }, "description": "Variable โ†’ JSON pointer into the response body." } + } + } + } +} diff --git a/src/cases/assign.ts b/src/cases/assign.ts index 152524d..f02ef0d 100644 --- a/src/cases/assign.ts +++ b/src/cases/assign.ts @@ -3,6 +3,7 @@ import type { CrudChain } from '../generate/graph.js'; import type { NegCase } from '../generate/negative.js'; import { bodyPointer, caseId, location, scenarioUid, type CaseParts, type Phase, type ScenarioStep } from './ids.js'; import type { ErrorPlan } from '../generate/error-cases.js'; +import type { ResolvedScenario } from '../scenarios/dsl.js'; /** * Case IDs of the tests the generator writes for one operation (docs/OPENAPI_CHANGE_TRIGGER.md, "Stable IDs"). @@ -27,7 +28,7 @@ export interface SuiteCaseIds { /** `variants`: one case per documented query value, in the order of `AssignInput.queryVariants`. */ functional: { success?: string; notFound?: string; unauthorized?: string; variants: string[]; invalidCredentials?: string; methodNotAllowed?: string; preconditionFailed?: string }; contract: { success?: string; notFound?: string; unauthorized?: string; body: string[]; params: string[]; unsupportedMediaType?: string }; - scenario: { createRead?: string; updateRead?: string; deleteGone?: string; conflict?: string }; + scenario: { createRead?: string; updateRead?: string; deleteGone?: string; conflict?: string; deleteTwice?: string; business: string[] }; /** Every case of this operation, by suite, with metadata for cases.json. */ records: Record<'functional' | 'contract' | 'scenario', CaseRecord[]>; scenarios: Record; @@ -43,7 +44,9 @@ export interface AssignInput { paramCases: NegCase[]; notFound?: { param: string }; unauthorized: boolean; - scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict?: boolean }; + scenarios: { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict?: boolean; deleteTwice?: boolean }; + /** Reviewed business scenarios whose primary step is this operation. */ + business?: ResolvedScenario[]; /** Documented error responses with a safe trigger (stage 6). */ errors?: ErrorPlan; /** Documented query values the suite sends one by one (functional positive), each its own physical test. */ @@ -64,7 +67,7 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): return id; }; const ok = successStatus(s.op); - const ids: SuiteCaseIds = { functional: { variants: [] }, contract: { body: [], params: [] }, scenario: {}, records, scenarios }; + const ids: SuiteCaseIds = { functional: { variants: [] }, contract: { body: [], params: [] }, scenario: { business: [] }, records, scenarios }; const rel = related.length ? { relatedOperationUids: related } : {}; if (s.positive) { @@ -128,9 +131,23 @@ export function assignCaseIds(s: AssignInput, uidOf: (op: Operation) => string): scenarios[sUid] = { scenarioType: 'business', primaryOperationUid: uid, steps }; ids.scenario.conflict = add('scenario', { subjectUid: sUid, polarity: 'negative', location: location.lifecycle(), rule: 'business-rule' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uid))] }); } + if (s.scenarios.deleteTwice) { + // Deleting the same resource twice: the second delete gets the documented 404. + const steps = [...step(chain.create, 'setup'), ...step(s.op, 'action'), { operationUid: uid, phase: 'assertion' as Phase }]; + const sUid = scenarioUid('crud', steps); + scenarios[sUid] = { scenarioType: 'crud', primaryOperationUid: uid, steps, roles: { create: chain.create ? uidOf(chain.create) : null, read: null, update: null, delete: uid } }; + ids.scenario.deleteTwice = add('scenario', { subjectUid: sUid, polarity: 'negative', location: location.lifecycle(), rule: 'business-rule' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uid))] }); + } if (s.scenarios.createRead) ids.scenario.createRead = define([...step(chain.create, 'action'), ...step(chain.read, 'assertion'), ...step(chain.delete, 'cleanup')]); if (s.scenarios.updateRead) ids.scenario.updateRead = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion'), ...step(chain.delete, 'cleanup')]); if (s.scenarios.deleteGone) ids.scenario.deleteGone = define([...step(chain.create, 'setup'), ...step(s.op, 'action'), ...step(chain.read, 'assertion')]); } + // Reviewed business scenarios: identity from the external ID (never from the title or the steps). + for (const sc of s.business ?? []) { + const steps = sc.steps.map((st) => ({ operationUid: uidOf(st.op), phase: st.phase })); + const sUid = scenarioUid('business', steps, sc.id); + scenarios[sUid] = { scenarioType: 'business', primaryOperationUid: uidOf(sc.primaryOp), steps, externalId: sc.id }; + ids.scenario.business.push(add('scenario', { subjectUid: sUid, polarity: sc.polarity, location: location.lifecycle(), rule: 'business-rule' }, { relatedOperationUids: [...new Set(steps.map((x) => x.operationUid).filter((u) => u !== uidOf(sc.primaryOp)))] })); + } return ids; } diff --git a/src/cli.ts b/src/cli.ts index 4f0c54c..e3bf336 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -23,6 +23,8 @@ import { SUPPORTED_OASDIFF_VERSION } from './change/oasdiff.js'; import { normalizeSpec } from './change/normalize.js'; import { readSource } from './change/network.js'; import { validateManifest, validateRegistry } from './cases/validate.js'; +import { validateScenarios, type ResolvedScenario } from './scenarios/dsl.js'; +import { isUrl } from './change/network.js'; import { accountNotice, ACCOUNT_MODES, checkRegisterConfig, missingLoginVars, parseAccountMode, registerAccount, type AccountMode } from './audit/account.js'; import { AiRunner, describeAiError, RUNNERS, type RunnerKind } from './ai/runner.js'; import { proposeDependencies } from './ai/dependencies.js'; @@ -214,6 +216,7 @@ common(program.command('audit').description('analyse a spec (and, if allowed, a common(program.command('generate').description('audit, then generate Playwright API tests for confirmed CRUD dependencies')) .option('--tests-dir ', 'where generated tests are written (default: API_TESTS_DIR or tests/api)') .option('--deps ', 'JSON file with human-confirmed dependencies') + .option('--scenarios ', 'reviewed business scenarios (schemas/scenarios.schema.json); validated against the spec') .option('--max-cases ', 'request-body negative cases per operation; the rest is reported as CASE_LIMIT_REACHED', '60') .addOption(new Option('--lang ', 'language of generated tests (default: API_TESTS_LANG or typescript)').choices(['typescript', 'python'])) .option('--run', 'run the generated tests once against --base-url (needs --allow-write)', false) @@ -222,7 +225,7 @@ common(program.command('generate').description('audit, then generate Playwright .addOption(new Option('--ai-runner ', 'console tool: claude, codex, or command (API_AI_COMMAND). Default: API_AI or claude').choices(RUNNERS)) .option('--ai-max-calls ', 'AI call budget per run', '10') .option('--ai-model ', 'model name passed to the console tool (default: its own default)') - .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; maxCases: string; aiModel?: string; aiRunner?: RunnerKind }) => { + .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; maxCases: string; scenarios?: string; aiModel?: string; aiRunner?: RunnerKind }) => { const location = await resolveInputs(specArg, o); o.testsDir ??= cfg.testsDir; o.lang ??= cfg.testsLang; @@ -238,7 +241,14 @@ common(program.command('generate').description('audit, then generate Playwright log('Generating test suites (functional / contract / scenarios)โ€ฆ'); const maxCases = Number(o.maxCases); if (!Number.isInteger(maxCases) || maxCases < 1) throw new Error(`--max-cases must be a positive integer, got "${o.maxCases}".`); - const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases }); + let scenarios: ResolvedScenario[] | undefined; + if (o.scenarios) { + const checked = validateScenarios(JSON.parse(await readFile(o.scenarios, 'utf8')), r.ops); + if (checked.errors.length) throw new Error(`${o.scenarios} is invalid:\n${checked.errors.map((e) => ` ${e.pointer || '(root)'}: ${e.reason}`).join('\n')}`); + scenarios = checked.scenarios; + log(`Scenarios: ${scenarios.length} reviewed business scenario(s) from ${o.scenarios}`); + } + const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases, scenarios }); for (const s of gen.scenarios) log(` ${s.status.padEnd(9)} ${s.name}`); for (const f of gen.removed) log(` REMOVED ${relative(process.cwd(), f).replace(/\\/g, '/')} (generated earlier, no longer produced)`); if (o.run) { @@ -399,6 +409,22 @@ program process.exitCode = r.exitCode; }); +program + .command('scenarios') + .description('reviewed business scenarios') + .command('validate') + .description('check a scenarios file against the spec: operations, parameters, documented statuses, saved values, cleanup (exit 1 on an error)') + .argument('', 'scenarios JSON (schemas/scenarios.schema.json)') + .requiredOption('--spec ', 'the spec the scenarios run against') + .option('--allow-network', 'allow a URL --spec', false) + .action(async (file: string, o: { spec: string; allowNetwork: boolean }) => { + const spec = await loadSpec(isUrl(o.spec) ? (o.allowNetwork ? o.spec : (() => { throw new Error(`${o.spec} is a URL: pass --allow-network`); })()) : o.spec); + const r = validateScenarios(JSON.parse(await readFile(file, 'utf8')), buildCatalog(spec.doc)); + log(`${r.scenarios.length} valid scenario(s), ${r.errors.length} error(s)`); + for (const e of r.errors) log(` ${e.pointer || '(root)'}: ${e.reason}`); + if (r.errors.length) process.exitCode = 1; + }); + const registryCmd = program.command('registry').description('the case registry (_support/cases.json): stable operation, case and scenario IDs'); registryCmd .command('validate') diff --git a/src/contract/contract.py b/src/contract/contract.py index 2b98c2d..0228215 100644 --- a/src/contract/contract.py +++ b/src/contract/contract.py @@ -71,6 +71,22 @@ def _nullable(node: Any) -> Any: return out +def fill_vars(value: Any, saved: dict) -> Any: + """Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text.""" + import re + + if isinstance(value, str): + whole = re.fullmatch(r"\{([A-Za-z_]\w*)\}", value) + if whole: + return saved.get(whole.group(1)) + return re.sub(r"\{([A-Za-z_]\w*)\}", lambda m: str(saved.get(m.group(1))), value) + if isinstance(value, list): + return [fill_vars(v, saved) for v in value] + if isinstance(value, dict): + return {k: fill_vars(v, saved) for k, v in value.items()} + return value + + def read_pointer(body: Any, pointer: str) -> Any: node = body for raw in pointer.split("/")[1:]: diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 926be40..d4b429a 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -15,6 +15,7 @@ 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 type { ResolvedScenario } from '../scenarios/dsl.js'; import { bodyCases, documentedRejections, nonexistentIdExpr, type NegCase } from './negative.js'; import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; import { API_BASE, buildApiIndex, renderApiBaseClass, renderApiChildClass, renderApis } from './api-objects.js'; @@ -37,6 +38,8 @@ export interface GenerateOptions { lang?: TestLang; // default typescript /** Body negative cases per operation (default 60); the rest is reported as CASE_LIMIT_REACHED. */ maxCases?: number; + /** Reviewed business scenarios (validated with validateScenarios against the same operations). */ + scenarios?: ResolvedScenario[]; } export interface Scenario { @@ -318,10 +321,10 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const firstWith405 = op.responses.some((r) => r.status === '405') && !paths405.has(op.path); if (firstWith405) paths405.add(op.path); const errors = op.deprecated ? { gaps: [] } : errorPlan({ doc: spec.doc, op, ops, chain: plan?.chain, role: errRole, hasUpdatePayload: plan?.updatePayload !== undefined, reachable, firstWith405 }); - const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors }; + const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors, business: (o.scenarios ?? []).filter((b) => b.primaryOp === op) }; const counts = suiteCounts(input); const 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 }, 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 }, 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). diff --git a/src/generate/python.ts b/src/generate/python.ts index 5238808..828cb5d 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -1,5 +1,7 @@ import type { Operation } from '../types.js'; import { requiredRequest } from './param-cases.js'; +import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/dsl.js'; +import type { CrudChain } from './graph.js'; import { hasFill, queryVariants, roleOf, scenarioCases, uniqueNote, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; /** @@ -359,7 +361,7 @@ function pyHeader(suite: SuiteType, s: SuiteInput, meta: Meta, extra: string[]): const lines = [...extra]; if (s.plan) lines.unshift(`Preconditions and cleanup: ${s.plan.chain.source}`); lines.push('Polarity is a marker: run one side with -m positive or -m negative.'); - return [header(suite, s.op, meta, lines), 'import json # noqa: F401', 'import uuid # noqa: F401', 'from urllib.parse import quote # noqa: F401', '', 'import pytest', '', 'from contract import read_pointer # noqa: F401', '', `pytestmark = pytest.mark.${suite}`, '', '']; + return [header(suite, s.op, meta, lines), 'import json # noqa: F401', 'import uuid # noqa: F401', 'from urllib.parse import quote # noqa: F401', '', 'import pytest', '', 'from contract import fill_vars, read_pointer, report_cleanup_failure # noqa: F401', '', `pytestmark = pytest.mark.${suite}`, '', '']; } /** The successful call with its precondition (fixtures) and cleanup; `assert` returns the assertion lines. */ @@ -491,6 +493,66 @@ function pyErrorTests(s: SuiteInput): string[] { return L; } +/** A reviewed business scenario: steps in order, saved values, expected statuses; cleanup steps in finally. */ +function pyBusinessTest(s: SuiteInput, sc: ResolvedScenario, id?: string): string[] { + const L: string[] = [withId(sc.polarity === 'positive' ? POS : NEG, id), `def test_${pyName(sc.id)}(api):`, ` """${sc.title.replace(/"/g, "'")}"""`, ' saved = {}']; + const callOf = (st: ResolvedStep) => { + // Concatenation, not an f-string: the values are string literals, which an f-string expression cannot + // hold with escapes before Python 3.12. + const parts = st.op.path.replace(/^\//, '').split(/(\{[^}]+\})/).filter((x) => x !== ''); + const p = parts + .map((part) => { + const m = part.match(/^\{(.+)\}$/); + if (!m) return str(part); + const given = st.params?.[m[1]]; + const known = st.op.params.find((x) => x.in === 'path' && x.name === m[1])?.knownValue; + return `quote(str(${given !== undefined ? `fill_vars(${pyLit(given)}, saved)` : str(String(known))}), safe='')`; + }) + .join(' + '); + const req = requiredRequest(st.op); + const query = Object.fromEntries(Object.entries(st.params ?? {}).filter(([k]) => st.op.params.some((x) => x.in === 'query' && x.name === k))); + const args = [ + Object.keys(query).length || Object.keys(req.params).length ? `params={**${pyLit(req.params)}, **fill_vars(${pyLit(query)}, saved)}` : '', + st.body !== undefined ? `json=fill_vars(${pyLit(st.body)}, saved)` : '', + Object.keys(req.headers).length ? `headers=${pyLit(req.headers)}` : '', + ].filter(Boolean); + return `api.${st.op.method}(${p}${args.length ? ', ' + args.join(', ') : ''})`; + }; + const main = sc.steps.filter((st) => st.phase !== 'cleanup'); + const cleanup = sc.steps.filter((st) => st.phase === 'cleanup'); + L.push(' try:'); + main.forEach((st, j) => { + L.push(` # ${st.phase}${st.name ? ` ${st.name}` : ''}: ${st.op.key}`, ` res${j} = ${callOf(st)}`); + if (st.expect) { + const e = String(st.expect).toUpperCase(); + const cond = /^\dXX$/.test(e) ? `str(res${j}.status_code)[0] == "${e[0]}"` : `res${j}.status_code == ${e}`; + L.push(` assert ${cond}, f"CONTRACT_MISMATCH ${st.op.method.toUpperCase()} ${st.op.path.replace(/[{}]/g, (c) => c + c)}: expected ${e}, got {res${j}.status_code}"`); + } + if (Object.keys(st.save ?? {}).length) { + L.push(` body${j} = res${j}.json() if res${j}.content else None`); + for (const [name, ptr] of Object.entries(st.save ?? {})) L.push(` saved[${str(name)}] = read_pointer(body${j}, ${str(ptr)})`); + } + }); + if (!main.length) L.push(' pass'); + L.push(' finally:'); + if (!cleanup.length) L.push(' pass'); + cleanup.forEach((st, j) => { + const needs = varsIn([st.params, st.body]); + const guard = needs.length ? needs.map((v) => `saved.get(${str(v)}) is not None`).join(' and ') : 'True'; + L.push( + ` if ${guard}:`, + ' try:', + ` clean${j} = ${callOf(st)}`, + ' except Exception: # noqa: BLE001 - cleanup must not hide the real failure', + ` clean${j} = None`, + ` if clean${j} is None or (not clean${j}.ok and clean${j}.status_code != 404):`, + ` report_cleanup_failure(${str(st.op.key)}, str(${needs.length ? `saved.get(${str(needs[0])})` : '""'}), clean${j}.status_code if clean${j} is not None else "no response")`, + ); + }); + L.push('', ''); + return L; +} + /** test_contract.py: responses match OpenAPI; invalid requests are rejected as documented. */ export function renderPyContract(s: SuiteInput, meta: Meta): string { const { op, plan } = s; @@ -550,14 +612,31 @@ export function renderPyContract(s: SuiteInput, meta: Meta): string { /** test_scenarios.py: multi-request flows whose primary (action under test) is this operation. */ export function renderPyScenarios(s: SuiteInput, meta: Meta): string { const { op, plan } = s; - const chain = plan!.chain; - const r = chain.read!; - const res = resourceModule(plan!).replace(/_resource$/, ''); + // CRUD flows need the confirmed chain; reviewed business scenarios (--scenarios) do not. + const chain = plan?.chain as CrudChain; + const r = chain?.read as Operation; + const res = plan ? resourceModule(plan).replace(/_resource$/, '') : ''; const sc = scenarioCases(s); - const extra = ['Each scenario: setup (create) โ†’ action (this operation) โ†’ assertion (read) โ†’ cleanup (delete).']; + const business = s.business ?? []; + const extra = plan ? ['Each scenario: setup (create) โ†’ action (this operation) โ†’ assertion (read) โ†’ cleanup (delete).'] : []; + if (business.length) extra.push('Business scenarios come from the reviewed scenarios file: steps, expected statuses and cleanup as written there.'); if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = pyHeader('scenario', s, meta, extra); const id = `created_${res}`; + if (sc.deleteTwice) { + // A repeated delete of the same resource gets the documented 404. + L.push( + withId(NEG, s.ids?.scenario.deleteTwice), + `def test_deleting_the_same_resource_again_gets_404(api, ${id}):`, + ` first = api.${op.method}(${pathExpr(op, chain.param, id)}${pyRequired(op)})`, + ` ${assertSuccess(op, 'first')}`, + ` res = api.${op.method}(${pathExpr(op, chain.param, id)}${pyRequired(op)})`, + ` ${statusIs(op, '404')}`, + '', + '', + ); + } + business.forEach((b, n) => L.push(...pyBusinessTest(s, b, s.ids?.scenario.business[n]))); if (sc.conflict) { // 409 on the fields a reviewed deps file names: the same payload twice. Both records are removed. L.push( diff --git a/src/generate/templates.ts b/src/generate/templates.ts index 6a537c0..3ca0eb3 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -5,6 +5,7 @@ import { apiCall, type ApiRef } from './api-objects.js'; import type { SuiteCaseIds } from '../cases/assign.js'; import { requiredRequest, type ParamRequest } from './param-cases.js'; import type { ErrorPlan } from './error-cases.js'; +import { varsIn, type ResolvedScenario, type ResolvedStep } from '../scenarios/dsl.js'; import { boundaryValues } from './boundaries.js'; /** Payloads and assumptions for one confirmed resource chain. */ @@ -225,6 +226,8 @@ export interface SuiteInput { ids?: SuiteCaseIds; /** Documented error responses with a safe trigger (stage 6). */ errors?: ErrorPlan; + /** Reviewed business scenarios whose primary step is this operation (stage 8). */ + business?: ResolvedScenario[]; } export type Role = 'create' | 'read' | 'update' | 'delete'; @@ -236,10 +239,11 @@ export function roleOf(op: Operation, plan?: ChainPlan): Role | undefined { } /** Multi-request scenarios whose primary operation is `op` (the action under test, never the setup step). */ -export function scenarioCases(s: Pick): { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict: boolean } { +export function scenarioCases(s: Pick): { createRead: boolean; updateRead: boolean; deleteGone: boolean; conflict: boolean; deleteTwice: boolean } { const role = roleOf(s.op, s.plan); const read = s.plan?.chain.read; return { + deleteTwice: s.positive && role === 'delete' && s.op.responses.some((r) => r.status === '404'), conflict: s.positive && role === 'create' && !!s.errors?.conflict, createRead: s.positive && role === 'create' && !!read, updateRead: s.positive && role === 'update' && !!read && s.plan!.updatePayload !== undefined, @@ -255,7 +259,7 @@ export function suiteCounts(s: SuiteInput): Record { return { functional: (s.positive ? 1 : 0) + extra + (s.positive && !s.plan ? queryVariants(s.op).length : 0) + (e?.invalidCredentials ? 1 : 0) + (e?.methodNotAllowed ? 1 : 0) + (e?.preconditionFailed && s.plan ? 1 : 0), contract: (s.positive ? 1 : 0) + extra + s.bodyCases.length + s.paramCases.length + (e?.unsupportedMediaType && s.plan ? 1 : 0), - scenario: (sc.createRead ? 1 : 0) + (sc.updateRead ? 1 : 0) + (sc.deleteGone ? 1 : 0) + (sc.conflict ? 1 : 0), + 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), }; } @@ -405,6 +409,53 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { return close(L); } +/** A reviewed business scenario: its steps in order, saved values, expected statuses; cleanup steps in finally. */ +function businessTest(s: SuiteInput, sc: ResolvedScenario, id?: string): string[] { + const L: string[] = []; + const pol = sc.polarity; + L.push(` test(${q(sc.title)}, ${testOptions(pol, id)}, async ({ api }) => {`, ` const vars: Record = {};`); + const callOf = (st: ResolvedStep, v: string, indent: string) => { + const ref = s.refs.get(st.op)!; + const req = requiredRequest(st.op); + const args = ref.pathParams.map((name) => { + const given = st.params?.[name]; + if (given !== undefined) return `String(fillVars(${JSON.stringify(given)}, vars))`; + return q(String(st.op.params.find((x) => x.in === 'path' && x.name === name)?.knownValue)); + }); + const query = Object.fromEntries(Object.entries(st.params ?? {}).filter(([k]) => st.op.params.some((x) => x.in === 'query' && x.name === k))); + const opts = [ + Object.keys(query).length || Object.keys(req.params).length ? `params: { ...${JSON.stringify(req.params)}, ...fillVars(${JSON.stringify(query)}, vars) }` : '', + Object.keys(req.headers).length ? `headers: ${JSON.stringify(req.headers)}` : '', + st.body !== undefined ? `data: fillVars(${JSON.stringify(st.body)}, vars)` : '', + ].filter(Boolean); + return `${indent}const ${v} = await ${apiCall(ref, 'api', args, opts.length ? `{ ${opts.join(', ')} }` : undefined)};`; + }; + const main = sc.steps.filter((st) => st.phase !== 'cleanup'); + const cleanup = sc.steps.filter((st) => st.phase === 'cleanup'); + L.push(` try {`); + main.forEach((st, j) => { + L.push(` // ${st.phase}${st.name ? ` ${st.name}` : ''}: ${st.op.key}`, callOf(st, `res${j}`, ' ')); + if (st.expect) L.push(` expectStatus(res${j}, [${q(String(st.expect))}], '${st.op.method}', ${q(st.op.path)});`); + if (Object.keys(st.save ?? {}).length) { + L.push(` const body${j} = await res${j}.json().catch(() => undefined);`); + for (const [name, ptr] of Object.entries(st.save ?? {})) L.push(` vars[${q(name)}] = readPointer(body${j}, ${q(ptr)});`); + } + }); + L.push(` } finally {`); + cleanup.forEach((st, j) => { + const needs = varsIn([st.params, st.body]); + const guard = needs.length ? needs.map((v) => `vars[${q(v)}] !== undefined`).join(' && ') : 'true'; + L.push( + ` if (${guard}) {`, + callOf(st, `clean${j}`, ' ').replace(/;$/, '.catch(() => undefined);'), + ` if (!clean${j} || (!clean${j}.ok() && clean${j}.status() !== 404)) reportCleanupFailure(${q(st.op.key)}, String(${needs.length ? `vars[${q(needs[0])}]` : "''"}), clean${j} ? clean${j}.status() : 'no response');`, + ` }`, + ); + }); + L.push(` }`, ` });`, ''); + return L; +} + /** Documented error responses with a safe trigger (stage 6): invalid credentials, 405, 412. */ function errorTests(s: SuiteInput): string[] { const { op, plan } = s; @@ -533,17 +584,38 @@ export function renderContract(s: SuiteInput, meta: Meta): string { /** scenarios.spec.ts: multi-request flows whose primary (action under test) is this operation. */ export function renderScenarios(s: SuiteInput, meta: Meta): string { const { op, refs, plan } = s; - const chain = plan!.chain; - const r = chain.read!; + // CRUD flows need the confirmed chain; reviewed business scenarios (--scenarios) do not. + const chain = plan?.chain as CrudChain; + const r = chain?.read as Operation; + const business = s.business ?? []; const sc = scenarioCases(s); const call = (o: Operation, options?: string) => { const ref = refs.get(o)!; return apiCall(ref, 'api', pathArgs(o, ref, chain.param, 'id'), options); }; - const extra = ['Each scenario: setup (create) โ†’ action (this operation) โ†’ assertion (read) โ†’ cleanup (delete).']; + const extra = plan ? ['Each scenario: setup (create) โ†’ action (this operation) โ†’ assertion (read) โ†’ cleanup (delete).'] : []; + if (business.length) extra.push('Business scenarios come from the reviewed scenarios file: steps, expected statuses and cleanup as written there.'); if (sc.updateRead) extra.push(`ASSUMPTION (not in spec, reviewer must confirm): ${plan!.assumptions.find((a) => a.startsWith('after')) ?? 'read after update returns the new values'}`); const L = suiteHeader('scenario', s, meta, extra); - L.push(...imports(s, ['expect', ...(sc.createRead ? ['readPointer'] : []), ...(sc.conflict ? ['expectStatus'] : [])], true, false), '', `test.describe('${op.key} ยท scenarios', { tag: '@scenario' }, () => {`); + const names = ['expect', ...(sc.createRead || business.length ? ['readPointer'] : []), ...(sc.conflict || sc.deleteTwice || business.length ? ['expectStatus'] : []), ...(business.length ? ['fillVars', 'reportCleanupFailure'] : [])]; + L.push(...imports(s, names, !!plan, false), '', `test.describe('${op.key} ยท scenarios', { tag: '@scenario' }, () => {`); + if (sc.deleteTwice) { + // A repeated delete of the same resource gets the documented 404. + L.push( + ` test('deleting the same resource again gets the documented 404', ${testOptions('negative', s.ids?.scenario.deleteTwice)}, async ({ api }) => {`, + ` const { id } = await resource.create(api);`, + ` try {`, + ` const first = await ${call(op, optionsWith(op))};`, + ` ${expectSuccess(op, 'first')}`, + ` const res = await ${call(op, optionsWith(op))};`, + ` expectStatus(res, ['404'], '${op.method}', ${q(op.path)});`, + ` } finally {`, + ` await resource.remove(api, id);`, + ` }`, + ` });`, + '', + ); + } if (sc.conflict) { // 409 on the fields a reviewed deps file names: the same payload twice. Both records are removed. const fields = s.errors!.conflict!.fields; @@ -617,6 +689,7 @@ export function renderScenarios(s: SuiteInput, meta: Meta): string { '', ); } + L.push(...business.flatMap((sc2, n) => businessTest(s, sc2, s.ids?.scenario.business[n]))); return close(L); } @@ -685,6 +758,21 @@ export async function expectRejected(res: APIResponse, documented: string[], met return expectContract(res, method, path); } +/** Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text. */ +export function fillVars(value: T, vars: Record): T { + const sub = (v: any): any => { + if (typeof v === 'string') { + const whole = v.match(/^\\{([A-Za-z_]\\w*)\\}$/); + if (whole) return vars[whole[1]]; + return v.replace(/\\{([A-Za-z_]\\w*)\\}/g, (_: string, k: string) => String(vars[k])); + } + if (Array.isArray(v)) return v.map(sub); + if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, sub(x)])); + return v; + }; + return sub(value); +} + export function readPointer(body: unknown, pointer: string): unknown { return pointer .split('/') diff --git a/src/scenarios/dsl.ts b/src/scenarios/dsl.ts new file mode 100644 index 0000000..8ac3990 --- /dev/null +++ b/src/scenarios/dsl.ts @@ -0,0 +1,133 @@ +import type { Operation } from '../types.js'; +import type { CoverageGap } from '../generate/body-cases.js'; + +/** + * Reviewed business scenarios (docs/SUPPORT_MATRIX.md, stage 8). Business flows are never guessed from paths: + * they come from this file, written and reviewed by a human, validated strictly against the spec. + * JSON Schema: schemas/scenarios.schema.json. + */ + +export type Phase = 'setup' | 'action' | 'assertion' | 'cleanup'; + +export interface ScenarioStepDef { + name?: string; + operationId: string; + phase: Phase; + /** Path and query parameters by name. Strings may use "{var}" for values saved by earlier steps. */ + params?: Record; + /** JSON request body; "{var}" strings are replaced by saved values. */ + body?: unknown; + /** The documented status this step must get ("201", "4XX"...). Optional for cleanup steps. */ + expect?: string; + /** Values to keep for later steps: variable โ†’ JSON pointer into the response body. */ + save?: Record; +} + +export interface ScenarioDef { + /** External stable ID: the scenarioUid comes from it (never from the title). */ + id: string; + title: string; + polarity: 'positive' | 'negative'; + /** The step under test: its name or operationId. Must be an action step. */ + primary: string; + steps: ScenarioStepDef[]; +} + +export interface ScenarioFile { + scenarios: ScenarioDef[]; +} + +export interface ResolvedStep extends ScenarioStepDef { + op: Operation; +} + +export interface ResolvedScenario extends Omit { + steps: ResolvedStep[]; + primaryOp: Operation; +} + +const PHASES: Phase[] = ['setup', 'action', 'assertion', 'cleanup']; +const VAR = /\{([A-Za-z_][\w]*)\}/g; +const ID = /^[a-z0-9][a-z0-9._-]*$/; + +/** Variables a value refers to ("{cartId}" anywhere inside strings). */ +export function varsIn(value: unknown): string[] { + if (typeof value === 'string') return [...value.matchAll(VAR)].map((m) => m[1]); + if (Array.isArray(value)) return value.flatMap(varsIn); + if (value && typeof value === 'object') return Object.values(value).flatMap(varsIn); + return []; +} + +const documented = (op: Operation, status: string) => { + const s = status.toUpperCase(); + return op.responses.some((r) => r.status.toUpperCase() === s || (/^\dXX$/.test(r.status.toUpperCase()) && r.status[0] === s[0]) || r.status === 'default'); +}; + +/** Strict validation; every problem is an error with a pointer into the file. */ +export function validateScenarios(file: unknown, ops: Operation[]): { errors: { pointer: string; reason: string }[]; scenarios: ResolvedScenario[] } { + const errors: { pointer: string; reason: string }[] = []; + const err = (pointer: string, reason: string) => errors.push({ pointer, reason }); + const out: ResolvedScenario[] = []; + const f = file as ScenarioFile; + if (!f || typeof f !== 'object' || !Array.isArray(f.scenarios)) { + err('', 'a scenarios file is { "scenarios": [ โ€ฆ ] }'); + return { errors, scenarios: out }; + } + const byId = new Map(ops.filter((o) => o.operationId).map((o) => [o.operationId!, o])); + const ids = new Set(); + f.scenarios.forEach((sc, i) => { + const p = `/scenarios/${i}`; + const before = errors.length; + for (const k of Object.keys(sc ?? {})) if (!['id', 'title', 'polarity', 'primary', 'steps'].includes(k)) err(`${p}/${k}`, `unknown field "${k}"`); + if (typeof sc?.id !== 'string' || !ID.test(sc.id)) err(`${p}/id`, 'id is a stable external ID: lowercase letters, digits, ".", "_", "-"'); + else if (ids.has(sc.id)) err(`${p}/id`, `duplicate id "${sc.id}" (DUPLICATE_EXTERNAL_SCENARIO_ID)`); + else ids.add(sc.id); + if (typeof sc?.title !== 'string' || !sc.title.trim()) err(`${p}/title`, 'title is required'); + if (sc?.polarity !== 'positive' && sc?.polarity !== 'negative') err(`${p}/polarity`, 'polarity is "positive" or "negative"'); + const steps = Array.isArray(sc?.steps) ? sc.steps : []; + if (steps.length < 2) err(`${p}/steps`, 'a scenario has at least two steps'); + const saved = new Set(); + const resolved: ResolvedStep[] = []; + let seenCleanup = false; + steps.forEach((st, j) => { + const sp = `${p}/steps/${j}`; + for (const k of Object.keys(st ?? {})) if (!['name', 'operationId', 'phase', 'params', 'body', 'expect', 'save'].includes(k)) err(`${sp}/${k}`, `unknown field "${k}"`); + const op = byId.get(st?.operationId); + if (!op) { + err(`${sp}/operationId`, `operation "${st?.operationId}" is not in the spec`); + return; + } + if (!PHASES.includes(st.phase)) err(`${sp}/phase`, `phase is one of ${PHASES.join(', ')}`); + if (st.phase === 'cleanup') seenCleanup = true; + else if (seenCleanup) err(`${sp}/phase`, 'cleanup steps come last'); + if (st.expect === undefined && st.phase !== 'cleanup') err(`${sp}/expect`, 'every step but cleanup names its expected status'); + if (st.expect !== undefined && !documented(op, String(st.expect))) err(`${sp}/expect`, `${st.expect} is not documented for ${op.key}`); + for (const v of varsIn([st.params, st.body])) if (!saved.has(v)) err(sp, `"{${v}}" is not saved by an earlier step`); + for (const name of op.params.filter((x) => x.in === 'path').map((x) => x.name)) { + if (!(name in (st.params ?? {})) && op.params.find((x) => x.name === name)?.knownValue === undefined) err(`${sp}/params`, `path parameter "${name}" has no value`); + } + for (const name of Object.keys(st.params ?? {})) if (!op.params.some((x) => x.name === name && (x.in === 'path' || x.in === 'query'))) err(`${sp}/params/${name}`, `${op.key} has no path or query parameter "${name}"`); + if (st.body !== undefined && !op.hasRequestBody) err(`${sp}/body`, `${op.key} has no request body`); + for (const [v, ptr] of Object.entries(st.save ?? {})) { + if (typeof ptr !== 'string' || !(ptr === '' || ptr.startsWith('/'))) err(`${sp}/save/${v}`, 'save values are JSON pointers such as "/id"'); + saved.add(v); + } + resolved.push({ ...st, op }); + }); + // Data a scenario creates must be removed: any non-safe setup step needs a cleanup step. + const writes = resolved.filter((s) => s.phase !== 'cleanup' && !['get', 'head', 'options'].includes(s.op.method)); + if (writes.length && !resolved.some((s) => s.phase === 'cleanup')) err(`${p}/steps`, 'the scenario writes data but has no cleanup step (MISSING_CLEANUP)'); + const primary = resolved.find((s) => s.name === sc?.primary) ?? resolved.find((s) => s.op.operationId === sc?.primary); + if (!primary) err(`${p}/primary`, `primary "${sc?.primary}" is not a step name or operationId of this scenario`); + else if (primary.phase !== 'action') err(`${p}/primary`, 'the primary step is the action under test (phase "action")'); + if (errors.length === before && primary) out.push({ ...sc, steps: resolved, primaryOp: primary.op }); + }); + return { errors, scenarios: out }; +} + +/** Coverage note for operations without any scenario: business flows need the reviewed file. */ +export const NO_SCENARIO_FILE: CoverageGap = { + code: 'UNCONFIRMED_BUSINESS_RULE', + location: 'lifecycle', + reason: 'business flows (state transitions, parent โ†’ child, idempotency, polling) need a reviewed scenarios file (--scenarios)', +}; diff --git a/tests/api/_support/cases.json b/tests/api/_support/cases.json index 71e8866..e0d6ee9 100644 --- a/tests/api/_support/cases.json +++ b/tests/api/_support/cases.json @@ -504,6 +504,17 @@ "subjectUid": "scn_4EG5AXFZY2YS", "suiteType": "scenario" }, + "ata:scn_6I3KELJAMGYP:scenario:positive:lifecycle:business-rule": { + "location": "lifecycle", + "polarity": "positive", + "relatedOperationUids": [ + "op_EDRRXKOK26ZL", + "op_UPN7JLUXYUZ7" + ], + "rule": "business-rule", + "subjectUid": "scn_6I3KELJAMGYP", + "suiteType": "scenario" + }, "ata:scn_7MN4FYBHZCZQ:scenario:positive:lifecycle:crud": { "location": "lifecycle", "polarity": "positive", @@ -526,6 +537,27 @@ "rule": "crud", "subjectUid": "scn_I6MIGZS3ULNR", "suiteType": "scenario" + }, + "ata:scn_V2OYCQUW2VKW:scenario:negative:lifecycle:business-rule": { + "location": "lifecycle", + "polarity": "negative", + "relatedOperationUids": [ + "op_UPN7JLUXYUZ7" + ], + "rule": "business-rule", + "subjectUid": "scn_V2OYCQUW2VKW", + "suiteType": "scenario" + }, + "ata:scn_VQLGIE5JMTBU:scenario:negative:lifecycle:business-rule": { + "location": "lifecycle", + "polarity": "negative", + "relatedOperationUids": [ + "op_EDRRXKOK26ZL", + "op_UPN7JLUXYUZ7" + ], + "rule": "business-rule", + "subjectUid": "scn_VQLGIE5JMTBU", + "suiteType": "scenario" } }, "externalIdAliases": {}, @@ -623,6 +655,25 @@ } ] }, + "scn_6I3KELJAMGYP": { + "externalId": "items.read-created", + "primaryOperationUid": "op_7P2UH7UKQRHC", + "scenarioType": "business", + "steps": [ + { + "operationUid": "op_UPN7JLUXYUZ7", + "phase": "setup" + }, + { + "operationUid": "op_7P2UH7UKQRHC", + "phase": "action" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "cleanup" + } + ] + }, "scn_7MN4FYBHZCZQ": { "primaryOperationUid": "op_UPN7JLUXYUZ7", "roles": { @@ -674,6 +725,53 @@ "phase": "cleanup" } ] + }, + "scn_V2OYCQUW2VKW": { + "primaryOperationUid": "op_EDRRXKOK26ZL", + "roles": { + "create": "op_UPN7JLUXYUZ7", + "read": null, + "update": null, + "delete": "op_EDRRXKOK26ZL" + }, + "scenarioType": "crud", + "steps": [ + { + "operationUid": "op_UPN7JLUXYUZ7", + "phase": "setup" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "action" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "assertion" + } + ] + }, + "scn_VQLGIE5JMTBU": { + "externalId": "items.gone-after-delete", + "primaryOperationUid": "op_7P2UH7UKQRHC", + "scenarioType": "business", + "steps": [ + { + "operationUid": "op_UPN7JLUXYUZ7", + "phase": "setup" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "setup" + }, + { + "operationUid": "op_7P2UH7UKQRHC", + "phase": "action" + }, + { + "operationUid": "op_EDRRXKOK26ZL", + "phase": "cleanup" + } + ] } }, "schemaVersion": 1 diff --git a/tests/api/_support/contract-assert.ts b/tests/api/_support/contract-assert.ts index d935a82..2d1da78 100644 --- a/tests/api/_support/contract-assert.ts +++ b/tests/api/_support/contract-assert.ts @@ -55,6 +55,21 @@ export async function expectRejected(res: APIResponse, documented: string[], met return expectContract(res, method, path); } +/** Scenario values: "{name}" alone is replaced by the saved value itself, inside a longer string by its text. */ +export function fillVars(value: T, vars: Record): T { + const sub = (v: any): any => { + if (typeof v === 'string') { + const whole = v.match(/^\{([A-Za-z_]\w*)\}$/); + if (whole) return vars[whole[1]]; + return v.replace(/\{([A-Za-z_]\w*)\}/g, (_: string, k: string) => String(vars[k])); + } + if (Array.isArray(v)) return v.map(sub); + if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, sub(x)])); + return v; + }; + return sub(value); +} + export function readPointer(body: unknown, pointer: string): unknown { return pointer .split('/') diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index a95fcdf..0e68125 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -1,5 +1,5 @@ { - "caseRegistryHash": "132c3ea625d3120236f76ce24950359b96d5a04047a9aa10b24fe127144680bd", + "caseRegistryHash": "8755eefa57796e2434f5acfd81f1d9dc5235dadac364c53a5928c95ea4e9604f", "files": { "_support/api/generated/AdminApiBase.ts": { "ownership": "generated", @@ -39,7 +39,7 @@ }, "_support/contract-assert.ts": { "ownership": "generated", - "sha256": "78f7d10c5e3b5e16fc2589da1beaec473034391b3fca2ab20254b6992245729a" + "sha256": "3209352f79c89cb749fe9a640802f2dbf0429fa9d3b9f9faf375f307c87d0bf4" }, "_support/contract.ts": { "ownership": "generated", @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "dbc27d1b465c4c9fffd068d92bc28b15bde50e5f192ba77c9e6d8e8fe91c51bb" + "sha256": "c5b5b8d76c04ba62de4fc8ad968de49c06290fa5438da3ef05f405f534f5de32" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -111,6 +111,7 @@ }, "items/delete-by-id/scenarios.spec.ts": { "caseIds": [ + "ata:scn_V2OYCQUW2VKW:scenario:negative:lifecycle:business-rule", "ata:scn_4EG5AXFZY2YS:scenario:positive:lifecycle:crud" ], "operationUids": [ @@ -119,7 +120,7 @@ "op_7P2UH7UKQRHC" ], "ownership": "generated", - "sha256": "8174a9a3169561d39f2447242bb94b64ee05dbac34f71b0e7f212fe6836ad41c", + "sha256": "420d713c48f68e70aaeaaeaaa42b8055df861e3efa31382fe849dad6b41e9d01", "suiteType": "scenario" }, "items/get-by-id/contract.spec.ts": { @@ -150,6 +151,20 @@ "sha256": "2896edace4ecdb2a4980d912b9f3115ad1612169d902d2ea609947bd200b6af0", "suiteType": "functional" }, + "items/get-by-id/scenarios.spec.ts": { + "caseIds": [ + "ata:scn_6I3KELJAMGYP:scenario:positive:lifecycle:business-rule", + "ata:scn_VQLGIE5JMTBU:scenario:negative:lifecycle:business-rule" + ], + "operationUids": [ + "op_7P2UH7UKQRHC", + "op_UPN7JLUXYUZ7", + "op_EDRRXKOK26ZL" + ], + "ownership": "generated", + "sha256": "e236e4cd315de6dc77e56cded24124d057372b1021c70f3d30caa7c0f3e835de", + "suiteType": "scenario" + }, "items/get/contract.spec.ts": { "caseIds": [ "ata:op_4PIO72ZI3SIY:contract:positive:response.body#:schema", @@ -356,7 +371,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "c0234b4bfb54752c38970fe2107b785bb796dc89", + "revision": "7f59010131f3bf9c27829bdc7e056c17a38dc803", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index c7d0810..44ef688 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "c0234b4bfb54752c38970fe2107b785bb796dc89", + "capturedRevision": "7f59010131f3bf9c27829bdc7e056c17a38dc803", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/api/items/delete-by-id/scenarios.spec.ts b/tests/api/items/delete-by-id/scenarios.spec.ts index 96a3863..a5550d6 100644 --- a/tests/api/items/delete-by-id/scenarios.spec.ts +++ b/tests/api/items/delete-by-id/scenarios.spec.ts @@ -5,9 +5,22 @@ // Each scenario: setup (create) โ†’ action (this operation) โ†’ assertion (read) โ†’ cleanup (delete). // Polarity is a tag: run one side with --grep @positive or --grep @negative. import { test, expect } from '../../_support/fixtures.js'; +import { expectStatus } from '../../_support/contract-assert.js'; import * as resource from '../../_support/items.resource.js'; test.describe('DELETE /items/{itemId} ยท scenarios', { tag: '@scenario' }, () => { + test('deleting the same resource again gets the documented 404', { tag: '@negative', annotation: { type: 'caseId', description: 'ata:scn_V2OYCQUW2VKW:scenario:negative:lifecycle:business-rule' } }, async ({ api }) => { + const { id } = await resource.create(api); + try { + const first = await api.items.deleteItem(id); + expect(first.status(), 'documented success status of deleteItem').toBe(204); + const res = await api.items.deleteItem(id); + expectStatus(res, ['404'], 'delete', '/items/{itemId}'); + } finally { + await resource.remove(api, id); + } + }); + test('the deleted resource is no longer returned by getItem', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:scn_4EG5AXFZY2YS:scenario:positive:lifecycle:crud' } }, async ({ api }) => { const { id } = await resource.create(api); try { diff --git a/tests/api/items/get-by-id/scenarios.spec.ts b/tests/api/items/get-by-id/scenarios.spec.ts new file mode 100644 index 0000000..cef1559 --- /dev/null +++ b/tests/api/items/get-by-id/scenarios.spec.ts @@ -0,0 +1,53 @@ +// GET /items/{itemId} ยท scenario cases. Generated by api-test-agent 0.1.3. +// Spec: demo-api/openapi.yaml (hash d7b3b546ce170690). Regenerated on spec change: put hand-written cases in separate files. +// Review before merging; never edit assertions just to make a test pass. +// Preconditions and cleanup: OpenAPI links on createItem (GetItem, UpdateItem, DeleteItem) +// Each scenario: setup (create) โ†’ action (this operation) โ†’ assertion (read) โ†’ cleanup (delete). +// Business scenarios come from the reviewed scenarios file: steps, expected statuses and cleanup as written there. +// Polarity is a tag: run one side with --grep @positive or --grep @negative. +import { test, expect } from '../../_support/fixtures.js'; +import { readPointer, expectStatus, fillVars, reportCleanupFailure } from '../../_support/contract-assert.js'; +import * as resource from '../../_support/items.resource.js'; + +test.describe('GET /items/{itemId} ยท scenarios', { tag: '@scenario' }, () => { + test('an item that was just created can be read by its id', { tag: '@positive', annotation: { type: 'caseId', description: 'ata:scn_6I3KELJAMGYP:scenario:positive:lifecycle:business-rule' } }, async ({ api }) => { + const vars: Record = {}; + try { + // setup create: POST /items + const res0 = await api.items.createItem({ data: fillVars({"name":"Scenario item","price":5,"tags":["scenario"]}, vars) }); + expectStatus(res0, ['201'], 'post', '/items'); + const body0 = await res0.json().catch(() => undefined); + vars['itemId'] = readPointer(body0, '/id'); + // action read: GET /items/{itemId} + const res1 = await api.items.getItem(String(fillVars("{itemId}", vars))); + expectStatus(res1, ['200'], 'get', '/items/{itemId}'); + } finally { + if (vars['itemId'] !== undefined) { + const clean0 = await api.items.deleteItem(String(fillVars("{itemId}", vars))).catch(() => undefined); + if (!clean0 || (!clean0.ok() && clean0.status() !== 404)) reportCleanupFailure('DELETE /items/{itemId}', String(vars['itemId']), clean0 ? clean0.status() : 'no response'); + } + } + }); + + test('an item that was deleted cannot be read any more', { tag: '@negative', annotation: { type: 'caseId', description: 'ata:scn_VQLGIE5JMTBU:scenario:negative:lifecycle:business-rule' } }, async ({ api }) => { + const vars: Record = {}; + try { + // setup create: POST /items + const res0 = await api.items.createItem({ data: fillVars({"name":"Scenario item","price":5}, vars) }); + expectStatus(res0, ['201'], 'post', '/items'); + const body0 = await res0.json().catch(() => undefined); + vars['itemId'] = readPointer(body0, '/id'); + // setup delete: DELETE /items/{itemId} + const res1 = await api.items.deleteItem(String(fillVars("{itemId}", vars))); + expectStatus(res1, ['204'], 'delete', '/items/{itemId}'); + // action read: GET /items/{itemId} + const res2 = await api.items.getItem(String(fillVars("{itemId}", vars))); + expectStatus(res2, ['404'], 'get', '/items/{itemId}'); + } finally { + if (vars['itemId'] !== undefined) { + const clean0 = await api.items.deleteItem(String(fillVars("{itemId}", vars))).catch(() => undefined); + if (!clean0 || (!clean0.ok() && clean0.status() !== 404)) reportCleanupFailure('DELETE /items/{itemId}', String(vars['itemId']), clean0 ? clean0.status() : 'no response'); + } + } + }); +}); diff --git a/tests/unit/error-cases.test.ts b/tests/unit/error-cases.test.ts index c4a3b71..6b0cd1e 100644 --- a/tests/unit/error-cases.test.ts +++ b/tests/unit/error-cases.test.ts @@ -62,7 +62,7 @@ describe('stage 6: documented error responses', () => { `ata:${post}:contract:negative:request.content-type:content-type`, `ata:${put}:contract:negative:request.content-type:content-type`, ]) expect(ts.reg.cases[id], id).toBeDefined(); - const conflict = Object.entries(ts.reg.cases).find(([id, c]) => c.rule === 'business-rule' && c.polarity === 'negative'); + const conflict = Object.entries(ts.reg.cases).find(([, c]) => c.rule === 'business-rule' && c.polarity === 'negative' && ts.reg.scenarios[c.subjectUid]?.scenarioType === 'business'); expect(conflict, 'conflict scenario').toBeDefined(); expect(ts.reg.scenarios[conflict![1].subjectUid]).toMatchObject({ scenarioType: 'business', primaryOperationUid: post }); const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); diff --git a/tests/unit/scenarios.test.ts b/tests/unit/scenarios.test.ts new file mode 100644 index 0000000..03cfbce --- /dev/null +++ b/tests/unit/scenarios.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { Ajv } from 'ajv'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { findPython, generate } from '../../src/generate/generate.js'; +import { validateScenarios } from '../../src/scenarios/dsl.js'; +import { scenarioUid } from '../../src/cases/ids.js'; +import { operationUid } from '../../src/change/normalize.js'; +import { validateRegistry } from '../../src/cases/validate.js'; +import { normalizeSpec } from '../../src/change/normalize.js'; + +/** Stage 8 (docs/SUPPORT_MATRIX.md): CRUD flows and reviewed business scenarios. */ + +const demo = await loadSpec('demo-api/openapi.yaml'); +const ops = buildCatalog(demo.doc); +const file = JSON.parse(await readFile('demo-api/scenarios.json', 'utf8')); +const schema = JSON.parse(await readFile('schemas/scenarios.schema.json', 'utf8')); + +describe('stage 8: scenario model', () => { + it('the demo scenarios file matches its JSON Schema and the spec', () => { + expect(new Ajv({ allErrors: true }).validate(schema, file)).toBe(true); + const r = validateScenarios(file, ops); + expect(r.errors).toEqual([]); + expect(r.scenarios.map((s) => s.primaryOp.key)).toEqual(['GET /items/{itemId}', 'GET /items/{itemId}']); + }); + + it('strict validation: unknown operation, undefined variable, undocumented status, no cleanup, primary not an action', () => { + const bad = structuredClone(file); + const s0 = bad.scenarios[0]; + s0.steps[1].params.itemId = '{nope}'; + s0.steps[1].expect = '418'; + s0.steps.pop(); // no cleanup although the scenario creates data + s0.primary = 'create'; + bad.scenarios[1].steps[0].operationId = 'noSuchOp'; + bad.scenarios[1].id = 'items.read-created'; // duplicate external ID + const errors = validateScenarios(bad, ops).errors.map((e) => `${e.pointer}: ${e.reason}`); + for (const want of ['"{nope}" is not saved', '418 is not documented', 'no cleanup step', 'phase "action"', 'operation "noSuchOp" is not in the spec', 'duplicate id']) { + expect(errors.some((e) => e.includes(want)), want).toBe(true); + } + }); + + it('generated: one test per scenario in the primary operation folder, ID from the external ID, cleanup in finally; TS and Python agree', async () => { + const scenarios = validateScenarios(file, ops).scenarios; + const out = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-scn-')); + const res = await generate(demo, ops, { outDir: dir, version: 'test', lang, scenarios }); + return { dir, res, reg: JSON.parse(await readFile(join(dir, '_support/cases.json'), 'utf8')), read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await out('typescript'); + const py = await out('python'); + const steps = scenarios[0].steps.map((st) => ({ operationUid: operationUid(st.op.method, st.op.path.replace(/\{[^}]*\}/g, '{}')), phase: st.phase })); + const uid = scenarioUid('business', steps, 'items.read-created'); + expect(ts.reg.cases[`ata:${uid}:scenario:positive:lifecycle:business-rule`]).toBeDefined(); + expect(ts.reg.scenarios[uid]).toMatchObject({ scenarioType: 'business', externalId: 'items.read-created', primaryOperationUid: operationUid('GET', '/items/{}') }); + // The title is not part of the identity. + const renamed = structuredClone(scenarios); + renamed[0].title = 'another title'; + expect(scenarioUid('business', steps, renamed[0].id)).toBe(uid); + + const text = await ts.read('items/get-by-id/scenarios.spec.ts'); + expect(text).toMatch(/an item that was just created can be read by its id[\s\S]*vars\['itemId'\] = readPointer\(body0, '\/id'\);[\s\S]*\} finally \{[\s\S]*reportCleanupFailure\('DELETE \/items\/\{itemId\}'/); + const active = (reg: any) => Object.keys(reg.cases).filter((k) => !reg.cases[k].status).sort(); + expect(active(py.reg)).toEqual(active(ts.reg)); + expect(validateRegistry(await ts.read('_support/cases.json'), normalizeSpec(await readFile('demo-api/openapi.yaml', 'utf8'), 'demo')).errors).toEqual([]); + expect(await py.read('items/get_by_id/test_scenarios.py')).toContain('def test_items_read_created(api):'); + const compiled = spawnSync(findPython(), ['-m', 'py_compile', ...py.res.files.filter((f) => f.endsWith('.py'))], { encoding: 'utf8' }); + if (!compiled.error) expect(compiled.status, compiled.stderr).toBe(0); + }); + + it('CRUD: a repeated delete gets the documented 404', async () => { + const dir = await mkdtemp(join(tmpdir(), 'ata-del-')); + await generate(demo, ops, { outDir: dir, version: 'test' }); + const text = await readFile(join(dir, 'items/delete-by-id/scenarios.spec.ts'), 'utf8'); + expect(text).toMatch(/deleting the same resource again gets the documented 404[\s\S]*expectStatus\(res, \['404'\]/); + }); +}); From ca0195cce1e06ccd31121b2ef7279663a77512cb Mon Sep 17 00:00:00 2001 From: testomut Date: Mon, 9 Nov 2026 20:54:56 +0100 Subject: [PATCH 8/8] feat(coverage): coverage report with machine codes; parity and gap checks in CI (stages 9-10) - src/generate/coverage.ts: stable gap codes; positive-blocked reasons as codes; per operation the generated count and missing code of each suite, unchecked statuses (with the precise reason when an error gap names the status), unchecked request media types and security alternatives. - coverage-gaps.json gets a summary (operations, generated tests per suite, gaps by code); generate logs the totals. - Expected gaps: the synthetic fixture (unit test) and the demo API (CI, from the real run) must match exactly: a new gap or a silently vanished one fails. - CI: TypeScript / Python parity on the synthetic fixture too. - README: "What is covered, and what is not" (spec-derived, needs confirmation, never generated); docs/SUPPORT_MATRIX.md completed; CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 14 +++ CHANGELOG.md | 10 +++ README.md | 15 ++++ demo-api/expected-gaps.json | 5 ++ docs/SUPPORT_MATRIX.md | 16 ++-- src/cli.ts | 6 +- src/generate/coverage.ts | 86 +++++++++++++++++++ src/generate/generate.ts | 33 ++++++- tests/api/_support/generation-manifest.json | 4 +- tests/api/_support/openapi.snapshot.meta.json | 2 +- .../coverage/kitchen-sink.expected-gaps.json | 9 ++ tests/unit/coverage-report.test.ts | 63 ++++++++++++++ 12 files changed, 252 insertions(+), 11 deletions(-) create mode 100644 demo-api/expected-gaps.json create mode 100644 src/generate/coverage.ts create mode 100644 tests/fixtures/coverage/kitchen-sink.expected-gaps.json create mode 100644 tests/unit/coverage-report.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6271c87..d68133a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,13 @@ jobs: npx tsx src/cli.ts generate tests/fixtures/coverage/kitchen-sink.yaml --deps tests/fixtures/coverage/kitchen-sink.deps.json --tests-dir tests/api-ks-python --lang python --max-cases 500 -o reports/ks-python --fail-on never python -m py_compile $(find tests/api-ks-python -name '*.py') npx tsx src/cli.ts registry validate tests/api-ks/_support/cases.json --spec tests/fixtures/coverage/kitchen-sink.yaml --require-spec > /dev/null + # TypeScript / Python parity on every template: the same active cases. + node -e ' + const active = (f) => Object.entries(require(f).cases).filter(([, c]) => c.status !== "retired").map(([id]) => id).sort(); + const ts = active("./tests/api-ks/_support/cases.json"), py = active("./tests/api-ks-python/_support/cases.json"); + console.log("kitchen sink cases:", ts.length, "TypeScript /", py.length, "Python"); + if (JSON.stringify(ts) !== JSON.stringify(py)) process.exit(1); + ' rm -rf tests/api-ks tests/api-ks-python - name: Start demo API @@ -85,6 +92,13 @@ jobs: ' npx tsx src/cli.ts registry validate tests/api/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null npx tsx src/cli.ts manifest validate --tests-dir tests/api + # Coverage gaps are exactly the expected ones: a new gap or a silently vanished one fails. + node -e ' + const got = require("./reports/generate/coverage-gaps.json").summary.gapsByCode; + const want = require("./demo-api/expected-gaps.json"); + console.log("coverage gaps:", JSON.stringify(got)); + if (JSON.stringify(got) !== JSON.stringify(want)) { console.log("expected:", JSON.stringify(want)); process.exit(1); } + ' - name: Generate Python tests (pytest + requests) and run them once run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 657bc4c..eff1d90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- **Coverage completeness** (see docs/SUPPORT_MATRIX.md): + - one physical test โ†’ one stable case ID (vocabulary v2: `accepted-value`, `invalid-credentials`, `method-not-allowed`, `precondition-failed`), checked on the real run (Playwright report, pytest collection); cases no longer generated become tombstones; + - recursive request-body negative cases at any depth, exactly one broken rule each (verified with ajv), configurable limit `--max-cases` with dropped cases reported; + - query / header / cookie / path parameter cases, array serialization by style / explode, required header / cookie parameters sent in every call; + - stricter response contract in TypeScript and Python alike: headers, no body for 204 / 205 / 304 / HEAD / no content, empty body, text schemas, writeOnly; what is not checked is said; + - documented errors with safe triggers: 401 invalid credentials, 405, 409 (deps `conflictOn`), 412, 415; 403 / 429 / others as gaps; + - boundary-valid query values, deps `echoes`, sampler fixes (multipleOf, exclusive bounds, uniqueItems), uncovered oneOf / anyOf branches reported; + - reviewed business scenarios (`--scenarios`, `scenarios validate`, schemas/scenarios.schema.json) and repeated delete; + - `coverage-gaps.json`: summary by machine code, per-suite status, unchecked statuses / request media types / security alternatives; + - CI: case-ID checks, registry and manifest validation, TypeScript / Python parity, the synthetic fixture must compile, expected coverage gaps. - **Stable case IDs** (step 3 of docs/OPENAPI_CHANGE_TRIGGER.md, core): every generated test carries `ata:::::` (Playwright annotation `caseId`, pytest marker `api_case_id`). `generate` writes `_support/cases.json` (operations, cases, CRUD scenario definitions; existing UIDs kept, removed operations retired, never rebuilt), `_support/generation-manifest.json` (file ownership and canonical hashes, written last) and `_support/openapi.snapshot.meta.json`, which makes the snapshot a `diff` baseline. New `registry validate [path] [--spec] [--require-spec]` and `manifest validate`. Case ID encoding / parsing and the rule vocabulary v1 with its allowed combinations follow the design. - **`diff`: semantic diff of two OpenAPI specs** (step 1 of docs/OPENAPI_CHANGE_TRIGGER.md). Writes `changes.json` (schema in `schemas/changes.schema.json`) and, with `--format markdown`, `changes.md`: operations added / removed / moved (rename detection with the documented thresholds; uncertain links marked `review`), `operationId` and path parameter renames, parameter, request and response changes, schema constraint changes per facet and direction, example / default changes, servers. Deterministic `operationUid` per operation. Formatting, descriptions, `$ref` layout, equivalent `allOf` and 3.0 โ†” 3.1 nullable give no changes. Compatibility verdicts come from oasdiff `1.34.1` (`OASDIFF_BIN` or `PATH`, not bundled; version pinned). Baseline: `--base`, else the Git merge base; otherwise `BLOCKED: BASE_SPEC_MISSING`. URLs need `--allow-network`; private and metadata hosts are denied unless allowed. Exit codes 0 / 1 (`--fail-on breaking | blocked | unknown`, repeatable, default `blocked`) / 2 (configuration). - **A failed create check no longer leaves data:** the resource helper's `create()` removes the record before failing when a check after the request fails (e.g. the API answers an undocumented `201` where the spec says `200`). Before, the test failed before cleanup was registered, and the record stayed (found on Toolshop favorites). diff --git a/README.md b/README.md index 09ff602..0e24812 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,21 @@ Generated files are overwritten when the spec changes; put hand-written cases in `generate --draft-pr` commits the tests and the report on a new branch and opens a GitHub Draft PR. It never pushes to the default branch or merges. +## What is covered, and what is not + +Coverage is reported, never implied. The full keyword-by-keyword table is in [docs/SUPPORT_MATRIX.md](docs/SUPPORT_MATRIX.md); every check that could not be generated is in `coverage-gaps.json` with a machine code and its exact location. + +**Derived from the spec alone (deterministic):** +- request bodies, recursively (`request.body#/items/*/sku`): required, type, null, enum, const, lengths, pattern, format, bounds, multipleOf, array and object size, uniqueItems, additionalProperties; one broken rule per case; +- query, header, cookie and path parameters, arrays in their documented style; +- documented successes, documented enum values and valid limits of query parameters (one test and one case ID each); +- responses: status, Content-Type, headers, JSON / text schema, no body where none is documented, writeOnly; +- documented errors with a safe trigger: 400 / 422, 401 (missing and invalid credentials), 404, 405 (GET only), 412, 415. + +**Needs your confirmation (deps or scenarios file):** CRUD chains and cleanup, 409 conflicts (`conflictOn`), fields a create returns as sent (`echoes`), values taken from existing data (`fill`), and every business flow (`--scenarios`): state transitions, parent โ†’ child, login / refresh, list / search / pagination. + +**Never generated (reported as gaps):** 403 without a reviewed role setup, 429, a 405 that would need an unsafe method, oneOf / anyOf branches other than the one sent, rules that cannot be broken without breaking another, media types other than JSON / text, and anything the spec does not state. + ## Options | Option | Default | | diff --git a/demo-api/expected-gaps.json b/demo-api/expected-gaps.json new file mode 100644 index 0000000..84bbd0d --- /dev/null +++ b/demo-api/expected-gaps.json @@ -0,0 +1,5 @@ +{ + "MISSING_CLEANUP": 2, + "MISSING_RESOURCE_SOURCE": 1, + "MISSING_RESPONSE_SCHEMA": 1 +} diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index ee6aa0f..f6826d0 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -146,11 +146,15 @@ CRUD flows come from confirmed dependencies (OpenAPI links or the deps file). Bu ## Reporting and CI -| Item | State | Stage | -|---|---|---| -| `coverage-gaps.json` per operation | ๐ŸŸก | counts + free-text reasons, no machine codes, no potential / dropped counts | 10 | +| Item | State | Notes | Stage | +|---|---|---|---| +| `coverage-gaps.json` | โœ… | summary (operations, generated tests per suite, gaps by code); per operation: gaps with code and location, per-suite generated count and missing code, positive-blocked code, body cases potential / generated / dropped, unchecked statuses (with the reason code), unchecked request media types, unchecked security alternatives | 10 โœ” | +| machine codes | โœ… | `MISSING_VALID_SAMPLE`, `MISSING_RESOURCE_SOURCE`, `MISSING_CLEANUP`, `MISSING_RESPONSE_SCHEMA`, `UNSUPPORTED_SCHEMA_KEYWORD`, `UNSUPPORTED_MEDIA_TYPE`, `UNCONFIRMED_BUSINESS_RULE`, `UNCOVERED_VARIANT`, `CANNOT_ISOLATE_RULE`, `CASE_LIMIT_REACHED`, `UNREACHABLE_RESPONSE_STATUS`, `UNSAFE_LIVE_CHECK`, `DEPRECATED_OPERATION`, `NO_DOCUMENTED_REJECTION` (`src/generate/coverage.ts`) | 10 โœ” | | unique case ID per physical test | โœ… | checked on the real run: Playwright JSON report annotations, pytest collection (`API_AGENT_CASES_OUT`) | 2 โœ” | +| cases no longer generated | โœ… | tombstones (`status: retired`), reactivated when generated again | 2 โœ” | | CI: registry and manifest validation | โœ… | `registry validate --spec --require-spec`, `manifest validate`, TypeScript and Python | 2 โœ” | -| CI: no duplicate case IDs, every test registered | โœ… | plus: TypeScript and Python generate the same active cases | 2 โœ” | -| cases no longer generated | โœ… | become tombstones (`status: retired`), reactivated when generated again | 2 โœ” | -| CI: expected coverage gaps | โŒ | | 10 | +| CI: no duplicate case IDs, every test registered | โœ… | | 2 โœ” | +| CI: TypeScript / Python parity | โœ… | the same active cases for the demo API and for the synthetic fixture | 9 โœ” | +| CI: the synthetic fixture compiles | โœ… | `tests/fixtures/coverage/kitchen-sink.yaml` generated in both languages: `tsc`, `py_compile`, valid registry | 6 โœ” | +| CI: expected coverage gaps | โœ… | demo API (`demo-api/expected-gaps.json`) in CI; the synthetic fixture in unit tests | 10 โœ” | +| README | โœ… | "What is covered, and what is not": spec-derived vs needs confirmation vs never generated | 10 โœ” | diff --git a/src/cli.ts b/src/cli.ts index e3bf336..0f670ee 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -11,6 +11,7 @@ import { runSchemathesis } from './audit/schemathesis.js'; import { resolveAuth } from './audit/auth.js'; import { buildReport, writeReport, type AuditReport } from './report/report.js'; import { cleanupSummary, generate, runGenerated, scenarioFindings } from './generate/generate.js'; +import { summarize } from './generate/coverage.js'; import { openDraftPr } from './pr.js'; import type { Finding, Operation } from './types.js'; import { classifyTarget, loadConfig } from './config.js'; @@ -285,7 +286,10 @@ common(program.command('generate').description('audit, then generate Playwright }); const files = await writeReport(report, o.out); const coverageFile = join(o.out, 'coverage-gaps.json'); - await writeFile(coverageFile, JSON.stringify({ spec: location, hash: r.spec.hash, operations: gen.coverage }, null, 2) + '\n'); + const byCode = summarize(gen.coverage); + const generated = Object.fromEntries((['functional', 'contract', 'scenario'] as const).map((k) => [k, gen.coverage.reduce((n, c) => n + c.counts[k], 0)])); + await writeFile(coverageFile, JSON.stringify({ spec: location, hash: r.spec.hash, summary: { operations: gen.coverage.length, generated, gapsByCode: byCode }, operations: gen.coverage }, null, 2) + '\n'); + if (Object.keys(byCode).length) log(`Coverage gaps: ${Object.entries(byCode).map(([k, n]) => `${k} ${n}`).join(', ')} (${coverageFile})`); log(`Report: ${files.md}`); log(`Coverage and gaps per operation: ${coverageFile}`); if (o.draftPr) { diff --git a/src/generate/coverage.ts b/src/generate/coverage.ts new file mode 100644 index 0000000..c1e2b0b --- /dev/null +++ b/src/generate/coverage.ts @@ -0,0 +1,86 @@ +import type { Operation } from '../types.js'; +import type { CoverageGap } from './body-cases.js'; +import type { ErrorPlan } from './error-cases.js'; + +/** + * Coverage report helpers (docs/SUPPORT_MATRIX.md, stage 10): machine codes for every reason a check is missing, + * and what the generated suite leaves unchecked per operation. + */ + +/** Stable machine codes. A new reason gets a new code; a code is never renamed. */ +export const GAP_CODES = [ + 'MISSING_VALID_SAMPLE', + 'MISSING_RESOURCE_SOURCE', + 'MISSING_CLEANUP', + 'MISSING_RESPONSE_SCHEMA', + 'UNSUPPORTED_SCHEMA_KEYWORD', + 'UNSUPPORTED_MEDIA_TYPE', + 'UNCONFIRMED_BUSINESS_RULE', + 'UNCOVERED_VARIANT', + 'CANNOT_ISOLATE_RULE', + 'CASE_LIMIT_REACHED', + 'UNREACHABLE_RESPONSE_STATUS', + 'UNSAFE_LIVE_CHECK', + 'DEPRECATED_OPERATION', + 'NO_DOCUMENTED_REJECTION', +] as const; + +/** The code behind a positive-blocked reason the generator writes in prose. */ +export function positiveCode(reason: string | undefined): string | null { + if (!reason) return null; + if (/deprecated/i.test(reason)) return 'DEPRECATED_OPERATION'; + if (/ends the session/i.test(reason)) return 'UNSAFE_LIVE_CHECK'; + if (/no confirmed precondition\/cleanup|cleaned up|No delete operation/i.test(reason)) return 'MISSING_CLEANUP'; + if (/No example-backed payload|Cannot build a valid|cannot derive/i.test(reason)) return 'MISSING_VALID_SAMPLE'; + if (/No concrete 2xx/i.test(reason)) return 'UNREACHABLE_RESPONSE_STATUS'; + if (/candidate|unconfirmed|Confirm|link the operation/i.test(reason)) return 'MISSING_RESOURCE_SOURCE'; + if (/No value for|spec example|with no value/i.test(reason)) return 'MISSING_RESOURCE_SOURCE'; + return 'UNCONFIRMED_BUSINESS_RULE'; +} + +export interface Exercised { + positive: boolean; + notFound: boolean; + unauthorized: boolean; + validation: string[]; // statuses expected by body / parameter cases + invalidInput: boolean; // there are body / parameter cases + errors?: ErrorPlan; + deleteTwice: boolean; +} + +/** Documented statuses no generated test exercises (2xx counts as exercised by the success call). */ +export function uncheckedStatuses(op: Operation, x: Exercised): { status: string; code: string }[] { + const hit = new Set(); + if (x.positive) for (const r of op.responses) if (/^2/.test(r.status)) hit.add(r.status); + if (x.notFound || x.deleteTwice) hit.add('404'); + if (x.unauthorized || x.errors?.invalidCredentials) hit.add('401'); + if (x.invalidInput) for (const v of x.validation) hit.add(v.toUpperCase()); + if (x.errors?.methodNotAllowed) hit.add('405'); + if (x.errors?.conflict) hit.add('409'); + if (x.errors?.preconditionFailed) hit.add('412'); + if (x.errors?.unsupportedMediaType) hit.add('415'); + // The precise reason when an error gap names this status; otherwise a code by status class. + const reason = (status: string) => x.errors?.gaps.find((g) => g.location === `response.status#/${status}`)?.code; + return op.responses + .filter((r) => !hit.has(r.status.toUpperCase())) + .map((r) => ({ status: r.status, code: reason(r.status) ?? (/^(5|default)/i.test(r.status) ? 'UNREACHABLE_RESPONSE_STATUS' : /^4/.test(r.status) ? 'NO_DOCUMENTED_REJECTION' : 'UNCONFIRMED_BUSINESS_RULE') })); +} + +/** Request media types the suite never sends (it sends JSON), and security alternatives beyond the one it uses. */ +export function uncheckedRequest(op: Operation): { contentTypes: string[]; securityAlternatives: string[][] } { + const json = op.requestContentTypes.find((c) => c.toLowerCase().includes('json')); + return { + contentTypes: op.requestContentTypes.filter((c) => c !== json), + securityAlternatives: op.security.length > 1 ? op.security.slice(1) : [], + }; +} + +/** Totals by code across operations. */ +export function summarize(ops: { gaps: CoverageGap[]; positiveBlockedCode?: string | null }[]): Record { + const out: Record = {}; + for (const o of ops) { + for (const g of o.gaps) out[g.code] = (out[g.code] ?? 0) + 1; + if (o.positiveBlockedCode) out[o.positiveBlockedCode] = (out[o.positiveBlockedCode] ?? 0) + 1; + } + return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b))); +} diff --git a/src/generate/generate.ts b/src/generate/generate.ts index d4b429a..2ca8f2c 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -15,6 +15,7 @@ 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 { positiveCode, uncheckedRequest, uncheckedStatuses } from './coverage.js'; import type { ResolvedScenario } from '../scenarios/dsl.js'; import { bodyCases, documentedRejections, nonexistentIdExpr, type NegCase } from './negative.js'; import { CONTRACT_ASSERT, SUITE_TYPES, TS_FILES, operationFolder, queryVariants, renderContract, renderFunctional, renderResourceHelpers, renderScenarios, scenarioCases, suiteCounts, type ChainPlan, type Meta, type SuiteInput, type SuiteType } from './templates.js'; @@ -80,6 +81,16 @@ export interface Coverage { gaps: CoverageGap[]; /** Body negative cases found / generated / dropped by the limit. */ bodyCases?: { potential: number; generated: number; dropped: number }; + /** Machine code of positiveBlocked. */ + positiveBlockedCode: string | null; + /** Per suite: generated tests, and the code when the suite is empty. */ + suites: Record; + /** Documented statuses no generated test exercises. */ + uncheckedStatuses: { status: string; code: string }[]; + /** Request media types never sent (the suite sends JSON). */ + uncheckedRequestContentTypes: string[]; + /** Security alternatives beyond the one the suite uses. */ + uncheckedSecurityAlternatives: string[][]; } function jsonBodySchema(spec: LoadedSpec, op: Operation): any { @@ -341,7 +352,27 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp return []; }), ); - coverage.push({ operation: op.key, counts, positiveBlocked: posReason ?? null, negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps], ...(bodyStats ? { bodyCases: bodyStats } : {}) }); + const pCode = positiveCode(posReason); + const req = uncheckedRequest(op); + const scn = scenarioCases(input); + coverage.push({ + operation: op.key, + counts, + positiveBlocked: posReason ?? null, + positiveBlockedCode: pCode, + negativeGaps: why, + lifecycle: plan ? plan.chain.name : null, + gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps], + ...(bodyStats ? { bodyCases: bodyStats } : {}), + suites: { + functional: { generated: counts.functional, missingCode: counts.functional ? null : pCode ?? 'NO_DOCUMENTED_REJECTION' }, + contract: { generated: counts.contract, missingCode: counts.contract ? null : pCode ?? 'NO_DOCUMENTED_REJECTION' }, + scenario: { generated: counts.scenario, missingCode: counts.scenario ? null : plan ? pCode ?? 'UNCONFIRMED_BUSINESS_RULE' : 'UNCONFIRMED_BUSINESS_RULE' }, + }, + uncheckedStatuses: uncheckedStatuses(op, { positive: input.positive, notFound: !!notFound, unauthorized, validation: rej.validation, invalidInput: bCases.length + qCases.length > 0, errors, deleteTwice: scn.deleteTwice }), + uncheckedRequestContentTypes: req.contentTypes, + uncheckedSecurityAlternatives: req.securityAlternatives, + }); const render: Record string> = py ? { functional: renderPyFunctional, contract: renderPyContract, scenario: renderPyScenarios } : { functional: renderFunctional, contract: renderContract, scenario: renderScenarios }; diff --git a/tests/api/_support/generation-manifest.json b/tests/api/_support/generation-manifest.json index 0e68125..fb8272f 100644 --- a/tests/api/_support/generation-manifest.json +++ b/tests/api/_support/generation-manifest.json @@ -55,7 +55,7 @@ }, "_support/openapi.snapshot.meta.json": { "ownership": "generated", - "sha256": "c5b5b8d76c04ba62de4fc8ad968de49c06290fa5438da3ef05f405f534f5de32" + "sha256": "c8e6f04b65d4ea77613ad771f2dfcf820450ae83bb19be1c3870d174bd1d2f1f" }, "_support/openapi.snapshot.ts": { "ownership": "generated", @@ -371,7 +371,7 @@ "schemaVersion": 1, "spec": { "hash": "d7b3b546ce170690", - "revision": "7f59010131f3bf9c27829bdc7e056c17a38dc803", + "revision": "91b54559edf4b02cafec7503f06277ea1ce7a21f", "source": "demo-api/openapi.yaml" } } diff --git a/tests/api/_support/openapi.snapshot.meta.json b/tests/api/_support/openapi.snapshot.meta.json index 44ef688..0324d6d 100644 --- a/tests/api/_support/openapi.snapshot.meta.json +++ b/tests/api/_support/openapi.snapshot.meta.json @@ -1,5 +1,5 @@ { - "capturedRevision": "7f59010131f3bf9c27829bdc7e056c17a38dc803", + "capturedRevision": "91b54559edf4b02cafec7503f06277ea1ce7a21f", "generatorVersion": "0.1.3", "schemaVersion": 1, "source": "demo-api/openapi.yaml", diff --git a/tests/fixtures/coverage/kitchen-sink.expected-gaps.json b/tests/fixtures/coverage/kitchen-sink.expected-gaps.json new file mode 100644 index 0000000..0ed1f7a --- /dev/null +++ b/tests/fixtures/coverage/kitchen-sink.expected-gaps.json @@ -0,0 +1,9 @@ +{ + "CANNOT_ISOLATE_RULE": 6, + "MISSING_CLEANUP": 1, + "UNCONFIRMED_BUSINESS_RULE": 1, + "UNCOVERED_VARIANT": 2, + "UNREACHABLE_RESPONSE_STATUS": 1, + "UNSAFE_LIVE_CHECK": 1, + "UNSUPPORTED_SCHEMA_KEYWORD": 1 +} diff --git a/tests/unit/coverage-report.test.ts b/tests/unit/coverage-report.test.ts new file mode 100644 index 0000000..ef3965c --- /dev/null +++ b/tests/unit/coverage-report.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { generate } from '../../src/generate/generate.js'; +import { GAP_CODES, positiveCode, summarize } from '../../src/generate/coverage.js'; +import { validateScenarios } from '../../src/scenarios/dsl.js'; + +/** Stage 10 (docs/SUPPORT_MATRIX.md): coverage reporting with machine codes. */ + +async function run(file: string, deps?: string, scenarios?: string) { + const spec = await loadSpec(file); + const ops = buildCatalog(spec.doc); + const sc = scenarios ? validateScenarios(JSON.parse(await readFile(scenarios, 'utf8')), ops).scenarios : undefined; + return generate(spec, ops, { outDir: await mkdtemp(join(tmpdir(), 'ata-cov-')), version: 'test', deps: deps ? JSON.parse(await readFile(deps, 'utf8')) : undefined, maxCases: 500, scenarios: sc }); +} + +describe('stage 10: coverage report', () => { + it('every gap and every empty suite has a known machine code', async () => { + const r = await run('tests/fixtures/coverage/kitchen-sink.yaml', 'tests/fixtures/coverage/kitchen-sink.deps.json'); + for (const c of r.coverage) { + for (const g of c.gaps) expect(GAP_CODES, `${c.operation} ${g.location}`).toContain(g.code); + for (const s of Object.values(c.suites)) if (s.missingCode) expect(GAP_CODES).toContain(s.missingCode); + for (const u of c.uncheckedStatuses) expect(GAP_CODES).toContain(u.code); + if (c.positiveBlocked) expect(c.positiveBlockedCode).not.toBeNull(); + } + }); + + it('the synthetic fixture has exactly the expected gaps (a new or vanished gap fails)', async () => { + const r = await run('tests/fixtures/coverage/kitchen-sink.yaml', 'tests/fixtures/coverage/kitchen-sink.deps.json'); + expect(summarize(r.coverage)).toEqual(JSON.parse(await readFile('tests/fixtures/coverage/kitchen-sink.expected-gaps.json', 'utf8'))); + }); + + it('the demo API has exactly the expected gaps', async () => { + const r = await run('demo-api/openapi.yaml', undefined, 'demo-api/scenarios.json'); + expect(summarize(r.coverage)).toEqual(JSON.parse(await readFile('demo-api/expected-gaps.json', 'utf8'))); + }); + + it('reports unchecked statuses, request media types and security alternatives', async () => { + const r = await run('tests/fixtures/coverage/kitchen-sink.yaml', 'tests/fixtures/coverage/kitchen-sink.deps.json'); + const list = r.coverage.find((c) => c.operation === 'GET /orders')!; + expect(list.uncheckedStatuses).toEqual([ + { status: '403', code: 'UNCONFIRMED_BUSINESS_RULE' }, + { status: '429', code: 'UNSAFE_LIVE_CHECK' }, + ]); + const update = r.coverage.find((c) => c.operation === 'PUT /orders/{orderId}')!; + expect(update.uncheckedStatuses).toEqual([{ status: '418', code: 'UNREACHABLE_RESPONSE_STATUS' }]); + const multi = { ...buildCatalog((await loadSpec('tests/fixtures/coverage/kitchen-sink.yaml')).doc)[0], requestContentTypes: ['application/json', 'multipart/form-data'], security: [['bearer'], ['apiKey']] } as any; + const { uncheckedRequest } = await import('../../src/generate/coverage.js'); + expect(uncheckedRequest(multi)).toEqual({ contentTypes: ['multipart/form-data'], securityAlternatives: [['apiKey']] }); + }); + + it('positive-blocked reasons map to codes', () => { + expect(positiveCode('POST /x changes data and has no confirmed precondition/cleanup (no OpenAPI links or deps file).')).toBe('MISSING_CLEANUP'); + expect(positiveCode('Path "id" would come from a spec example, not from a real record')).toBe('MISSING_RESOURCE_SOURCE'); + expect(positiveCode('No example-backed payload for PUT /x')).toBe('MISSING_VALID_SAMPLE'); + expect(positiveCode('GET /logout ends the session shared by the other tests')).toBe('UNSAFE_LIVE_CHECK'); + expect(positiveCode('Operation is deprecated.')).toBe('DEPRECATED_OPERATION'); + expect(positiveCode(undefined)).toBeNull(); + }); +});