From 615ae0bce8b59f718ee919d65bbce0775e14c55f Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Mon, 9 Nov 2026 10:33:35 +0100 Subject: [PATCH 1/2] Plan roadmap 1.14: BIAN body, status and event payload conformance for Party Reference Data Directory Co-Authored-By: Claude Opus 5.5 --- .../2026-11-09-party-bian-conformance/plan.md | 40 ++++++++++++ .../requirements.md | 64 +++++++++++++++++++ .../validation.md | 35 ++++++++++ 3 files changed, 139 insertions(+) create mode 100644 specs/2026-11-09-party-bian-conformance/plan.md create mode 100644 specs/2026-11-09-party-bian-conformance/requirements.md create mode 100644 specs/2026-11-09-party-bian-conformance/validation.md diff --git a/specs/2026-11-09-party-bian-conformance/plan.md b/specs/2026-11-09-party-bian-conformance/plan.md new file mode 100644 index 0000000..bf44ffd --- /dev/null +++ b/specs/2026-11-09-party-bian-conformance/plan.md @@ -0,0 +1,40 @@ +# Plan: Party BIAN conformance + +Order: harness first (proved on the fake context), then the catalogue move, then Party wiring and fixes, then ADR and docs. The solution builds and all tests pass after each group. + +## 1. Harness: read BIAN body and payload schemas +- [ ] `OpenApiSpecificationReader`: give `BianOperation` its request-body schema and its 2xx responses (status → schema), resolving `$ref` through Microsoft.OpenApi; accept the `'application/json:'` media-type key as JSON. +- [ ] `AsyncApiSpecificationReader`: give `BianChannel` its message payload schema (`channels.*.messages.*.$ref` → `components.messages.*.payload` → `components.schemas`), with YamlDotNet. +- [ ] A small neutral schema model (`BianSchemaNode`: JSON type, properties, items, `IsEnumWrapper`) both readers produce, so the comparison does not depend on Microsoft.OpenApi types. +- [ ] Loader tests in `RimBank.Conformance.Tests/Specifications/` on the real Party YAML: Register request has `PartyType`, Retrieve 200 has the CR fields, `PartyReferenceDataDirectoryEntry/Created` payload resolves. + +## 2. Harness: subset assertions +- [ ] `RimBankSchema`: export a CLR type's JSON schema with `JsonSchemaExporter` and given `JsonSerializerOptions`, into the same node model (`JsonElement` → "any"). +- [ ] `SchemaSubset.Compare(rimbank, bian, nameComparison)` → list of problems with JSON paths (`$.PartyReference.PartyName`): unknown property, incompatible type; enum wrapper ⇄ string accepted. +- [ ] `ImplementedRoute` carries the endpoint's request type (`IAcceptsMetadata`) and 2xx response types/statuses (`IProducesResponseTypeMetadata`). +- [ ] New assertions in `BianConformance`, all reported in one failure: + - `routes.ShouldHaveBodiesConformingTo(specification, jsonOptions, deviations)`; + - success statuses ⊆ spec 2xx (folded into the same call); + - `publishedEvents.ShouldHavePayloadsConformingTo(specification, wireOptions, deviations)` (event type + its `Channel` const). +- [ ] `ConformanceDeviation(Operation or Channel, JsonPath, Adr)` record; a listed deviation that no longer occurs also fails (keeps the list honest). +- [ ] Self-tests on `FakeContexts/`: conforming fake passes; extra field, wrong type, nested extra field, undeclared 2xx, unknown event property, stale deviation each fail with a message naming the operation/channel and JSON path. + +## 3. Catalogue drives the declarations +- [ ] Move `CataloguedOperation`, `CataloguedChannel` and `PartyReferenceDataDirectoryCatalogue` to `tests/RimBank.Conformance.Testing/Catalogues/` (namespace `RimBank.Conformance.Testing`); reference Party `.PublishedLanguage` from it; keep `PartyReferenceDataDirectoryCatalogueTests` in `RimBank.Conformance.Tests`. +- [ ] Add `Implemented` (non-deferred operation ids) and `Published` (non-deferred channels with their event types) helpers. +- [ ] Architecture tests still green (the `*.Testing` project is not production code). + +## 4. Party: wire the checks and fix mismatches +- [ ] `PartyReferenceDataDirectoryConformanceTests`: replace the hand-written `_implemented` array with `PartyReferenceDataDirectoryCatalogue.Implemented`; add body/status and event payload tests against the running host (Testcontainers), using the host's `JsonOptions` and Wolverine's serializer options. +- [ ] `PartyReferenceDataDirectoryConformanceDeviations` (in `RimBank.Api.Tests`): start empty, run the tests, and triage each problem: + - fix in the `.Api` model or the published event when RimBank simply mis-named or mis-typed a BIAN field; + - otherwise add a deviation row citing the ADR that decided it (for example ADR 0024 for the BQ ids in the Register response). +- [ ] Ensure every Party endpoint exposes its request type and 2xx response in metadata (add `.Accepts()` / `.Produces()` where missing). +- [ ] Update the endpoint and published-event tests and the 1.13 schema snapshots if a fix changes a shape (flag any published-contract change in the PR). +- [ ] Remove the "full subset check … is roadmap 1.14" comment. + +## 5. ADR, docs and roadmap +- [ ] `docs/adr/0037-bian-body-and-payload-conformance.md` (from `template.md`); pointer added to ADR 0020 "Consequences" and ADR 0036 "wire format". +- [ ] tech-stack §9 contract row and §3.3 (`RimBank.Conformance.Testing` now holds the catalogues); CONTRIBUTING "BIAN conformance" (declare via catalogue, deviations list). +- [ ] Tick **1.14** in `specs/roadmap.md`. +- [ ] `dotnet format --verify-no-changes`, full test run. diff --git a/specs/2026-11-09-party-bian-conformance/requirements.md b/specs/2026-11-09-party-bian-conformance/requirements.md new file mode 100644 index 0000000..c78a326 --- /dev/null +++ b/specs/2026-11-09-party-bian-conformance/requirements.md @@ -0,0 +1,64 @@ +# Party BIAN conformance + +Roadmap phase: 1.14 +Branch: plan/1.14-party-bian-conformance + +## Context + +Roadmap 1.14 asks for "OpenAPI and AsyncAPI conformance tests green for the implemented subset". Half of that already exists: since 0.14 ([ADR 0020](../../docs/adr/0020-bian-conformance-harness.md)) `PartyReferenceDataDirectoryConformanceTests` checks that the 13 Party routes are BIAN operations with the spec's method and that `Retrieve` is `GET`, and the catalogue tests check that the two published channel addresses exist in the AsyncAPI. What was explicitly left to 1.14: + +- **Request and response bodies** (ADR 0020, "Out of scope"; the comment in `PartyReferenceDataDirectoryConformanceTests`: "The full subset check of the request and response shapes is roadmap 1.14"). +- **Event payloads**: ADR 0036 says the camelCase wire names of `PartyReferenceDataDirectoryEntryCreated/Updated` are compared to BIAN's PascalCase names "without regard to case" in 1.14. +- The **declared operation list** in `RimBank.Api.Tests` is a hand-written array that can drift from the ADR 0024 catalogue in `RimBank.Conformance.Tests`. + +Mission: the BIAN v14 ext-DDD YAML is the source of truth, and the quality bar requires conformance tests against it; "no speculative coverage" means RimBank implements a **subset** and never invents fields. Tech-stack §5 (BIAN routes and property names, Problem Details replaces `HTTPError`), §8.4 (published events carry the state consumers need) and §9 (contract row) drive the rules below. + +Spec files: `doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml` and `.../asyncapi-3.x/yamls/PartyReferenceDataDirectory.yaml`. + +Depends on 1.5–1.13 (all done). Unblocks 1.16/1.17 (MCP input schemas reuse the `.Api` models, so they inherit this conformance) and gives Stages 2–5 a ready-made harness. + +## Scope + +### In scope + +- **Body schema subset** (harness, `RimBank.Conformance.Testing`): for each implemented operation, the JSON schema of its request model and of its success response model (exported with `JsonSchemaExporter` and the host's `JsonSerializerOptions`) is compared, recursively, to the BIAN schema of that operation's `requestBody` and `2xx` response: + - every property RimBank serialises exists in the BIAN schema at the same JSON path (property names exact for HTTP bodies); + - its JSON type is compatible (string/number/integer/boolean/object/array; `format` ignored); + - BIAN enum wrappers (an object with a single string property, ADR 0024) match a plain JSON string; + - fewer fields than BIAN is always fine (subset). +- **Success status codes**: each endpoint's declared 2xx (`IProducesResponseTypeMetadata`) is a 2xx the spec declares for that operation. Error statuses are not compared (RFC 9457 replaces BIAN's `HTTPError`, ADR 0015). +- **Event payload subset**: the JSON properties of each published integration event (Wolverine's camelCase wire format) exist in its AsyncAPI channel's message payload schema, compared **without regard to case** (ADR 0036). The AsyncAPI reader learns to read `components.messages.*.payload` and resolve `$ref`. +- **Deviations as data**: any field RimBank must carry but BIAN does not declare (for example the BQ ids in the Register response, ADR 0024) is listed in a per-context allow-list that the test reads, each row citing its ADR. A deviation not in the list fails. +- **Catalogue drives the declarations**: `PartyReferenceDataDirectoryCatalogue` moves from `RimBank.Conformance.Tests` to `RimBank.Conformance.Testing`; the Party conformance test declares its operations and channels as the catalogue's non-deferred rows, so the ADR 0024 table, the routing table and the published events cannot drift apart. +- Fix any real mismatch the new checks find in the Party `.Api` models or published events (rename, retype or drop), or record it as an ADR'd deviation. +- ADR 0037, and doc updates (tech-stack §9 contract row, CONTRIBUTING "BIAN conformance", ADR 0020 "Consequences" pointer). + +### Out of scope + +- An architecture rule that every context in `RimBank.Api` has a conformance test (left for when a second context exists, Stage 2). +- Error bodies and non-2xx statuses (Problem Details, ADR 0015). +- `required` / `enum` value / string-format checks: BIAN marks almost nothing required and RimBank's validation is a business rule in core, not a contract shape. +- Comparing against a generated OpenAPI document (Microsoft.AspNetCore.OpenApi is still not wired). +- Deferred operations (Control, Request, Execute, Exchange) and the 8 BQ channels (ADR 0024). +- Authorisation policies (1.15) and MCP tool lists (1.16, 1.17). + +## Decisions + +| Decision | Choice | Rationale | +|---|---|---| +| Direction | RimBank ⊆ BIAN, per JSON path | Mission "no speculative coverage"; ADR 0020 already uses implemented ⊆ spec for routes. | +| How RimBank's shape is read | `JsonSchemaExporter` on the endpoint's request type (`IAcceptsMetadata`) and 2xx response type, using the host's `JsonOptions` | Uses the real serialiser contract (property names, `JsonElement?` passthroughs, ignore conditions), not reflection guesses; same exporter as the 1.13 schema snapshots (ADR 0036). | +| Type matching | JSON type only; `format`, `required`, `enum` ignored; enum wrapper ⇄ string accepted; `JsonElement` (accepted-and-ignored fields) matches any type | Keeps the check about shape, which is what BIAN conformance means here; the wrapper flattening is already decided in ADR 0024. | +| Name matching | Exact for HTTP bodies; case-insensitive for event payloads | HTTP models use BIAN PascalCase names (ADR 0024); events are camelCase on the wire (ADR 0036). | +| Status codes | Only 2xx compared | Errors are Problem Details (ADR 0015) and RimBank adds 409/428 by design (ADR 0018, 0027). | +| Deviations | Per-context allow-list (JSON path + ADR reference), read by the test | Visible, reviewable, and an unlisted deviation fails. | +| Catalogue location | `tests/RimBank.Conformance.Testing/Catalogues/` | Shared by `RimBank.Conformance.Tests` and `RimBank.Api.Tests`; a `*.Testing` project is not a production assembly, so its reference to Party `.PublishedLanguage` breaks no dependency rule. | +| Spec quirks | Tolerate the `'application/json:'` media-type key (trailing colon) in BIAN request bodies | `doc-0/` is read-only (ADR 0002); the harness reads the files as they are. | + +## ADRs to write + +- **ADR 0037 – BIAN body and payload conformance:** the subset rule per JSON path, how RimBank's schema is exported, type and name matching (enum wrappers, `JsonElement`, case-insensitive events), 2xx-only status checks, the deviation allow-list, the catalogue move, and the spec quirks tolerated. Updates ADR 0020's "Consequences" with a pointer. + +## Open questions + +- How many real mismatches exist today is unknown until the harness runs (group 3 of the plan). Each one is either fixed in the model or added to the allow-list with an ADR reference; if a fix would change an already-published contract shape, raise it in the PR before changing it. diff --git a/specs/2026-11-09-party-bian-conformance/validation.md b/specs/2026-11-09-party-bian-conformance/validation.md new file mode 100644 index 0000000..6b9432b --- /dev/null +++ b/specs/2026-11-09-party-bian-conformance/validation.md @@ -0,0 +1,35 @@ +# Validation: Party BIAN conformance + +## Done when (from roadmap) +> **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. +> + Definition of done (roadmap.md) + +Read as: for every non-deferred operation and channel of ADR 0024, the route, method, success status, request body, response body and event payload are a subset of the BIAN v14 ext-DDD YAML, and every exception is listed with its ADR. + +## Automated checks +- [ ] `RimBank.Conformance.Tests/Specifications`: the Party OpenAPI request/2xx schemas and AsyncAPI payloads load and resolve `$ref` (including the `'application/json:'` key). +- [ ] `RimBank.Conformance.Tests/FakeContexts`: the conforming fake passes; each of these fails with a message naming the operation or channel and the JSON path: + - [ ] extra top-level request property; + - [ ] extra nested response property; + - [ ] incompatible JSON type; + - [ ] success status the spec does not declare; + - [ ] unknown event payload property (and a case-only difference passes); + - [ ] a deviation listed but no longer occurring. +- [ ] `RimBank.Conformance.Tests/Catalogues`: catalogue tests still green after the move. +- [ ] `RimBank.Api.Tests` `PartyReferenceDataDirectoryConformanceTests` (Testcontainers host): routes, bodies, statuses and both published channels green; declarations come from the catalogue, not a hand-written list. +- [ ] Every row of `PartyReferenceDataDirectoryConformanceDeviations` cites an ADR. +- [ ] Existing Party endpoint, MCP and published-language tests (including the 1.13 schema snapshots) green, updated only where a fix changed a shape. +- [ ] `RimBank.Architecture.Tests` green. +- [ ] `dotnet format --verify-no-changes` clean; CI (build, test, format, CodeQL) green. + +## Manual / demo checks +- [ ] `dotnet test tests/RimBank.Conformance.Tests` and `dotnet test tests/RimBank.Api.Tests --filter FullyQualifiedName~Conformance` pass locally. +- [ ] Read one failure message from the fake-context self-tests in the test output: it names the BIAN operation, the JSON path and the rule broken, and says how to fix it or which ADR to write. + +## Merge criteria +- [ ] All checks above pass in CI +- [ ] Roadmap checkbox 1.14 ticked in the same PR +- [ ] ADR 0037 written; ADR 0020 and ADR 0036 point to it +- [ ] Any change to a published HTTP or event shape is called out in the PR description +- [ ] tech-stack §3.3/§9 and CONTRIBUTING updated +- [ ] No new production dependency (harness changes stay in `tests/`), no secrets or PII in test data or logs From 2c008bb4f3cb5a4f150c795c8203528ba9c501ee Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Mon, 9 Nov 2026 10:50:48 +0100 Subject: [PATCH 2/2] Check Party request, response and event payload bodies and success statuses against the BIAN schemas, with ADR-cited deviations and the catalogue driving the declarations (roadmap 1.14) Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 25 ++- docs/adr/0020-bian-conformance-harness.md | 1 + ...-party-reference-data-directory-mapping.md | 2 +- docs/adr/0036-party-published-language.md | 2 +- .../0037-bian-body-and-payload-conformance.md | 68 ++++++ .../2026-11-09-party-bian-conformance/plan.md | 44 ++-- specs/roadmap.md | 2 +- specs/tech-stack.md | 6 +- ...renceDataDirectoryConformanceDeviations.cs | 92 ++++++++ ...yReferenceDataDirectoryConformanceTests.cs | 59 +++-- tests/RimBank.Api.Tests/packages.lock.json | 1 + .../packages.linux-x64.lock.json | 2 +- .../packages.win-x64.lock.json | 2 +- .../AsyncApiSpecificationReader.cs | 41 ++-- .../BianConformance.Bodies.cs | 205 ++++++++++++++++++ .../BianConformance.cs | 2 +- .../BianOperation.cs | 15 +- .../RimBank.Conformance.Testing/BianSchema.cs | 63 ++++++ .../PartyReferenceDataDirectoryCatalogue.cs | 15 +- .../ConformanceDeviation.cs | 29 +++ .../ImplementedEndpoint.cs | 61 ++++++ .../OpenApiSpecificationReader.cs | 89 +++++++- .../RimBank.Conformance.Testing.csproj | 6 + .../SchemaSubset.cs | 99 +++++++++ .../SpecificationDocument.cs | 94 ++++++++ .../packages.lock.json | 3 + .../FakeContexts/FakeContext.cs | 30 +++ .../FakeContextBodyConformanceTests.cs | 177 +++++++++++++++ .../FakeContexts/FakeModels.cs | 53 +++++ .../RimBank.Conformance.Tests.csproj | 1 - ...eferenceDataDirectorySpecificationTests.cs | 47 ++++ .../packages.lock.json | 1 + 32 files changed, 1242 insertions(+), 95 deletions(-) create mode 100644 docs/adr/0037-bian-body-and-payload-conformance.md create mode 100644 tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceDeviations.cs create mode 100644 tests/RimBank.Conformance.Testing/BianConformance.Bodies.cs create mode 100644 tests/RimBank.Conformance.Testing/BianSchema.cs rename tests/{RimBank.Conformance.Tests => RimBank.Conformance.Testing}/Catalogues/PartyReferenceDataDirectoryCatalogue.cs (82%) create mode 100644 tests/RimBank.Conformance.Testing/ConformanceDeviation.cs create mode 100644 tests/RimBank.Conformance.Testing/ImplementedEndpoint.cs create mode 100644 tests/RimBank.Conformance.Testing/SchemaSubset.cs create mode 100644 tests/RimBank.Conformance.Testing/SpecificationDocument.cs create mode 100644 tests/RimBank.Conformance.Tests/FakeContexts/FakeContextBodyConformanceTests.cs create mode 100644 tests/RimBank.Conformance.Tests/FakeContexts/FakeModels.cs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 957e6a5..1d7059a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -135,18 +135,29 @@ The host runs one Wolverine bus ([ADR 0017](docs/adr/0017-wolverine-wiring.md)). ### BIAN conformance -Each context's folder of `tests/RimBank.Api.Tests` (which references `tests/RimBank.Conformance.Testing`) has one conformance test that checks its routes and channels against its BIAN v14 specification ([ADR 0020](docs/adr/0020-bian-conformance-harness.md)). Declare the BIAN operation ids the context implements (as the spec's `operationId`), and the channel addresses it publishes to: +Each context's folder of `tests/RimBank.Api.Tests` (which references `tests/RimBank.Conformance.Testing`) has one conformance class that checks its routes, bodies and published events against its BIAN v14 specification ([ADR 0020](docs/adr/0020-bian-conformance-harness.md), [ADR 0037](docs/adr/0037-bian-body-and-payload-conformance.md)). What the context implements and publishes comes from its ADR catalogue in `tests/RimBank.Conformance.Testing/Catalogues/` (the rows that are not `deferred`), and its deliberate differences from BIAN come from a deviation list next to the test: ```csharp -var specification = await BianSpecifications.LoadAsync("PartyReferenceDataDirectory"); -var routes = ImplementedRoute.From(factory.Services.GetRequiredService()); +var specification = await BianSpecifications.LoadAsync(PartyReferenceDataDirectoryCatalogue.ServiceDomain); +var endpoints = host.Alba.Services.GetRequiredService(); -routes.ShouldConformTo(specification, ["PartyReferenceDataDirectoryEntry/Register", "PartyReferenceDataDirectoryEntry/Retrieve"]); -string[] published = ["PartyReferenceDataDirectoryEntry/Created"]; -published.ShouldBeChannelsOf(specification); +ImplementedRoute.From(endpoints).ShouldConformTo(specification, PartyReferenceDataDirectoryCatalogue.Implemented); +ImplementedEndpoint.From(endpoints).ShouldHaveBodiesConformingTo(specification, httpJsonOptions, PartyReferenceDataDirectoryConformanceDeviations.All); +PartyReferenceDataDirectoryCatalogue.Published.ShouldHavePayloadsConformingTo(specification, wireJsonOptions, PartyReferenceDataDirectoryConformanceDeviations.All); ``` -The test fails if a route under `//` is not in the spec or uses another method than the spec (BIAN uses `POST` for `Register` and `PUT` for most other commands), if a `Retrieve` is not `GET` or a command is `GET`, if a declared operation is not mapped, or if a channel is not in the AsyncAPI file. Path parameter names do not matter (`{id}` matches `{partyreferencedatadirectoryid}`). Add each new operation to the declared list in the same PR that maps it. +The tests fail if: + +- a route under `//` is not in the spec, or uses another method than the spec (BIAN uses `POST` for `Register` and `PUT` for most other commands); +- a `Retrieve` is not `GET`, or a command is `GET`; +- a catalogued operation is not mapped; +- an endpoint declares no 2xx response (`.Produces(status)`), or a 2xx the spec does not declare; +- an endpoint reads a body where the spec declares none, or reads none where it declares one; +- a request, response or event payload property is not in the BIAN schema at the same JSON path, or has an incompatible JSON type. + +Path parameter names do not matter (`{id}` matches `{partyreferencedatadirectoryid}`). HTTP property names must match exactly. Event names are compared without regard to case (they are camelCase on the wire). Fewer fields than BIAN is always fine. + +When you add an operation or an event, set its phase in the catalogue in the same PR. When you need a field that BIAN does not have, or one shaped differently, first decide it in an ADR. Then add a `ConformanceDeviation` row for its JSON path, citing that ADR (`"ADR 0031: …"`). A row without an ADR, or a row that no longer matches anything, fails the test. ### Architecture rules diff --git a/docs/adr/0020-bian-conformance-harness.md b/docs/adr/0020-bian-conformance-harness.md index d16c162..3b7b8c4 100644 --- a/docs/adr/0020-bian-conformance-harness.md +++ b/docs/adr/0020-bian-conformance-harness.md @@ -52,3 +52,4 @@ Where the implemented routes come from: - Choosing `POST` or `PUT` for a command is not a free choice: the spec decides. - A new BIAN release (a new `doc-0/release…/` folder, with its own ADR) changes `BianSpecifications.RelativePath`. - Moving Microsoft.OpenApi to 3.x waits until Microsoft.AspNetCore.OpenApi supports it. +- Roadmap 1.14 adds request, response, success status and event payload checks, and moves the declarations to each context's catalogue ([ADR 0037](0037-bian-body-and-payload-conformance.md)). diff --git a/docs/adr/0024-party-reference-data-directory-mapping.md b/docs/adr/0024-party-reference-data-directory-mapping.md index 72e4277..200ec17 100644 --- a/docs/adr/0024-party-reference-data-directory-mapping.md +++ b/docs/adr/0024-party-reference-data-directory-mapping.md @@ -228,5 +228,5 @@ Validation codes (400) for each request's fields are added by the phase that add - Associations scale and version independently of the entry. The price is a cross-aggregate existence check, done on the write side. It is not transactional across streams, but entries are never deleted, so a successful check stays true. Control (terminate) is deferred, and will decide what a terminated entry means for its associations. - BQ updates of one entry contend on one stream version. This is acceptable because they are rare, human-paced changes. - The CR Control, Request, Execute and Exchange operations and the 8 BQ channels are not implemented in Stage 1. The 1.14 conformance tests cover only the implemented subset, and 1.17's tool-list test compares against the implemented rows of the operation table. -- **Enforcement:** `tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs` holds the operation and channel tables above as data. `PartyReferenceDataDirectoryCatalogueTests` fails if a spec operation or channel is missing from them or listed twice, if a row's command/query kind differs from the spec's, or if a phase is neither a Stage 1 phase nor `deferred`. A phase that changes this mapping updates this ADR and that table in the same PR. +- **Enforcement:** `tests/RimBank.Conformance.Testing/Catalogues/PartyReferenceDataDirectoryCatalogue.cs` (in `RimBank.Conformance.Tests` until 1.14, [ADR 0037](0037-bian-body-and-payload-conformance.md)) holds the operation and channel tables above as data. `PartyReferenceDataDirectoryCatalogueTests` fails if a spec operation or channel is missing from them or listed twice, if a row's command/query kind differs from the spec's, or if a phase is neither a Stage 1 phase nor `deferred`. A phase that changes this mapping updates this ADR and that table in the same PR. Since 1.14 the context's conformance tests in `RimBank.Api.Tests` declare their operations and published events from that table, and check the bodies against BIAN with the deviations listed in ADR 0037. - tech-stack §3.4 shows the `PartyAssociation` aggregate in `Associations/`, and the roadmap 1.11 row and Stage 1 header point here. diff --git a/docs/adr/0036-party-published-language.md b/docs/adr/0036-party-published-language.md index 5e50123..aa9889e 100644 --- a/docs/adr/0036-party-published-language.md +++ b/docs/adr/0036-party-published-language.md @@ -52,7 +52,7 @@ Constraints: - **Compatibility:** a field may be added; a field is never removed, renamed or retyped. A breaking change is a new type with a `.v2` identity, published next to v1 until consumers move. - **Mapping:** `PartyReferenceDataDirectoryPublication` (core, `Publication/`) maps a decided `PartyRegistered` or `PartyReferenceDataDirectoryEntryUpdated` to its integration event. `OccurredAt` and `DirectoryEntryDate` are the open or refresh date, so the mapper is pure. `RegisterPartyHandler` and `UpdatePartyReferenceDataDirectoryEntryHandler` return `(Result<…Acknowledged>, ?)`, with the event id from their `TimeProvider`. An error returns `null`, so a refused command publishes nothing by construction. An idempotent replay does not run the handler (ADR 0018), so it publishes nothing again. Behavior Qualifier commands publish nothing. - **Delivery:** the cascaded event goes to the context's durable local queue (ADR 0017's namespace rule also covers the child namespace `.PublishedLanguage`). Its envelope is saved in `party_reference_data_directory.wolverine_incoming_envelopes` in the same transaction as the events. Until a consumer exists (4.1), no handler receives it, and Wolverine logs it and discards it (`UnknownMessageBehavior.LogOnly`, the default). Events are not replayed for entries registered before 1.13, because there is no consumer to replay for. 4.1 decides how a new consumer catches up. -- **Wire format:** Wolverine's default System.Text.Json serializer, so property names are camelCase on the wire (`partyType`). Reads are case-insensitive, and an unknown field is ignored. BIAN names the same fields in PascalCase; 1.14 compares them without regard to case. +- **Wire format:** Wolverine's default System.Text.Json serializer, so property names are camelCase on the wire (`partyType`). Reads are case-insensitive, and an unknown field is ignored. BIAN names the same fields in PascalCase; 1.14 compares them without regard to case, and lists the envelope fields as deviations ([ADR 0037](0037-bian-body-and-payload-conformance.md)). - **Contract:** `PartyPublishedLanguageSchemaTests` (Party `.Postgresql.Tests`, `Publication/`) exports each event's schema with the wire settings and compares it, with its channel and identity, to `Publication/Approved/.approved.json`. On a mismatch it writes `.received.json` (git-ignored). The test also checks: - Wolverine writes the same property names; - an event survives the wire round trip; diff --git a/docs/adr/0037-bian-body-and-payload-conformance.md b/docs/adr/0037-bian-body-and-payload-conformance.md new file mode 100644 index 0000000..0b2a459 --- /dev/null +++ b/docs/adr/0037-bian-body-and-payload-conformance.md @@ -0,0 +1,68 @@ +# 0037. BIAN body, status and payload conformance + +- Status: Accepted +- Date: 2026-11-09 +- Roadmap phase: 1.14 + +## Context + +Roadmap 1.14 asks for "OpenAPI and AsyncAPI conformance tests green for the implemented subset". Since 0.14 the harness ([ADR 0020](0020-bian-conformance-harness.md)) has checked routes, methods, the command/query rule and channel addresses. It left out request and response bodies. [ADR 0036](0036-party-published-language.md) also said 1.14 would compare the camelCase wire names of the published events to BIAN's PascalCase names. + +The mission's source-of-truth rule and "no speculative coverage" mean RimBank implements a **subset** of each BIAN schema and does not invent fields. But earlier ADRs deliberately did differ from BIAN in some places: response bodies carry record ids, Demographics records a verification, contact points use their ISO 20022 subtypes, and events carry an envelope. A body check has to keep those differences visible and stop new, undecided ones. + +Three things about the BIAN v14 files matter here (`doc-0/` is read-only, [ADR 0002](0002-bian-specs-location.md)): + +- In the OpenAPI, request and response bodies are under the media-type key `'application/json:'`, with a stray colon. +- In the Party OpenAPI, the `200` of the Control Record's Register, Control, Update, Request, Execute and Exchange operations points to `#/components/responses/BadRequest` (an `HTTPError` body). Each operation's own response component, `Response` (for example `RegisterPartyReferenceDataDirectoryEntryResponse`), exists but is not used. +- Enums are written as generated wrappers in the OpenAPI (`Partytypevalues: { Partytypevalues: Person | Organisation }`, which [ADR 0024](0024-party-reference-data-directory-mapping.md) flattens to strings), but as plain string schemas in the AsyncAPI. Many ISO 20022 entity references are `type: string` with a `format` that names a type. + +## Options considered + +How RimBank's shape is read: + +1. **Reflection over the CLR models.** Simple, but it guesses property names, ignore conditions and `JsonElement` passthroughs. +2. **`JsonSchemaExporter` with the serializer options the host and the bus actually use.** It reads the real serializer contract, and it is the exporter 1.13 already uses for its schema snapshots. +3. **The host's generated OpenAPI document.** It is not compared yet (ADR 0020), and it describes the Problem Details bodies, which are out of scope. + +How deliberate differences are recorded: + +1. **Rules built into the harness** (for example "an `Id` property is always allowed"). The list is shorter, but a difference passes without anyone deciding it. +2. **A list per context, one row per JSON path, each citing its ADR.** Longer, but every difference is reviewed and traced to a decision. + +## Decision + +- **Rule:** for every implemented operation, RimBank's request body and each of its 2xx response bodies are a subset of the BIAN schema, checked by JSON path. Each property RimBank writes must exist at the same path, and its JSON type must be compatible. Having fewer properties is always fine. For every published integration event, the payload is a subset of its channel's message payload in the same way. +- **Shapes:** RimBank's schema comes from `JsonSchemaExporter` (option 2). For HTTP bodies it uses the host's `Microsoft.AspNetCore.Http.Json.JsonOptions`, and for events Wolverine's default message settings (camelCase). The request type is the one minimal APIs infer from the body parameter (`IAcceptsMetadata`). The responses come from `.Produces(status)` (`IProducesResponseTypeMetadata`). +- **Matching:** + - HTTP property names must match exactly. Event property names are compared without regard to case (ADR 0036). + - Only JSON types are compared: `object`, `array`, `string`, `number`, `integer` and `boolean`. RimBank may write an `integer` where BIAN declares a `number`. `format`, `required` and `enum` values are not compared, because validation is a business rule in core. + - A BIAN enum wrapper accepts a plain string (ADR 0024). + - A schema without a type allows anything, on either side. For RimBank that is a `JsonElement` passthrough or a recursive `$ref`. + - `null` is always allowed. A number that the web defaults can also read from a string still counts as a number. +- **Statuses:** each endpoint must declare at least one 2xx response, and each 2xx it declares must be a 2xx the spec declares for that operation. Error statuses are not compared, because Problem Details replaces BIAN's `HTTPError` ([ADR 0015](0015-problem-details-mapping.md)) and RimBank adds 409 and 428 by design (ADR 0018, [ADR 0027](0027-optimistic-concurrency-for-commands.md)). A `304` is not a 2xx and is not compared either. +- **Request presence:** an endpoint reads a JSON body exactly when the spec declares one, so a missing `.Accepts`/body parameter cannot silently skip the check. +- **Spec quirks:** a media type is JSON when its key starts with `application/json`. When a 2xx response resolves to `HTTPError`, the harness uses the operation's own `#/components/responses/Response`. +- **Deviations as data** (option 2): `ConformanceDeviation(Target, Part, JsonPath, Reason)`, where `Part` is `Request`, `Response` or `Payload`. A listed row excuses exactly the problem at that path. A row that excuses nothing on a checked operation or channel fails. A row whose reason does not cite an ADR (`ADR NNNN`) also fails. Each context keeps its list in `RimBank.Api.Tests`, next to its conformance test. +- **Declarations come from the catalogue:** each context's ADR catalogue (operations and channels, with their phase and event type) moves into `tests/RimBank.Conformance.Testing/Catalogues/`. The context's conformance test declares its operations (`Implemented`) and events (`Published`) as the catalogue's rows that are not deferred. A test library is not a production assembly, so its reference to the context's `.PublishedLanguage` breaks no dependency rule. +- **API:** `endpoints.ShouldHaveBodiesConformingTo(specification, jsonOptions, deviations)` with `ImplementedEndpoint.From(EndpointDataSource)`, and `publishedEventTypes.ShouldHavePayloadsConformingTo(specification, wireOptions, deviations)`. As in ADR 0020, every problem is reported in one failure, with the operation or channel, the JSON path and how to fix or excuse it. + +The Party Reference Data Directory deviations at the time of this ADR (`PartyReferenceDataDirectoryConformanceDeviations`) are: + +| Where | Paths | Decided in | +|---|---|---| +| Responses of every operation | the ids of the records they are about (`PartyReferenceDataDirectoryEntryId`, `DemographicsId`, `ReferenceId`, `BankRelationsId`, `AssociationsId`) | ADR 0024 | +| Entry Retrieve and Update responses | `RefreshDate` | ADR 0024 | +| Demographics responses; Exchange request | `VerificationStatus`, `VerificationDate`; `ExchangeActionType` | [ADR 0028](0028-demographics-exchange-as-verification.md) | +| Reference Update request and Reference responses | `ResidentialAddress.Country` as BIAN's `Country` object; `eMailAddress.EmailAddress`, `CellPhoneNumber.MobileNumber`, `SocialNetworkContacts.URLAddress` | [ADR 0030](0030-iso-3166-country-codes.md), [ADR 0031](0031-reference-contact-points-and-addresses.md) | +| Reference responses | `CompanyOfficerRole` as a string | [ADR 0034](0034-reference-corporate-and-officer-references.md) | +| `PartyReferenceDataDirectoryEntry/Created` and `…/Updated` payloads | `eventId`, `occurredAt`, `partyReferenceDataDirectoryEntryId`, `version` | ADR 0036 | + +No Party model had to change: every difference the check found had already been decided in one of these ADRs. + +## Consequences + +- A new field that BIAN does not declare, a renamed BIAN field, a retyped field or a new success status fails the context's conformance test. The pull request then either fixes the model or adds a deviation row and the ADR behind it. +- Each new BIAN operation or channel is added to the context's catalogue, with its phase, in the same PR that implements it. The conformance tests then pick it up with no hand-written list. +- MCP tools reuse the `.Api` request models (tech-stack §6), so from 1.16 on their input schemas inherit this conformance. +- Stage 2 and later contexts add a catalogue under `Catalogues/`, a deviation list and a three-test conformance class, like Party. A rule that every context has them can be added once a second context exists. +- Any other quirk in a later BIAN file (another error-wired 2xx, another media-type key) shows up as a harness loader test failure and is handled here. diff --git a/specs/2026-11-09-party-bian-conformance/plan.md b/specs/2026-11-09-party-bian-conformance/plan.md index bf44ffd..8e3baf6 100644 --- a/specs/2026-11-09-party-bian-conformance/plan.md +++ b/specs/2026-11-09-party-bian-conformance/plan.md @@ -3,38 +3,38 @@ Order: harness first (proved on the fake context), then the catalogue move, then Party wiring and fixes, then ADR and docs. The solution builds and all tests pass after each group. ## 1. Harness: read BIAN body and payload schemas -- [ ] `OpenApiSpecificationReader`: give `BianOperation` its request-body schema and its 2xx responses (status → schema), resolving `$ref` through Microsoft.OpenApi; accept the `'application/json:'` media-type key as JSON. -- [ ] `AsyncApiSpecificationReader`: give `BianChannel` its message payload schema (`channels.*.messages.*.$ref` → `components.messages.*.payload` → `components.schemas`), with YamlDotNet. -- [ ] A small neutral schema model (`BianSchemaNode`: JSON type, properties, items, `IsEnumWrapper`) both readers produce, so the comparison does not depend on Microsoft.OpenApi types. -- [ ] Loader tests in `RimBank.Conformance.Tests/Specifications/` on the real Party YAML: Register request has `PartyType`, Retrieve 200 has the CR fields, `PartyReferenceDataDirectoryEntry/Created` payload resolves. +- [x] `OpenApiSpecificationReader`: give `BianOperation` its request-body schema and its 2xx responses (status → schema), resolving `$ref` through Microsoft.OpenApi; accept the `'application/json:'` media-type key as JSON. +- [x] `AsyncApiSpecificationReader`: give `BianChannel` its message payload schema (`channels.*.messages.*.$ref` → `components.messages.*.payload` → `components.schemas`), with YamlDotNet. +- [x] A small neutral schema model (`BianSchema` over the YAML read as a JSON tree, `$ref` resolved lazily: JSON type, properties, items, `IsEnumWrapper`) both readers produce, so the comparison does not depend on Microsoft.OpenApi types. +- [x] Loader tests in `RimBank.Conformance.Tests/Specifications/` on the real Party YAML: Register request has `PartyType`, Retrieve 200 has the CR fields, `PartyReferenceDataDirectoryEntry/Created` payload resolves. ## 2. Harness: subset assertions -- [ ] `RimBankSchema`: export a CLR type's JSON schema with `JsonSchemaExporter` and given `JsonSerializerOptions`, into the same node model (`JsonElement` → "any"). -- [ ] `SchemaSubset.Compare(rimbank, bian, nameComparison)` → list of problems with JSON paths (`$.PartyReference.PartyName`): unknown property, incompatible type; enum wrapper ⇄ string accepted. -- [ ] `ImplementedRoute` carries the endpoint's request type (`IAcceptsMetadata`) and 2xx response types/statuses (`IProducesResponseTypeMetadata`). -- [ ] New assertions in `BianConformance`, all reported in one failure: +- [x] `SchemaSubset`: export a CLR type's JSON schema with `JsonSchemaExporter` and given `JsonSerializerOptions` (`JsonElement` → "any"). +- [x] `SchemaSubset.Compare(rimbank, bian, nameComparison)` → list of problems with JSON paths (`$.PartyReference.PartyName`): unknown property, incompatible type; enum wrapper ⇄ string accepted. +- [x] `ImplementedEndpoint` (a new type beside `ImplementedRoute`, which stays a plain value) carries the endpoint's request type (`IAcceptsMetadata`) and 2xx response types/statuses (`IProducesResponseTypeMetadata`). +- [x] New assertions in `BianConformance`, all reported in one failure: - `routes.ShouldHaveBodiesConformingTo(specification, jsonOptions, deviations)`; - success statuses ⊆ spec 2xx (folded into the same call); - `publishedEvents.ShouldHavePayloadsConformingTo(specification, wireOptions, deviations)` (event type + its `Channel` const). -- [ ] `ConformanceDeviation(Operation or Channel, JsonPath, Adr)` record; a listed deviation that no longer occurs also fails (keeps the list honest). -- [ ] Self-tests on `FakeContexts/`: conforming fake passes; extra field, wrong type, nested extra field, undeclared 2xx, unknown event property, stale deviation each fail with a message naming the operation/channel and JSON path. +- [x] `ConformanceDeviation(Operation or Channel, JsonPath, Adr)` record; a listed deviation that no longer occurs also fails (keeps the list honest). +- [x] Self-tests on `FakeContexts/`: conforming fake passes; extra field, wrong type, nested extra field, undeclared 2xx, unknown event property, stale deviation each fail with a message naming the operation/channel and JSON path. ## 3. Catalogue drives the declarations -- [ ] Move `CataloguedOperation`, `CataloguedChannel` and `PartyReferenceDataDirectoryCatalogue` to `tests/RimBank.Conformance.Testing/Catalogues/` (namespace `RimBank.Conformance.Testing`); reference Party `.PublishedLanguage` from it; keep `PartyReferenceDataDirectoryCatalogueTests` in `RimBank.Conformance.Tests`. -- [ ] Add `Implemented` (non-deferred operation ids) and `Published` (non-deferred channels with their event types) helpers. -- [ ] Architecture tests still green (the `*.Testing` project is not production code). +- [x] Move `CataloguedOperation`, `CataloguedChannel` and `PartyReferenceDataDirectoryCatalogue` to `tests/RimBank.Conformance.Testing/Catalogues/` (namespace `RimBank.Conformance.Testing`); reference Party `.PublishedLanguage` from it; keep `PartyReferenceDataDirectoryCatalogueTests` in `RimBank.Conformance.Tests`. +- [x] Add `Implemented` (non-deferred operation ids) and `Published` (non-deferred channels with their event types) helpers. +- [x] Architecture tests still green (the `*.Testing` project is not production code). ## 4. Party: wire the checks and fix mismatches -- [ ] `PartyReferenceDataDirectoryConformanceTests`: replace the hand-written `_implemented` array with `PartyReferenceDataDirectoryCatalogue.Implemented`; add body/status and event payload tests against the running host (Testcontainers), using the host's `JsonOptions` and Wolverine's serializer options. -- [ ] `PartyReferenceDataDirectoryConformanceDeviations` (in `RimBank.Api.Tests`): start empty, run the tests, and triage each problem: +- [x] `PartyReferenceDataDirectoryConformanceTests`: replace the hand-written `_implemented` array with `PartyReferenceDataDirectoryCatalogue.Implemented`; add body/status and event payload tests against the running host (Testcontainers), using the host's `JsonOptions` and Wolverine's serializer options. +- [x] `PartyReferenceDataDirectoryConformanceDeviations` (in `RimBank.Api.Tests`): start empty, run the tests, and triage each problem: - fix in the `.Api` model or the published event when RimBank simply mis-named or mis-typed a BIAN field; - otherwise add a deviation row citing the ADR that decided it (for example ADR 0024 for the BQ ids in the Register response). -- [ ] Ensure every Party endpoint exposes its request type and 2xx response in metadata (add `.Accepts()` / `.Produces()` where missing). -- [ ] Update the endpoint and published-event tests and the 1.13 schema snapshots if a fix changes a shape (flag any published-contract change in the PR). -- [ ] Remove the "full subset check … is roadmap 1.14" comment. +- [x] Ensure every Party endpoint exposes its request type and 2xx response in metadata (all already did; the harness now fails an endpoint that reads no body where BIAN declares one). +- [x] Update the endpoint and published-event tests and the 1.13 schema snapshots if a fix changes a shape (none needed: all 63 differences found were already ADR-decided, so no shape changed). +- [x] Remove the "full subset check … is roadmap 1.14" comment. ## 5. ADR, docs and roadmap -- [ ] `docs/adr/0037-bian-body-and-payload-conformance.md` (from `template.md`); pointer added to ADR 0020 "Consequences" and ADR 0036 "wire format". -- [ ] tech-stack §9 contract row and §3.3 (`RimBank.Conformance.Testing` now holds the catalogues); CONTRIBUTING "BIAN conformance" (declare via catalogue, deviations list). -- [ ] Tick **1.14** in `specs/roadmap.md`. -- [ ] `dotnet format --verify-no-changes`, full test run. +- [x] `docs/adr/0037-bian-body-and-payload-conformance.md` (from `template.md`); pointer added to ADR 0020 "Consequences" and ADR 0036 "wire format". +- [x] tech-stack §9 contract row and §3.3 (`RimBank.Conformance.Testing` now holds the catalogues); CONTRIBUTING "BIAN conformance" (declare via catalogue, deviations list). +- [x] Tick **1.14** in `specs/roadmap.md`. +- [x] `dotnet format --verify-no-changes`, full test run. diff --git a/specs/roadmap.md b/specs/roadmap.md index 32ac28a..da79818 100644 --- a/specs/roadmap.md +++ b/specs/roadmap.md @@ -60,7 +60,7 @@ - [x] **1.21 Reference BQ: corporate and officer references:** `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference` and `CompanyOfficerRole`, references to other parties, added to the Reference Update and Retrieve after the Associations BQ (ADR 0032). Each reference is another registered entry, checked on the write side; they are recorded only on an organisation, the corporate customer and legal entity are organisations and the officer a person ([ADR 0034](../docs/adr/0034-reference-corporate-and-officer-references.md)). - [x] **1.12 BankRelations BQ:** the party's relationships with the bank; Update command and Retrieve query. It records a closed relation type, the bank employee (a person) or unit (an organisation) as a registered entry checked on the write side, and the relationship's dates and lifecycle status ([ADR 0035](../docs/adr/0035-party-bank-relations.md)). - [x] **1.13 Published language:** `PartyReferenceDataDirectoryEntryCreated/Updated` integration events, mapped from domain events (not from read models), carrying the state consumers need, versioned, published through the outbox, and pinned by a schema contract test. -- [ ] **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. +- [x] **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. - [ ] **1.15 Authorisation policies:** per-operation policies (separate scopes for command and query operations), with tests. - [ ] **1.16 MCP adapter: Register & Retrieve:** `RimBank.Party.PartyReferenceDataDirectory.Mcp` tools for Register (command) and Retrieve (query, `readOnly`), with a parity test against the HTTP endpoints. - [ ] **1.17 MCP adapter: remaining operations:** Update and BQ tools; a test that the tool list matches the implemented BIAN operations. diff --git a/specs/tech-stack.md b/specs/tech-stack.md index 2f4e824..1854243 100644 --- a/specs/tech-stack.md +++ b/specs/tech-stack.md @@ -108,8 +108,8 @@ Before a service domain is created, its mapping must be checked against the BIAN ├─ RimBank.Postgresql.Tests/ # store, messaging and idempotency conventions with two test-only fake contexts, Testcontainers (ADR 0016–0018) ├─ RimBank.Host.Testing/ # shared helpers for in-memory host tests: test-signed access tokens (ADR 0019), used by Host.Tests, Api.Tests and Mcp.Tests ├─ RimBank.SharedKernel.Testing/ # shared test helpers: typed ID contract (ADR 0008), FsCheck money generators (ADR 0009), decider/projection helpers (0.6) - ├─ RimBank.Conformance.Testing/ # BIAN conformance harness used by RimBank.Api.Tests: spec loaders, route and channel assertions (ADR 0020) - ├─ RimBank.Conformance.Tests/ # the harness on the real Party YAML and a test-only fake context (ADR 0020) + ├─ RimBank.Conformance.Testing/ # BIAN conformance harness used by RimBank.Api.Tests: spec loaders, route, channel, body, status and payload assertions, and each context's ADR catalogue in Catalogues/ (ADR 0020, ADR 0037) + ├─ RimBank.Conformance.Tests/ # the harness on the real Party YAML, the catalogue tests, and a test-only fake context (ADR 0020, ADR 0037) ├─ RimBank.Core.Tests/ # domain + application of every context (no I/O), same folders as RimBank.Core (ADR 0023) │ └─ Party/PartyReferenceDataDirectory/ └─ Party/ @@ -336,7 +336,7 @@ CQRS is applied **logically everywhere** and **physically where needed**. Every | Property-based | FsCheck | Money arithmetic, balance invariants, evolve/decide laws, projection/aggregate agreement | | Integration | Testcontainers (PostgreSQL), Alba | Marten persistence and projections (inline and async daemon), Wolverine outbox, HTTP endpoints end to end | | Architecture | ArchUnitNET | Dependency rules and CQRS rules in §4, naming rules in §3, cross-context isolation in §8.4 | -| Contract | OpenAPI/AsyncAPI conformance tests (`RimBank.Conformance.Testing`: Microsoft.OpenApi, YamlDotNet, [ADR 0020](../docs/adr/0020-bian-conformance-harness.md)); published-event schema snapshots (`JsonSchemaExporter` against committed approved files, [ADR 0036](../docs/adr/0036-party-published-language.md)) | Implemented routes and channels exist in the BIAN v14 ext-DDD YAML with the spec's method, `Retrieve` is `GET` and nothing else is; published integration events stay backwards compatible | +| Contract | OpenAPI/AsyncAPI conformance tests (`RimBank.Conformance.Testing`: Microsoft.OpenApi, YamlDotNet, [ADR 0020](../docs/adr/0020-bian-conformance-harness.md); bodies, 2xx statuses and event payloads as a subset of the BIAN schemas, with ADR-cited deviations, [ADR 0037](../docs/adr/0037-bian-body-and-payload-conformance.md)); published-event schema snapshots (`JsonSchemaExporter` against committed approved files, [ADR 0036](../docs/adr/0036-party-published-language.md)) | Implemented routes and channels exist in the BIAN v14 ext-DDD YAML with the spec's method, `Retrieve` is `GET` and nothing else is; request, response and event payload fields exist in the BIAN schema unless an ADR decided otherwise; published integration events stay backwards compatible | | MCP | MCP C# SDK client in-process against the test host | Tool list, input schemas, results, Problem Details errors, and parity with the HTTP endpoint for the same operation | | Mutation (later) | Stryker.NET | The `RimBank.Core` folders of money-moving domains (`--mutate "//**"`) | diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceDeviations.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceDeviations.cs new file mode 100644 index 0000000..6686507 --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceDeviations.cs @@ -0,0 +1,92 @@ +using RimBank.Conformance.Testing; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +/// +/// The deliberate differences between the Party Reference Data Directory's bodies and its BIAN v14 schemas, each +/// decided in an ADR (ADR 0037). A difference not listed here fails the conformance tests, and so does a row that no +/// longer occurs. +/// +internal static class PartyReferenceDataDirectoryConformanceDeviations +{ + private const string EntryRegister = "PartyReferenceDataDirectoryEntry/Register"; + private const string EntryRetrieve = "PartyReferenceDataDirectoryEntry/Retrieve"; + private const string EntryUpdate = "PartyReferenceDataDirectoryEntry/Update"; + private const string DemographicsUpdate = "Demographics/Update"; + private const string DemographicsExchange = "Demographics/Exchange"; + private const string DemographicsRetrieve = "Demographics/Retrieve"; + private const string ReferenceUpdate = "Reference/Update"; + private const string ReferenceRetrieve = "Reference/Retrieve"; + private const string AssociationsRegister = "Associations/Register"; + private const string AssociationsUpdate = "Associations/Update"; + private const string AssociationsRetrieve = "Associations/Retrieve"; + private const string BankRelationsUpdate = "BankRelations/Update"; + private const string BankRelationsRetrieve = "BankRelations/Retrieve"; + + private const string RecordIds = + "ADR 0024: a response carries the ids of the records it is about, which BIAN puts only in the path, so a client can call their operations."; + + private const string Verification = + "ADR 0028: Demographics Exchange records a verification outcome, so the record carries VerificationStatus and VerificationDate."; + + private const string ContactPoint = + "ADR 0031: a contact point is read through its ISO 20022 subtype property inside BIAN's ContactPoint object."; + + private const string Envelope = + "ADR 0036: a published event carries a small envelope (event id, time, entry id, stream version) so consumers can order and deduplicate."; + + public static IReadOnlyList All { get; } = + [ + // The Control Record: Register, Retrieve and Update answer with the entry and its three singleton BQs. + .. Responses([EntryRegister, EntryRetrieve, EntryUpdate], RecordIds, "PartyReferenceDataDirectoryEntryId", "DemographicsId", "ReferenceId", "BankRelationsId"), + .. Responses( + [EntryRetrieve, EntryUpdate], + "ADR 0024: the entry's last Update is returned as RefreshDate, BIAN's second DirectoryEntryDateType, next to the OpenDate pair.", + "RefreshDate"), + + // Demographics. + .. Responses([DemographicsUpdate, DemographicsExchange, DemographicsRetrieve], RecordIds, "PartyReferenceDataDirectoryEntryId", "DemographicsId"), + .. Responses([DemographicsUpdate, DemographicsExchange, DemographicsRetrieve], Verification, "VerificationStatus", "VerificationDate"), + new(DemographicsExchange, ConformancePart.Request, "$.ExchangeActionType", "ADR 0028: Exchange takes RimBank's extension field ExchangeActionType (Verify | Reject)."), + + // Reference. + .. Responses([ReferenceUpdate, ReferenceRetrieve], RecordIds, "PartyReferenceDataDirectoryEntryId", "ReferenceId"), + .. Both( + ReferenceUpdate, + [ReferenceRetrieve], + "ADR 0030, ADR 0031: a postal address's Country is BIAN's Country object with its ISO 3166 Code, where BIAN's PostalAddress types it as a string.", + "$.ResidentialAddress.Country"), + .. Both(ReferenceUpdate, [ReferenceRetrieve], ContactPoint, "$.eMailAddress.EmailAddress", "$.CellPhoneNumber.MobileNumber", "$.SocialNetworkContacts.URLAddress"), + .. Responses( + [ReferenceUpdate, ReferenceRetrieve], + "ADR 0034: CompanyOfficerRole is a plain role name, because BIAN types it as a Party, which has no role property.", + "CompanyOfficerRole"), + + // Associations and BankRelations. + .. Responses([AssociationsRegister, AssociationsUpdate, AssociationsRetrieve], RecordIds, "AssociationsId", "PartyReferenceDataDirectoryEntryId"), + .. Responses([BankRelationsUpdate, BankRelationsRetrieve], RecordIds, "BankRelationsId", "PartyReferenceDataDirectoryEntryId"), + + // The published language (camelCase on the wire). + .. Payloads( + ["PartyReferenceDataDirectoryEntry/Created", "PartyReferenceDataDirectoryEntry/Updated"], + Envelope, + "eventId", + "occurredAt", + "partyReferenceDataDirectoryEntryId", + "version"), + ]; + + private static IEnumerable Responses(string[] operations, string reason, params string[] properties) => + operations.SelectMany(operation => properties.Select(property => new ConformanceDeviation(operation, ConformancePart.Response, "$." + property, reason))); + + // The same paths in a command's request and response, and in the responses of the operations that return its record. + private static IEnumerable Both(string command, string[] alsoReturnedBy, string reason, params string[] paths) => + paths.SelectMany(path => (IEnumerable) + [ + new(command, ConformancePart.Request, path, reason), + .. alsoReturnedBy.Prepend(command).Select(operation => new ConformanceDeviation(operation, ConformancePart.Response, path, reason)), + ]); + + private static IEnumerable Payloads(string[] channels, string reason, params string[] properties) => + channels.SelectMany(channel => properties.Select(property => new ConformanceDeviation(channel, ConformancePart.Payload, "$." + property, reason))); +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs index 97ef4c5..efe0612 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs @@ -1,39 +1,56 @@ +using System.Text.Json; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using RimBank.Conformance.Testing; +using HttpJsonOptions = Microsoft.AspNetCore.Http.Json.JsonOptions; namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; -// Roadmap 1.5, 1.7 and ADR 0020: every route the running host maps under /PartyReferenceDataDirectory/ is an operation -// of the BIAN specification, with its method, and every operation implemented so far is mapped. The full subset check -// of the request and response shapes is roadmap 1.14. +// Roadmap 1.14 (ADR 0020, ADR 0037): the implemented subset of Party Reference Data Directory conforms to its BIAN v14 +// OpenAPI and AsyncAPI specifications. What it implements and publishes comes from the ADR 0024 catalogue, so the +// ADR, the running host's routing table and the published language cannot drift apart. Every deliberate difference +// is a row of PartyReferenceDataDirectoryConformanceDeviations that cites its ADR. public sealed class PartyReferenceDataDirectoryConformanceTests(PostgresqlServer server) { - private static readonly string[] _implemented = - [ - RegisterPartyEndpoint.OperationId, - RetrievePartyReferenceDataDirectoryEntryEndpoint.OperationId, - UpdatePartyReferenceDataDirectoryEntryEndpoint.OperationId, - UpdateDemographicsEndpoint.OperationId, - ExchangeDemographicsEndpoint.OperationId, - RetrieveDemographicsEndpoint.OperationId, - UpdatePartyReferenceEndpoint.OperationId, - RetrievePartyReferenceEndpoint.OperationId, - RegisterPartyAssociationEndpoint.OperationId, - UpdatePartyAssociationEndpoint.OperationId, - RetrievePartyAssociationEndpoint.OperationId, - UpdateBankRelationsEndpoint.OperationId, - RetrieveBankRelationsEndpoint.OperationId, - ]; + // Wolverine's default System.Text.Json settings for messages; PartyPublishedLanguageSchemaTests proves they still + // write the names Wolverine writes (ADR 0036). + private static readonly JsonSerializerOptions _wire = new(JsonSerializerOptions.Default) + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + }; + + private static Task Specification => + BianSpecifications.LoadAsync(PartyReferenceDataDirectoryCatalogue.ServiceDomain); [Fact] public async Task The_mapped_routes_conform_to_the_BIAN_specification() { await using var host = await server.StartHostAsync(); - var specification = await BianSpecifications.LoadAsync("PartyReferenceDataDirectory"); var routes = ImplementedRoute.From(host.Alba.Services.GetRequiredService()); - routes.ShouldConformTo(specification, _implemented); + routes.ShouldConformTo(await Specification, PartyReferenceDataDirectoryCatalogue.Implemented); + } + + [Fact] + public async Task The_request_and_response_bodies_and_success_statuses_conform_to_the_BIAN_specification() + { + await using var host = await server.StartHostAsync(); + var json = host.Alba.Services.GetRequiredService>().Value.SerializerOptions; + + var endpoints = ImplementedEndpoint.From(host.Alba.Services.GetRequiredService()); + + endpoints.ShouldHaveBodiesConformingTo(await Specification, json, PartyReferenceDataDirectoryConformanceDeviations.All); + } + + [Fact] + public async Task The_published_event_payloads_conform_to_the_BIAN_AsyncAPI_specification() + { + PartyReferenceDataDirectoryCatalogue.Published.ShouldHavePayloadsConformingTo( + await Specification, + _wire, + PartyReferenceDataDirectoryConformanceDeviations.All); } } diff --git a/tests/RimBank.Api.Tests/packages.lock.json b/tests/RimBank.Api.Tests/packages.lock.json index d33a50e..1dcab38 100644 --- a/tests/RimBank.Api.Tests/packages.lock.json +++ b/tests/RimBank.Api.Tests/packages.lock.json @@ -1206,6 +1206,7 @@ "dependencies": { "Microsoft.OpenApi": "[2.13.0, )", "Microsoft.OpenApi.YamlReader": "[2.13.0, )", + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "YamlDotNet": "[18.1.0, )" } diff --git a/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json b/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json index 18984cc..d1aa7d9 100644 --- a/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json +++ b/tests/RimBank.Architecture.Tests/packages.linux-x64.lock.json @@ -1550,6 +1550,7 @@ "dependencies": { "Microsoft.OpenApi": "[2.13.0, )", "Microsoft.OpenApi.YamlReader": "[2.13.0, )", + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "YamlDotNet": "[18.1.0, )" } @@ -1559,7 +1560,6 @@ "dependencies": { "Microsoft.AspNetCore.Mvc.Testing": "[10.0.14, )", "RimBank.Conformance.Testing": "[0.1.0-alpha, )", - "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "xunit.v3": "[4.0.2, )" } diff --git a/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json b/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json index e196589..9b04925 100644 --- a/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json +++ b/tests/RimBank.Architecture.Tests/packages.win-x64.lock.json @@ -1550,6 +1550,7 @@ "dependencies": { "Microsoft.OpenApi": "[2.13.0, )", "Microsoft.OpenApi.YamlReader": "[2.13.0, )", + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "YamlDotNet": "[18.1.0, )" } @@ -1559,7 +1560,6 @@ "dependencies": { "Microsoft.AspNetCore.Mvc.Testing": "[10.0.14, )", "RimBank.Conformance.Testing": "[0.1.0-alpha, )", - "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "xunit.v3": "[4.0.2, )" } diff --git a/tests/RimBank.Conformance.Testing/AsyncApiSpecificationReader.cs b/tests/RimBank.Conformance.Testing/AsyncApiSpecificationReader.cs index 084e11b..1ef3f60 100644 --- a/tests/RimBank.Conformance.Testing/AsyncApiSpecificationReader.cs +++ b/tests/RimBank.Conformance.Testing/AsyncApiSpecificationReader.cs @@ -1,38 +1,41 @@ -using YamlDotNet.RepresentationModel; +using System.Text.Json.Nodes; namespace RimBank.Conformance.Testing; /// -/// Reads the channels of a BIAN ext-DDD AsyncAPI 3 (YAML) specification with YamlDotNet (ADR 0020). Only -/// channels.*.address is read; every other field is ignored. A channel without an address uses its key. +/// Reads the channels of a BIAN ext-DDD AsyncAPI 3 (YAML) specification (ADR 0020, ADR 0037): each channel's +/// address (its key when it has none) and the payload schema of its first message. Every other field is ignored. /// internal static class AsyncApiSpecificationReader { public static async Task> ReadAsync(FileInfo file, CancellationToken cancellationToken) { - var yaml = new YamlStream(); - using (var reader = file.OpenText()) - { - yaml.Load(new StringReader(await reader.ReadToEndAsync(cancellationToken))); - } - - if (yaml.Documents.FirstOrDefault()?.RootNode is not YamlMappingNode root - || !root.Children.TryGetValue(new YamlScalarNode("channels"), out var channelsNode) - || channelsNode is not YamlMappingNode channels) + var tree = await SpecificationDocument.LoadAsync(file, cancellationToken); + if (tree.Root["channels"] is not JsonObject channels) { throw new InvalidOperationException($"The AsyncAPI specification '{file.FullName}' has no 'channels' mapping."); } return [ - .. channels.Children.Select(channel => new BianChannel(AddressOf(channel.Key, channel.Value))), + .. channels.Select(channel => new BianChannel(AddressOf(channel.Key, channel.Value)) + { + Payload = PayloadOf(tree, channel.Value), + }), ]; } - private static string AddressOf(YamlNode key, YamlNode channel) => - channel is YamlMappingNode mapping - && mapping.Children.TryGetValue(new YamlScalarNode("address"), out var address) - && address is YamlScalarNode { Value: { Length: > 0 } value } - ? value - : ((YamlScalarNode)key).Value ?? string.Empty; + private static string AddressOf(string key, JsonNode? channel) => + channel?["address"] is JsonValue address && address.GetValue() is { Length: > 0 } value ? value : key; + + private static BianSchema? PayloadOf(SpecificationDocument tree, JsonNode? channel) + { + if (tree.Resolve(channel)?["messages"] is not JsonObject { Count: > 0 } messages) + { + return null; + } + + var message = tree.Resolve(messages.First().Value); + return BianSchema.From(tree, message?["payload"], (message?["name"] as JsonValue)?.GetValue() ?? messages.First().Key); + } } diff --git a/tests/RimBank.Conformance.Testing/BianConformance.Bodies.cs b/tests/RimBank.Conformance.Testing/BianConformance.Bodies.cs new file mode 100644 index 0000000..a1dbe4f --- /dev/null +++ b/tests/RimBank.Conformance.Testing/BianConformance.Bodies.cs @@ -0,0 +1,205 @@ +using System.Reflection; +using System.Text.Json; +using System.Text.RegularExpressions; +using Shouldly; + +namespace RimBank.Conformance.Testing; + +/// The body, status and payload conformance assertions (roadmap 1.14, ADR 0037). +public static partial class BianConformance +{ + private const string ChannelField = "Channel"; + + /// + /// Asserts that the bodies and success statuses of a context's endpoints conform to its BIAN OpenAPI specification: + /// + /// every endpoint under /<ServiceDomain>/ declares at least one 2xx response, and each one is a 2xx the specification declares for that operation; + /// an endpoint reads a JSON body exactly when the specification declares one; + /// every property of its request and 2xx response bodies, as writes them, exists in the BIAN schema at the same JSON path, with the exact name and a compatible JSON type; + /// every row about a request or response is still needed, and cites an ADR. + /// + /// Routes that are not an operation of the specification are left to . + /// + /// The endpoints the application maps (). + /// The service domain's specification. + /// The serializer options the application writes HTTP bodies with. + /// The context's ADR-decided deviations. + /// At least one problem was found; the message lists all of them. + public static void ShouldHaveBodiesConformingTo( + this IEnumerable endpoints, + BianServiceDomainSpecification specification, + JsonSerializerOptions json, + IEnumerable deviations) + { + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(specification); + ArgumentNullException.ThrowIfNull(json); + ArgumentNullException.ThrowIfNull(deviations); + + var checkedOperations = new List(); + var found = new List<(ConformanceDeviation At, string Message)>(); + foreach (var endpoint in endpoints.Where(endpoint => InServiceDomain(specification, endpoint.Route)).Distinct()) + { + if (specification.Operations.FirstOrDefault(operation => + operation.Method == endpoint.Route.Method && operation.Path.Equals(endpoint.Route.Route)) is not { } operation) + { + continue; + } + + checkedOperations.Add(operation.OperationId); + found.AddRange(BodyProblems(operation, endpoint, json)); + } + + var listed = deviations.Where(deviation => deviation.Part is ConformancePart.Request or ConformancePart.Response).ToList(); + Report(specification, Unexcused(found, listed, checkedOperations)); + } + + /// + /// Asserts that the payloads of a context's published integration events conform to its BIAN AsyncAPI specification: + /// each event declares a Channel constant that is a channel of the specification, and every property it puts on + /// the wire, as writes it, exists in the channel's payload schema at the same JSON path, + /// compared without regard to case (events are camelCase on the wire, ADR 0036), with a compatible JSON type. Every + /// row about a payload must still be needed and cite an ADR. + /// + /// The event types the context publishes. + /// The service domain's specification. + /// The serializer options the bus writes messages with. + /// The context's ADR-decided deviations. + /// At least one problem was found; the message lists all of them. + public static void ShouldHavePayloadsConformingTo( + this IEnumerable publishedEvents, + BianServiceDomainSpecification specification, + JsonSerializerOptions wire, + IEnumerable deviations) + { + ArgumentNullException.ThrowIfNull(publishedEvents); + ArgumentNullException.ThrowIfNull(specification); + ArgumentNullException.ThrowIfNull(wire); + ArgumentNullException.ThrowIfNull(deviations); + + var checkedChannels = new List(); + var found = new List<(ConformanceDeviation At, string Message)>(); + foreach (var published in publishedEvents.Distinct()) + { + if (published.GetField(ChannelField, BindingFlags.Public | BindingFlags.Static)?.GetRawConstantValue() is not string address) + { + found.Add((new(published.Name, ConformancePart.Payload, "$", string.Empty), $"{published.Name} declares no public const string {ChannelField} (ADR 0036).")); + continue; + } + + var at = new ConformanceDeviation(address, ConformancePart.Payload, "$", string.Empty); + checkedChannels.Add(address); + if (specification.Channels.FirstOrDefault(channel => channel.Address == address) is not { } channel) + { + found.Add((at, $"{published.Name} is published on '{address}', which is not a channel of the BIAN AsyncAPI specification.")); + } + else if (channel.Payload is not { } payload) + { + found.Add((at, $"{published.Name} is published on '{address}', whose BIAN message declares no payload schema.")); + } + else + { + found.AddRange(SchemaSubset.Compare(published, wire, payload, StringComparison.OrdinalIgnoreCase) + .Select(problem => (at with { JsonPath = problem.JsonPath }, $"{published.Name} on {address}: {problem.JsonPath}: {problem.Message}"))); + } + } + + var listed = deviations.Where(deviation => deviation.Part == ConformancePart.Payload).ToList(); + Report(specification, Unexcused(found, listed, checkedChannels)); + } + + private static bool InServiceDomain(BianServiceDomainSpecification specification, ImplementedRoute route) => + string.Equals(route.Route.FirstSegment, specification.ServiceDomain, StringComparison.OrdinalIgnoreCase); + + private static IEnumerable<(ConformanceDeviation At, string Message)> BodyProblems(BianOperation operation, ImplementedEndpoint endpoint, JsonSerializerOptions json) + { + var id = operation.OperationId; + var request = new ConformanceDeviation(id, ConformancePart.Request, "$", string.Empty); + var response = request with { Part = ConformancePart.Response }; + + if (endpoint.RequestType is { } requestType) + { + if (operation.RequestBody is not { } requestBody) + { + yield return (request, $"{id} reads a {requestType.Name} body but the BIAN specification declares no request body."); + } + else + { + foreach (var problem in SchemaSubset.Compare(requestType, json, requestBody, StringComparison.Ordinal)) + { + yield return (request with { JsonPath = problem.JsonPath }, $"{id} request {requestType.Name}: {problem.JsonPath}: {problem.Message}"); + } + } + } + + else if (operation.RequestBody is not null) + { + yield return (request, $"{id} ({endpoint}) reads no JSON body but the BIAN specification declares one; bind the body as a parameter or declare it with .Accepts()."); + } + + var successes = endpoint.SuccessResponses.ToList(); + if (successes.Count == 0) + { + yield return (response, $"{id} ({endpoint}) declares no 2xx response; declare its success body with .Produces(status)."); + } + + foreach (var success in successes) + { + if (!operation.SuccessResponses.TryGetValue(success.StatusCode, out var schema)) + { + yield return (response, $"{id} answers {success.StatusCode} but the BIAN specification declares {Statuses(operation)}."); + } + else if (success.Type is { } responseType && schema is null) + { + yield return (response, $"{id} answers {success.StatusCode} with a {responseType.Name} body but the BIAN specification declares no body for it."); + } + else if (success.Type is { } bodyType && schema is not null) + { + foreach (var problem in SchemaSubset.Compare(bodyType, json, schema, StringComparison.Ordinal)) + { + yield return (response with { JsonPath = problem.JsonPath }, $"{id} {success.StatusCode} {bodyType.Name}: {problem.JsonPath}: {problem.Message}"); + } + } + } + } + + private static string Statuses(BianOperation operation) => + operation.SuccessResponses.Count == 0 ? "no 2xx response" : string.Join(" or ", operation.SuccessResponses.Keys.Order()); + + // Drops the problems a listed deviation excuses, then adds a problem for each listed deviation that excused nothing + // on a checked target, or that cites no ADR. + private static List Unexcused( + List<(ConformanceDeviation At, string Message)> found, + List listed, + List checkedTargets) + { + var excused = listed.ToHashSet(DeviationKey.Instance); + List problems = + [ + .. found.Where(problem => !excused.Contains(problem.At)) + .Select(problem => problem.Message + $" If this is deliberate, list it as a deviation ({problem.At}) citing the ADR that decides it."), + ]; + + var occurred = found.Select(problem => problem.At).ToHashSet(DeviationKey.Instance); + problems.AddRange(listed + .Where(deviation => checkedTargets.Contains(deviation.Target, StringComparer.Ordinal) && !occurred.Contains(deviation)) + .Select(deviation => $"The deviation {deviation} no longer occurs; remove it from the list.")); + problems.AddRange(listed + .Where(deviation => !AdrCitation().IsMatch(deviation.Reason)) + .Select(deviation => $"The deviation {deviation} cites no ADR; its reason must name the ADR that decides it (\"ADR 0024: …\").")); + return problems; + } + + [GeneratedRegex(@"\bADR \d{4}\b")] + private static partial Regex AdrCitation(); + + private sealed class DeviationKey : IEqualityComparer + { + public static readonly DeviationKey Instance = new(); + + public bool Equals(ConformanceDeviation? x, ConformanceDeviation? y) => + x is not null && y is not null && x.Target == y.Target && x.Part == y.Part && x.JsonPath == y.JsonPath; + + public int GetHashCode(ConformanceDeviation obj) => HashCode.Combine(obj.Target, obj.Part, obj.JsonPath); + } +} diff --git a/tests/RimBank.Conformance.Testing/BianConformance.cs b/tests/RimBank.Conformance.Testing/BianConformance.cs index 9604cc6..3c15f3b 100644 --- a/tests/RimBank.Conformance.Testing/BianConformance.cs +++ b/tests/RimBank.Conformance.Testing/BianConformance.cs @@ -7,7 +7,7 @@ namespace RimBank.Conformance.Testing; /// with , reads its routes with ImplementedRoute.From, and /// declares the BIAN operations and channels it implements. Every problem found is reported in one failure. /// -public static class BianConformance +public static partial class BianConformance { private const string Get = "GET"; diff --git a/tests/RimBank.Conformance.Testing/BianOperation.cs b/tests/RimBank.Conformance.Testing/BianOperation.cs index af42d71..ead7c83 100644 --- a/tests/RimBank.Conformance.Testing/BianOperation.cs +++ b/tests/RimBank.Conformance.Testing/BianOperation.cs @@ -22,10 +22,23 @@ public sealed record BianOperation(string OperationId, string Method, RouteTempl /// for a Retrieve operation, otherwise . public BianOperationKind Kind => Action == "Retrieve" ? BianOperationKind.Query : BianOperationKind.Command; + /// The schema of its JSON request body, or when it has none (ADR 0037). + public BianSchema? RequestBody { get; init; } + + /// + /// Its success (2xx) responses: status code to JSON body schema, for a response without a body. + /// Where BIAN wires a 2xx to an error response, the operation's own response component is used (ADR 0037). + /// + public IReadOnlyDictionary SuccessResponses { get; init; } = new Dictionary(); + /// public override string ToString() => $"{OperationId} ({Method} {Path})"; } /// One channel of a BIAN ext-DDD AsyncAPI specification, for example PartyReferenceDataDirectoryEntry/Created. /// The channel address. -public sealed record BianChannel(string Address); +public sealed record BianChannel(string Address) +{ + /// The schema of the payload of its message, or when it declares none (ADR 0037). + public BianSchema? Payload { get; init; } +} diff --git a/tests/RimBank.Conformance.Testing/BianSchema.cs b/tests/RimBank.Conformance.Testing/BianSchema.cs new file mode 100644 index 0000000..0e236ff --- /dev/null +++ b/tests/RimBank.Conformance.Testing/BianSchema.cs @@ -0,0 +1,63 @@ +using System.Text.Json.Nodes; + +namespace RimBank.Conformance.Testing; + +/// +/// A JSON schema of a BIAN specification: the body of an operation or the payload of a channel (ADR 0037). Its +/// $refs are resolved within its own document as the schema is walked, so recursive ISO 20022 types are fine. +/// +public sealed class BianSchema +{ + private readonly SpecificationDocument _document; + private readonly JsonObject _node; + + private BianSchema(SpecificationDocument document, JsonObject node, string name) + { + _document = document; + _node = node; + Name = name; + } + + /// The schema's name: the last segment of its $ref, for example RegisterPartyReferenceDataDirectoryEntry. + public string Name { get; } + + /// The JSON type the schema declares (object, array, string, …), object when it only lists properties, or when it allows anything. + public string? Type => + _node["type"] is JsonValue type ? type.GetValue() + : _node["properties"] is JsonObject ? "object" + : null; + + /// The names of its properties, in specification order. + public IReadOnlyList PropertyNames => + _node["properties"] is JsonObject properties ? [.. properties.Select(property => property.Key)] : []; + + /// The schema of its array items, or . + public BianSchema? Items => From(_document, _node["items"], Name + "[]"); + + /// + /// Whether it is one of BIAN's generated enum wrappers: an object with a single string property, such as + /// Partytypevalues: { Partytypevalues: Person | Organisation }. RimBank flattens these to plain strings (ADR 0024). + /// + public bool IsEnumWrapper => + Type == "object" && PropertyNames is [var only] && Property(only, StringComparison.Ordinal)?.Type == "string"; + + /// The schema of one of its properties, or when it has no such property. + /// The property name. + /// How names are compared: exact for HTTP bodies, ignoring case for event payloads. + public BianSchema? Property(string name, StringComparison comparison) => + _node["properties"] is JsonObject properties + && properties.FirstOrDefault(property => string.Equals(property.Key, name, comparison)) is { Key: not null } match + ? From(_document, match.Value, match.Key) + : null; + + /// + public override string ToString() => Name; + + internal static BianSchema? From(SpecificationDocument document, JsonNode? node, string fallbackName) + { + var name = node is JsonObject { } mapping && mapping["$ref"] is JsonValue reference + ? reference.GetValue()[(reference.GetValue().LastIndexOf('/') + 1)..] + : fallbackName; + return document.Resolve(node) is JsonObject resolved ? new BianSchema(document, resolved, name) : null; + } +} diff --git a/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs b/tests/RimBank.Conformance.Testing/Catalogues/PartyReferenceDataDirectoryCatalogue.cs similarity index 82% rename from tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs rename to tests/RimBank.Conformance.Testing/Catalogues/PartyReferenceDataDirectoryCatalogue.cs index cb8724c..2a157c1 100644 --- a/tests/RimBank.Conformance.Tests/Catalogues/PartyReferenceDataDirectoryCatalogue.cs +++ b/tests/RimBank.Conformance.Testing/Catalogues/PartyReferenceDataDirectoryCatalogue.cs @@ -1,7 +1,6 @@ -using RimBank.Conformance.Testing; using RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage; -namespace RimBank.Conformance.Tests; +namespace RimBank.Conformance.Testing; /// One BIAN operation of a service domain, as an ADR maps it. /// The BIAN operation id, for example Associations/Register. @@ -17,7 +16,9 @@ public sealed record CataloguedChannel(string Address, string Phase, Type? Publi // Roadmap 1.1: the operation and channel tables of ADR 0024 (docs/adr/0024-party-reference-data-directory-mapping.md) // as data, pinned to the real BIAN v14 specifications by PartyReferenceDataDirectoryCatalogueTests. -// A phase that changes the mapping updates the ADR and this table in the same pull request. +// A phase that changes the mapping updates the ADR and this table in the same pull request. Since roadmap 1.14 it +// lives in the shared harness, and the context's conformance tests in RimBank.Api.Tests declare what they implement +// and publish from it (ADR 0037), so the ADR, the routing table and the published language cannot drift apart. public static class PartyReferenceDataDirectoryCatalogue { /// The BIAN service domain name. @@ -48,6 +49,14 @@ public static class PartyReferenceDataDirectoryCatalogue new("PartyReferenceDataDirectoryEntry/Exchange", BianOperationKind.Command, Deferred), ]; + /// The operations implemented so far: every row that is not . + public static IReadOnlyList Implemented => + [.. Operations.Where(row => row.Phase != Deferred).Select(row => row.OperationId)]; + + /// The integration events published so far: the event type of every channel that is not . + public static IReadOnlyList Published => + [.. Channels.Where(row => row.Phase != Deferred).Select(row => row.PublishedEvent).OfType()]; + /// Every channel of the AsyncAPI specification. public static IReadOnlyList Channels { get; } = [ diff --git a/tests/RimBank.Conformance.Testing/ConformanceDeviation.cs b/tests/RimBank.Conformance.Testing/ConformanceDeviation.cs new file mode 100644 index 0000000..6341a6c --- /dev/null +++ b/tests/RimBank.Conformance.Testing/ConformanceDeviation.cs @@ -0,0 +1,29 @@ +namespace RimBank.Conformance.Testing; + +/// Which body of an operation or channel a is about. +public enum ConformancePart +{ + /// The JSON request body of an operation. + Request, + + /// A JSON success (2xx) response body of an operation. + Response, + + /// The payload of a published integration event on a channel. + Payload, +} + +/// +/// A deliberate difference between a RimBank body and its BIAN schema, decided in an ADR (ADR 0037): a field RimBank +/// must carry that BIAN does not declare, or a field shaped differently. A listed deviation exempts exactly the +/// problem at its JSON path; a deviation that no longer occurs fails, so the list stays true. +/// +/// The BIAN operation id (for example PartyReferenceDataDirectoryEntry/Register) or channel address. +/// The body the deviation is in. +/// The JSON path of the field, as the conformance failure prints it, for example $.DemographicsId. +/// Why, citing the ADR that decided it (ADR 0024: …). +public sealed record ConformanceDeviation(string Target, ConformancePart Part, string JsonPath, string Reason) +{ + /// + public override string ToString() => $"{Target} {Part.ToString().ToLowerInvariant()} {JsonPath}"; +} diff --git a/tests/RimBank.Conformance.Testing/ImplementedEndpoint.cs b/tests/RimBank.Conformance.Testing/ImplementedEndpoint.cs new file mode 100644 index 0000000..ff9642c --- /dev/null +++ b/tests/RimBank.Conformance.Testing/ImplementedEndpoint.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Metadata; +using Microsoft.AspNetCore.Routing; + +namespace RimBank.Conformance.Testing; + +/// A response an endpoint declares: its status code and its body type, when it has no body. +/// The HTTP status code. +/// The CLR type of its JSON body, or . +public sealed record ImplementedResponse(int StatusCode, Type? Type); + +/// +/// An endpoint a context maps, with the body types it declares (ADR 0037): the request type minimal APIs infer from its +/// body parameter () and the responses of its .Produces<T>() calls +/// (). +/// +/// Its method and route template. +/// The CLR type of its JSON request body, or when it reads none. +/// The responses it declares. +public sealed record ImplementedEndpoint(ImplementedRoute Route, Type? RequestType, IReadOnlyList Responses) +{ + /// The 2xx responses it declares. + public IEnumerable SuccessResponses => Responses.Where(response => response.StatusCode is >= 200 and < 300); + + /// Reads the endpoints of a running application's routing table, without sending a request. + /// The application's endpoint data source. + /// One endpoint per route endpoint and HTTP method. Endpoints without an HTTP method are skipped. + public static IReadOnlyList From(EndpointDataSource endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + return From(endpoints.Endpoints); + } + + /// Reads the endpoints mapped on an endpoint route builder before the application starts. + /// The endpoint route builder. + /// One endpoint per route endpoint and HTTP method. Endpoints without an HTTP method are skipped. + public static IReadOnlyList From(IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + return From(endpoints.DataSources.SelectMany(source => source.Endpoints)); + } + + /// + public override string ToString() => Route.ToString(); + + private static ImplementedEndpoint[] From(IEnumerable endpoints) => + [ + .. endpoints + .OfType() + .SelectMany(endpoint => (endpoint.Metadata.GetMetadata()?.HttpMethods ?? []) + .Select(method => new ImplementedEndpoint( + new ImplementedRoute(method.ToUpperInvariant(), RouteTemplate.Parse(endpoint.RoutePattern.RawText ?? string.Empty)), + endpoint.Metadata.GetMetadata()?.RequestType, + [ + .. endpoint.Metadata.GetOrderedMetadata() + .Select(response => new ImplementedResponse( + response.StatusCode, + response.Type is null || response.Type == typeof(void) ? null : response.Type)), + ]))), + ]; +} diff --git a/tests/RimBank.Conformance.Testing/OpenApiSpecificationReader.cs b/tests/RimBank.Conformance.Testing/OpenApiSpecificationReader.cs index 4a5f5d3..0323f95 100644 --- a/tests/RimBank.Conformance.Testing/OpenApiSpecificationReader.cs +++ b/tests/RimBank.Conformance.Testing/OpenApiSpecificationReader.cs @@ -1,34 +1,99 @@ +using System.Globalization; +using System.Text.Json.Nodes; using Microsoft.OpenApi; using Microsoft.OpenApi.Reader; namespace RimBank.Conformance.Testing; -/// Reads the operations of a BIAN ext-DDD OpenAPI (YAML) specification with Microsoft.OpenApi (ADR 0020). +/// +/// Reads the operations of a BIAN ext-DDD OpenAPI (YAML) specification with Microsoft.OpenApi (ADR 0020), and their +/// request and success response body schemas from the same file read as a JSON tree (ADR 0037). +/// internal static class OpenApiSpecificationReader { + private const string ErrorSchema = "HTTPError"; + public static async Task> ReadAsync(FileInfo file, CancellationToken cancellationToken) { var settings = new OpenApiReaderSettings(); settings.AddYamlReader(); - await using var stream = file.OpenRead(); - var result = await OpenApiDocument.LoadAsync(stream, "yaml", settings, cancellationToken); - var errors = result.Diagnostic?.Errors ?? []; - if (result.Document is not { } document || errors.Count > 0) + OpenApiDocument document; + await using (var stream = file.OpenRead()) { - throw new InvalidOperationException( - $"The OpenAPI specification '{file.FullName}' could not be read:{Environment.NewLine}" - + string.Join(Environment.NewLine, errors.Select(error => $"- {error.Pointer}: {error.Message}"))); + var result = await OpenApiDocument.LoadAsync(stream, "yaml", settings, cancellationToken); + var errors = result.Diagnostic?.Errors ?? []; + if (result.Document is not { } loaded || errors.Count > 0) + { + throw new InvalidOperationException( + $"The OpenAPI specification '{file.FullName}' could not be read:{Environment.NewLine}" + + string.Join(Environment.NewLine, errors.Select(error => $"- {error.Pointer}: {error.Message}"))); + } + + document = loaded; } + var tree = await SpecificationDocument.LoadAsync(file, cancellationToken); return [ .. (document.Paths ?? []) .SelectMany(path => (path.Value.Operations ?? []) - .Select(operation => new BianOperation( - operation.Value.OperationId ?? $"{operation.Key} {path.Key}", - operation.Key.Method.ToUpperInvariant(), - RouteTemplate.Parse(path.Key)))), + .Select(operation => Operation( + tree, + path.Key, + operation.Key.Method, + operation.Value.OperationId ?? $"{operation.Key} {path.Key}"))), ]; } + + private static BianOperation Operation(SpecificationDocument tree, string path, string method, string operationId) + { + var node = tree.Root["paths"]?[path]?[method.ToLowerInvariant()] as JsonObject; + var operation = new BianOperation(operationId, method.ToUpperInvariant(), RouteTemplate.Parse(path)); + return operation with + { + RequestBody = BodyOf(tree, node?["requestBody"], operationId + " request"), + SuccessResponses = SuccessResponsesOf(tree, node?["responses"] as JsonObject, operation), + }; + } + + private static Dictionary SuccessResponsesOf(SpecificationDocument tree, JsonObject? responses, BianOperation operation) + { + var success = new Dictionary(); + foreach (var (code, response) in responses ?? new JsonObject()) + { + if (int.TryParse(code, NumberStyles.None, CultureInfo.InvariantCulture, out var status) && status is >= 200 and < 300) + { + var body = BodyOf(tree, response, $"{operation.OperationId} {status}"); + success[status] = body?.Name == ErrorSchema ? OwnResponseOf(tree, operation) : body; + } + } + + return success; + } + + // BIAN v14 wires the 200 of some Control Record operations to the BadRequest response (an HTTPError body), while + // their own response component, named Response like every other operation's, is left unused. + private static BianSchema? OwnResponseOf(SpecificationDocument tree, BianOperation operation) + { + var record = operation.OperationId[..operation.OperationId.IndexOf('/', StringComparison.Ordinal)]; + var name = $"{operation.Action}{record}Response"; + return tree.At("#/components/responses/" + name) is { } own + ? BodyOf(tree, own, name) + : null; + } + + // A request body or response: its content's JSON media type (BIAN writes the key as 'application/json:'), or the + // first media type when none is JSON. + private static BianSchema? BodyOf(SpecificationDocument tree, JsonNode? bodyOrReference, string name) + { + if (tree.Resolve(bodyOrReference)?["content"] is not JsonObject content || content.Count == 0) + { + return null; + } + + var media = content.FirstOrDefault(entry => entry.Key.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)); + var schema = (media.Key is null ? content.First().Value : media.Value)?["schema"]; + return BianSchema.From(tree, schema, name); + } } diff --git a/tests/RimBank.Conformance.Testing/RimBank.Conformance.Testing.csproj b/tests/RimBank.Conformance.Testing/RimBank.Conformance.Testing.csproj index 59bcf77..36aa9ec 100644 --- a/tests/RimBank.Conformance.Testing/RimBank.Conformance.Testing.csproj +++ b/tests/RimBank.Conformance.Testing/RimBank.Conformance.Testing.csproj @@ -4,6 +4,8 @@ specifications from doc-0/release14.0.0/ and asserts that the routes and channels a context implements exist in them, with the spec's method, and that Retrieve operations are GET queries and every other operation a command. A class library that each context's .Api.Tests references; its own tests live in RimBank.Conformance.Tests. + Since roadmap 1.14 it also checks request, response and event payload bodies against the BIAN schemas, and holds + each context's ADR operation and channel catalogue (Catalogues/), which references its .PublishedLanguage (ADR 0037). --> RimBank.Conformance.Testing @@ -19,4 +21,8 @@ + + + + diff --git a/tests/RimBank.Conformance.Testing/SchemaSubset.cs b/tests/RimBank.Conformance.Testing/SchemaSubset.cs new file mode 100644 index 0000000..f6317c2 --- /dev/null +++ b/tests/RimBank.Conformance.Testing/SchemaSubset.cs @@ -0,0 +1,99 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Schema; + +namespace RimBank.Conformance.Testing; + +/// One way a RimBank body is not a subset of its BIAN schema. +/// Where, for example $.PartyReference.PartyName. +/// What is wrong. +internal sealed record SchemaProblem(string JsonPath, string Message); + +/// +/// Compares the JSON schema of a RimBank type, as System.Text.Json writes it, to a BIAN schema (ADR 0037). Every +/// property RimBank writes must exist in the BIAN schema at the same path with a compatible JSON type; fewer properties +/// is always fine. The walk follows the RimBank schema, which is finite, so recursive BIAN types need no guard. +/// +internal static class SchemaSubset +{ + private const int MaxDepth = 32; + + private static readonly JsonSchemaExporterOptions _exporter = new() { TreatNullObliviousAsNonNullable = true }; + + public static IReadOnlyList Compare(Type type, JsonSerializerOptions options, BianSchema bian, StringComparison names) + { + var problems = new List(); + Walk(JsonSchemaExporter.GetJsonSchemaAsNode(options, type, _exporter), bian, "$", names, problems, depth: 0); + return problems; + } + + private static void Walk(JsonNode? rimbank, BianSchema bian, string path, StringComparison names, List problems, int depth) + { + if (depth > MaxDepth || bian.Type is null || rimbank is not JsonObject) + { + return; + } + + foreach (var kind in KindsOf(rimbank)) + { + if (Problem(kind, bian) is { } mismatch) + { + problems.Add(new SchemaProblem(path, mismatch)); + continue; + } + + if (kind == "object" && rimbank?["properties"] is JsonObject properties) + { + foreach (var (name, property) in properties) + { + var path2 = $"{path}.{name}"; + if (bian.Property(name, names) is { } match) + { + Walk(property, match, path2, names, problems, depth + 1); + } + else + { + problems.Add(new SchemaProblem( + path2, + $"'{name}' is not a property of the BIAN schema {bian.Name}. Its properties are: {string.Join(", ", bian.PropertyNames)}.")); + } + } + } + else if (kind == "array" && bian.Items is { } items) + { + Walk(rimbank?["items"], items, path + "[*]", names, problems, depth + 1); + } + } + } + + // The JSON types RimBank may write at this node. A nullable type also allows null, which BIAN never forbids, and a + // number read leniently from a string (JsonSerializerDefaults.Web) is still written as a number. A schema without a + // type (a $ref back into a recursive RimBank type), like the schema `true` of a JsonElement passthrough, allows + // anything and is not compared. + private static List KindsOf(JsonNode? rimbank) + { + var kinds = rimbank?["type"] switch + { + JsonValue single => new List { single.GetValue() }, + JsonArray many => many.Select(kind => kind!.GetValue()).ToList(), + _ => new List(), + }; + kinds.Remove("null"); + if (kinds.Contains("string") && (kinds.Contains("integer") || kinds.Contains("number"))) + { + kinds.Remove("string"); + } + + return kinds; + } + + private static string? Problem(string kind, BianSchema bian) => (kind, bian.Type) switch + { + (_, _) when kind == bian.Type => null, + ("integer", "number") => null, + ("string", "object") when bian.IsEnumWrapper => null, + _ => $"RimBank writes a JSON {kind} where the BIAN schema {bian.Name} declares {Article(bian.Type!)} {bian.Type}.", + }; + + private static string Article(string type) => type is ['a' or 'e' or 'i' or 'o' or 'u', ..] ? "an" : "a"; +} diff --git a/tests/RimBank.Conformance.Testing/SpecificationDocument.cs b/tests/RimBank.Conformance.Testing/SpecificationDocument.cs new file mode 100644 index 0000000..2e58e05 --- /dev/null +++ b/tests/RimBank.Conformance.Testing/SpecificationDocument.cs @@ -0,0 +1,94 @@ +using System.Text.Json.Nodes; +using YamlDotNet.RepresentationModel; + +namespace RimBank.Conformance.Testing; + +/// +/// A BIAN YAML specification read as a JSON tree, so OpenAPI and AsyncAPI schemas are walked the same way (ADR 0037). +/// Scalars are kept as strings: the harness reads only type, properties, items and $ref. +/// A key repeated in one mapping keeps its last value. Local $refs (#/components/…) are resolved on demand. +/// +internal sealed class SpecificationDocument +{ + private const int MaxReferenceChain = 32; + + private SpecificationDocument(FileInfo file, JsonNode root) + { + File = file; + Root = root; + } + + public FileInfo File { get; } + + public JsonNode Root { get; } + + public static async Task LoadAsync(FileInfo file, CancellationToken cancellationToken) + { + var yaml = new YamlStream(); + using (var reader = file.OpenText()) + { + yaml.Load(new StringReader(await reader.ReadToEndAsync(cancellationToken))); + } + + var root = yaml.Documents.FirstOrDefault()?.RootNode is { } node + ? ToJson(node) ?? new JsonObject() + : new JsonObject(); + return new SpecificationDocument(file, root); + } + + /// Follows $ref until a node without one, or when a reference cannot be resolved. + public JsonNode? Resolve(JsonNode? node) + { + for (var hops = 0; hops < MaxReferenceChain; hops++) + { + if (node is not JsonObject mapping || mapping["$ref"] is not JsonValue reference) + { + return node; + } + + node = At(reference.GetValue()); + } + + throw new InvalidOperationException($"A $ref chain in '{File.FullName}' is longer than {MaxReferenceChain} hops."); + } + + /// The node at a local JSON pointer such as #/components/schemas/Party, or . + public JsonNode? At(string pointer) + { + if (!pointer.StartsWith("#/", StringComparison.Ordinal)) + { + return null; + } + + JsonNode? node = Root; + foreach (var segment in pointer[2..].Split('/')) + { + var key = segment.Replace("~1", "/", StringComparison.Ordinal).Replace("~0", "~", StringComparison.Ordinal); + node = node is JsonObject mapping ? mapping[key] : null; + } + + return node; + } + + private static JsonNode? ToJson(YamlNode node) => node switch + { + YamlMappingNode mapping => ToJson(mapping), + YamlSequenceNode sequence => new JsonArray([.. sequence.Children.Select(ToJson)]), + YamlScalarNode { Value: { } value } => JsonValue.Create(value), + _ => null, + }; + + private static JsonObject ToJson(YamlMappingNode mapping) + { + var json = new JsonObject(); + foreach (var (key, value) in mapping.Children) + { + if (key is YamlScalarNode { Value: { } name }) + { + json[name] = ToJson(value); + } + } + + return json; + } +} diff --git a/tests/RimBank.Conformance.Testing/packages.lock.json b/tests/RimBank.Conformance.Testing/packages.lock.json index cbe2543..9104c8b 100644 --- a/tests/RimBank.Conformance.Testing/packages.lock.json +++ b/tests/RimBank.Conformance.Testing/packages.lock.json @@ -65,6 +65,9 @@ "dependencies": { "System.CodeDom": "6.0.0" } + }, + "rimbank.party.partyreferencedatadirectory.publishedlanguage": { + "type": "Project" } } } diff --git a/tests/RimBank.Conformance.Tests/FakeContexts/FakeContext.cs b/tests/RimBank.Conformance.Tests/FakeContexts/FakeContext.cs index f0a6387..acb8378 100644 --- a/tests/RimBank.Conformance.Tests/FakeContexts/FakeContext.cs +++ b/tests/RimBank.Conformance.Tests/FakeContexts/FakeContext.cs @@ -21,4 +21,34 @@ public static async Task> MapAsync(params (strin return ImplementedRoute.From(app); } + + /// + /// Maps endpoints with no-op handlers that declare the given request and success response types, as a context's + /// .Produces<T>() and inferred body parameter would, and reads them back with their metadata. + /// + public static async Task> MapEndpointsAsync(params FakeEndpoint[] endpoints) + { + var builder = WebApplication.CreateSlimBuilder(); + await using var app = builder.Build(); + foreach (var endpoint in endpoints) + { + var mapped = app.MapMethods(endpoint.Route, [endpoint.Method], () => Results.NoContent()); + if (endpoint.Request is { } request) + { + mapped.Accepts(request, "application/json"); + } + + if (endpoint.Status is { } status) + { + mapped.Produces(status, endpoint.Response); + } + + mapped.ProducesProblem(StatusCodes.Status400BadRequest); + } + + return ImplementedEndpoint.From(app); + } } + +/// One endpoint of a fake context: its route, request body type and one declared response. +internal sealed record FakeEndpoint(string Method, string Route, Type? Request = null, int? Status = StatusCodes.Status200OK, Type? Response = null); diff --git a/tests/RimBank.Conformance.Tests/FakeContexts/FakeContextBodyConformanceTests.cs b/tests/RimBank.Conformance.Tests/FakeContexts/FakeContextBodyConformanceTests.cs new file mode 100644 index 0000000..bc5bc5b --- /dev/null +++ b/tests/RimBank.Conformance.Tests/FakeContexts/FakeContextBodyConformanceTests.cs @@ -0,0 +1,177 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Http; +using RimBank.Conformance.Testing; + +namespace RimBank.Conformance.Tests; + +// Roadmap 1.14: the body, status and payload assertions pass a conforming fake context and fail each kind of +// non-conformance with a message that names the BIAN operation or channel and the JSON path (ADR 0037). +public sealed class FakeContextBodyConformanceTests +{ + private const string Register = "PartyReferenceDataDirectoryEntry/Register"; + private const string RegisterRoute = "/PartyReferenceDataDirectory/Register"; + private const string Created = "PartyReferenceDataDirectoryEntry/Created"; + private const string Adr = "ADR 0024: a test deviation"; + + private static readonly JsonSerializerOptions _http = JsonSerializerOptions.Default; + private static readonly JsonSerializerOptions _wire = new(JsonSerializerOptions.Default) { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + + private static Task Party => BianSpecifications.LoadAsync("PartyReferenceDataDirectory"); + + [Fact] + public async Task A_conforming_subset_passes() + { + var endpoints = await FakeContext.MapEndpointsAsync( + new FakeEndpoint("POST", RegisterRoute, typeof(ConformingRegister), Response: typeof(ConformingRegister)), + new FakeEndpoint("GET", "/PartyReferenceDataDirectory/{id}/Retrieve", Response: typeof(ConformingRegister))); + + endpoints.ShouldHaveBodiesConformingTo(await Party, _http, []); + } + + [Fact] + public async Task Endpoints_outside_the_service_domain_or_the_spec_are_ignored() + { + var endpoints = await FakeContext.MapEndpointsAsync( + new FakeEndpoint("POST", "/mcp", typeof(RegisterWithExtraProperty), Status: null), + new FakeEndpoint("POST", "/PartyReferenceDataDirectory/{id}/Archive", typeof(RegisterWithExtraProperty))); + + endpoints.ShouldHaveBodiesConformingTo(await Party, _http, []); + } + + [Fact] + public async Task A_request_property_that_BIAN_does_not_declare_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(RegisterWithExtraProperty))); + + var failure = Should.Throw(async () => endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [])); + + failure.Message.ShouldContain("failed with 1 problem(s)"); + failure.Message.ShouldContain($"{Register} request RegisterWithExtraProperty: $.Archived: 'Archived' is not a property of the BIAN schema RegisterPartyReferenceDataDirectoryEntry"); + failure.Message.ShouldContain($"({Register} request $.Archived)"); + } + + [Fact] + public async Task A_nested_response_property_that_BIAN_does_not_declare_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(ConformingRegister), Response: typeof(RegisterWithExtraNestedProperty))); + + var failure = Should.Throw(async () => endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [])); + + failure.Message.ShouldContain($"{Register} 200 RegisterWithExtraNestedProperty: $.PartyReference.Nickname: 'Nickname' is not a property of the BIAN schema Party"); + } + + [Fact] + public async Task An_incompatible_JSON_type_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(RegisterWithWrongType))); + + var failure = Should.Throw(async () => endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [])); + + failure.Message.ShouldContain("$.PartyReference: RimBank writes a JSON string where the BIAN schema Party declares an object."); + } + + [Fact] + public async Task A_success_status_that_BIAN_does_not_declare_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(ConformingRegister), StatusCodes.Status201Created, typeof(ConformingRegister))); + + var failure = Should.Throw(async () => endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [])); + + failure.Message.ShouldContain($"{Register} answers 201 but the BIAN specification declares 200."); + } + + [Fact] + public async Task An_endpoint_without_a_declared_success_response_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(ConformingRegister), Status: null)); + + var failure = Should.Throw(async () => endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [])); + + failure.Message.ShouldContain($"{Register} (POST {RegisterRoute}) declares no 2xx response"); + } + + [Fact] + public async Task A_command_that_reads_no_body_where_BIAN_declares_one_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, Response: typeof(ConformingRegister))); + + var failure = Should.Throw(async () => endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [])); + + failure.Message.ShouldContain("failed with 1 problem(s)"); + failure.Message.ShouldContain($"{Register} (POST {RegisterRoute}) reads no JSON body but the BIAN specification declares one"); + } + + [Fact] + public async Task A_query_that_reads_a_body_where_BIAN_declares_none_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync( + new FakeEndpoint("GET", "/PartyReferenceDataDirectory/{id}/Retrieve", typeof(ConformingRegister), Response: typeof(ConformingRegister))); + + var failure = Should.Throw(async () => endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [])); + + failure.Message.ShouldContain("PartyReferenceDataDirectoryEntry/Retrieve reads a ConformingRegister body but the BIAN specification declares no request body."); + } + + [Fact] + public async Task A_listed_deviation_excuses_exactly_its_path() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(RegisterWithExtraProperty))); + + endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [new(Register, ConformancePart.Request, "$.Archived", Adr)]); + Should.Throw(async () => + endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [new(Register, ConformancePart.Response, "$.Archived", Adr)])); + } + + [Fact] + public async Task A_listed_deviation_that_no_longer_occurs_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(ConformingRegister))); + + var failure = Should.Throw(async () => + endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [new(Register, ConformancePart.Request, "$.Archived", Adr)])); + + failure.Message.ShouldContain($"The deviation {Register} request $.Archived no longer occurs; remove it from the list."); + } + + [Fact] + public async Task A_listed_deviation_without_an_ADR_fails() + { + var endpoints = await FakeContext.MapEndpointsAsync(new FakeEndpoint("POST", RegisterRoute, typeof(RegisterWithExtraProperty))); + + var failure = Should.Throw(async () => + endpoints.ShouldHaveBodiesConformingTo(await Party, _http, [new(Register, ConformancePart.Request, "$.Archived", "we needed it")])); + + failure.Message.ShouldContain($"The deviation {Register} request $.Archived cites no ADR"); + } + + [Fact] + public async Task A_payload_matching_BIAN_names_without_regard_to_case_passes() + { + Type[] published = [typeof(ConformingCreated)]; + + published.ShouldHavePayloadsConformingTo(await Party, _wire, []); + } + + [Fact] + public async Task A_payload_property_that_BIAN_does_not_declare_fails_unless_listed() + { + Type[] published = [typeof(CreatedWithEventId)]; + + var failure = Should.Throw(async () => published.ShouldHavePayloadsConformingTo(await Party, _wire, [])); + + failure.Message.ShouldContain($"CreatedWithEventId on {Created}: $.eventId: 'eventId' is not a property of the BIAN schema PartyReferenceDataDirectoryEntry"); + published.ShouldHavePayloadsConformingTo(await Party, _wire, [new(Created, ConformancePart.Payload, "$.eventId", Adr)]); + } + + [Fact] + public async Task A_payload_on_an_unknown_channel_or_without_a_channel_fails() + { + Type[] published = [typeof(Deleted), typeof(Unchannelled)]; + + var failure = Should.Throw(async () => published.ShouldHavePayloadsConformingTo(await Party, _wire, [])); + + failure.Message.ShouldContain("failed with 2 problem(s)"); + failure.Message.ShouldContain("Deleted is published on 'PartyReferenceDataDirectoryEntry/Deleted', which is not a channel of the BIAN AsyncAPI specification."); + failure.Message.ShouldContain("Unchannelled declares no public const string Channel"); + } +} diff --git a/tests/RimBank.Conformance.Tests/FakeContexts/FakeModels.cs b/tests/RimBank.Conformance.Tests/FakeContexts/FakeModels.cs new file mode 100644 index 0000000..cc83c6f --- /dev/null +++ b/tests/RimBank.Conformance.Tests/FakeContexts/FakeModels.cs @@ -0,0 +1,53 @@ +using System.Text.Json; + +namespace RimBank.Conformance.Tests; + +// Test-only bodies for the fake context, shaped against the real BIAN Party Reference Data Directory schemas +// (RegisterPartyReferenceDataDirectoryEntry, Party, PartyReferenceDataDirectoryEntry). C# property names are the JSON +// names, because the self-tests write HTTP bodies with JsonSerializerOptions.Default (no naming policy). + +/// +/// A subset of BIAN's Register body: an enum wrapper flattened to a string, a date, a nested Party, and a field accepted +/// as any JSON (a passthrough). +/// +internal sealed record ConformingRegister( + string PartyType, + DateTimeOffset DirectoryEntryDate, + ConformingParty? PartyReference = null, + JsonElement? DirectoryEntryDateType = null); + +/// A subset of BIAN's Party. +internal sealed record ConformingParty(string Identification); + +/// Register with a property BIAN does not declare. +internal sealed record RegisterWithExtraProperty(string PartyType, bool Archived); + +/// Register whose nested Party has a property BIAN does not declare. +internal sealed record RegisterWithExtraNestedProperty(string PartyType, PartyWithNickname PartyReference); + +/// A Party with a property BIAN does not declare. +internal sealed record PartyWithNickname(string Identification, string Nickname); + +/// Register whose PartyReference is a string where BIAN declares a Party object. +internal sealed record RegisterWithWrongType(string PartyType, string PartyReference); + +/// A published event whose camelCase wire names match BIAN's PascalCase payload names. +internal sealed record ConformingCreated(string PartyType, DateTimeOffset DirectoryEntryDate) +{ + public const string Channel = "PartyReferenceDataDirectoryEntry/Created"; +} + +/// A published event with a field BIAN's payload does not declare. +internal sealed record CreatedWithEventId(Guid EventId, string PartyType) +{ + public const string Channel = "PartyReferenceDataDirectoryEntry/Created"; +} + +/// A published event on a channel BIAN does not declare. +internal sealed record Deleted(string PartyType) +{ + public const string Channel = "PartyReferenceDataDirectoryEntry/Deleted"; +} + +/// A published event without a channel. +internal sealed record Unchannelled(string PartyType); diff --git a/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj b/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj index 0d93c33..696e911 100644 --- a/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj +++ b/tests/RimBank.Conformance.Tests/RimBank.Conformance.Tests.csproj @@ -20,7 +20,6 @@ - diff --git a/tests/RimBank.Conformance.Tests/Specifications/PartyReferenceDataDirectorySpecificationTests.cs b/tests/RimBank.Conformance.Tests/Specifications/PartyReferenceDataDirectorySpecificationTests.cs index db902ac..23d626d 100644 --- a/tests/RimBank.Conformance.Tests/Specifications/PartyReferenceDataDirectorySpecificationTests.cs +++ b/tests/RimBank.Conformance.Tests/Specifications/PartyReferenceDataDirectorySpecificationTests.cs @@ -91,6 +91,53 @@ public async Task The_AsyncAPI_specification_has_a_created_and_an_updated_channe ignoreOrder: true); } + [Fact] + public async Task Register_reads_its_request_body_with_the_JSON_media_type_BIAN_writes_with_a_colon() + { + var specification = await BianSpecifications.LoadAsync(ServiceDomain); + + var body = specification.Operation("PartyReferenceDataDirectoryEntry/Register").ShouldNotBeNull().RequestBody.ShouldNotBeNull(); + body.Name.ShouldBe("RegisterPartyReferenceDataDirectoryEntry"); + body.Type.ShouldBe("object"); + body.PropertyNames.ShouldBe(["PartyReference", "DirectoryEntryDateType", "DirectoryEntryDate", "PartyType"]); + body.Property("PartyType", StringComparison.Ordinal).ShouldNotBeNull().IsEnumWrapper.ShouldBeTrue(); + body.Property("DirectoryEntryDate", StringComparison.Ordinal).ShouldNotBeNull().Type.ShouldBe("string"); + body.Property("PartyReference", StringComparison.Ordinal).ShouldNotBeNull().Name.ShouldBe("Party"); + } + + [Theory] + [InlineData("PartyReferenceDataDirectoryEntry/Register", "RegisterPartyReferenceDataDirectoryEntry")] + [InlineData("PartyReferenceDataDirectoryEntry/Update", "UpdatePartyReferenceDataDirectoryEntry")] + public async Task A_200_that_BIAN_wires_to_BadRequest_uses_the_operations_own_response(string operationId, string schema) + { + var specification = await BianSpecifications.LoadAsync(ServiceDomain); + + var success = specification.Operation(operationId).ShouldNotBeNull().SuccessResponses; + success.Keys.ShouldBe([200]); + success[200].ShouldNotBeNull().Name.ShouldBe(schema); + } + + [Fact] + public async Task A_query_reads_its_200_response_and_has_no_request_body() + { + var specification = await BianSpecifications.LoadAsync(ServiceDomain); + + var retrieve = specification.Operation("Reference/Retrieve").ShouldNotBeNull(); + retrieve.RequestBody.ShouldBeNull(); + retrieve.SuccessResponses[200].ShouldNotBeNull().PropertyNames.ShouldContain("PartyFullLegalName"); + } + + [Fact] + public async Task A_channel_reads_its_message_payload() + { + var specification = await BianSpecifications.LoadAsync(ServiceDomain); + + var payload = specification.Channels.Single(channel => channel.Address == "PartyReferenceDataDirectoryEntry/Created").Payload.ShouldNotBeNull(); + payload.Name.ShouldBe("PartyReferenceDataDirectoryEntry"); + payload.Property("partyType", StringComparison.OrdinalIgnoreCase).ShouldNotBeNull().Type.ShouldBe("string"); + specification.Channels.ShouldAllBe(channel => channel.Payload != null); + } + [Fact] public async Task A_service_domain_is_read_once() { diff --git a/tests/RimBank.Conformance.Tests/packages.lock.json b/tests/RimBank.Conformance.Tests/packages.lock.json index 603dcac..7243e30 100644 --- a/tests/RimBank.Conformance.Tests/packages.lock.json +++ b/tests/RimBank.Conformance.Tests/packages.lock.json @@ -188,6 +188,7 @@ "dependencies": { "Microsoft.OpenApi": "[2.13.0, )", "Microsoft.OpenApi.YamlReader": "[2.13.0, )", + "RimBank.Party.PartyReferenceDataDirectory.PublishedLanguage": "[0.1.0-alpha, )", "Shouldly": "[4.3.0, )", "YamlDotNet": "[18.1.0, )" }