From 47c86dfe28713d946f2c96d8472efa06dcb75053 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Fri, 6 Nov 2026 16:08:43 +0100 Subject: [PATCH 01/11] [Add] Integration test plan for the REST client against Flexo (#407) --- .../INTEGRATION_TEST_PLAN.md | 626 ++++++++++++++++++ 1 file changed, 626 insertions(+) create mode 100644 SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md new file mode 100644 index 000000000..aca146f5d --- /dev/null +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -0,0 +1,626 @@ +# REST client integration test plan — building a complete SysML v2 model against Flexo + +Issue: #407 — *Verify REST Api client against compliant server*. + +## 1. Goal + +One integration scenario that, through `SysML2.NET.REST` only, **builds a model step by step on a +live Flexo server** until it contains an instance of every KerML / SysML v2 metaclass, and that on +the way **calls every operation of the OpenAPI document** — creating, reading, updating and +deleting both model elements and API objects (projects, branches, tags, commits, queries). + +Nothing is pre-seeded: Flexo starts empty and the scenario is the seed. Each step commits the next +part of the model, reads it back, and asserts it against what was sent and against the +specification. + +### What is under test + +**The system under test is the SysML2.NET REST client** — `SysML2.NET.REST` (`Session`, +`PsmApiClient`, `QueryStringBuilder`) together with the JSON serializer and deserializer it uses +for request and response bodies. A step passes when our client sends what the OpenAPI document +specifies, and turns what the server returns into the right DTOs, including paging, error and +merge-conflict handling. + +**Flexo is the counterpart, not the subject.** It is there because the client can only be +checked against a real server; it stands in for any compliant implementation. So: + +- Expectations come from the specifications, never from what Flexo happens to do. +- A difference is triaged (§8) and never absorbed by weakening an assertion: either our client is + wrong (we fix it), or Flexo is (we record it, report it upstream, and keep the scenario running). + +### Non-goals + +- **Verifying Flexo.** The scenario does not set out to test Flexo's correctness or completeness. + It covers only the server behaviour our client depends on, and finds Flexo issues only as a side + effect of that. +- **Claiming conformance** of the client or the serializer. This adds their first write → re-read → + same-model tests; it does not cover per-invariant metamodel semantics. + +## 2. Coverage target and its sources + +| Axis | Count | Source of truth | +|---|---:|---| +| Concrete metaclasses | 167 | Hypha `hypha:metamodel-lookup`, release **2026-07**; identical to the 167 classes in `SysML2.NET/Core/AutoGenDto/` | +| Abstract metaclasses | 8 | Hypha 2026-07 — covered through concrete subclasses (Appendix A.2) | +| Non-derived attributes | 97 | Hypha 2026-07 (Appendix A.3) | +| Enumerations / literals | 7 / 21 | Hypha 2026-07 (Appendix A.4) | +| PIM types | 17 + PSM `Error` | `SysML2.NET/PIM/DTO/` (from `ptc/25-02-29`) | +| PIM enumerations | 4 | `Operator` (7), `JoinOperator` (2), `Direction` (3), `ChangeType` (3) | +| API operations | 35 | `Resources/ptc-25-02-30.json` = `IPsmApiClient` (Appendix C) | + +Hypha does not cover the API & Services specification: PIM facts come from `ptc/25-02-29` and the +specification PDF, PSM facts from the OpenAPI document (CLAUDE.md, "PIM vs PSM"). + +The appendices are the progress checklist; the final step (§5, step 14) enforces them at run time. + +## 3. Test environment + +### 3.1 Flexo host — `Integration/FlexoTestHost.cs` + +Testcontainers, three containers on one network, following `TESTING.md` §10 and +`PostgreSqlSchemaTestHost`: + +| Container | Image (pinned) | Role | +|---|---|---| +| quad store | `atomgraph/fuseki:4.6` | triplestore, loaded from `cluster.trig` | +| layer1 | `openmbee/flexo-mms-layer1-service:v0.3.0` | Flexo MMS core | +| SysML v2 | `openmbee/flexo-sysmlv2:v0.2.1` | the API under test | + +- `cluster.trig` and the env values are copied from the Flexo `v0.2.1` tag into + `SySML2.NET.REST.Tests/Resources/Flexo/` (Apache-2.0; attribution in `NOTICE`). The file holds + only users, access control and the metaclass vocabulary — no model data. +- Readiness: poll `GET /projects` until 200. Bootstrap: `PUT {layer1}/orgs/sysmlv2` through a plain + `HttpClient` — layer1 is not the SysML v2 API and stays outside the client under test. +- Docker unavailable → `Assert.Ignore`. `[Category("Integration")]`, which CI already excludes. +- Fresh containers per run: every run starts from an empty server. + +### 3.2 Client wiring + +A test `IHttpClientFactory` returns an `HttpClient` whose handler chain is: + +1. **`BearerTokenHandler`** — adds `Authorization: Bearer `, the token generated in the test + from the shared HMAC secret (Flexo requires it; `Session` has no auth option — separate issue). +2. **`EndpointRecorder`** — records `(method, path template, status)` of every request by matching + the URL against the path templates of `Resources/ptc-25-02-30.json`. Step 14 uses it. + +The scenario then uses the production entry point unchanged: +`new Session(factory, deSerializer, serializer).Open(flexoUri, …)`. + +## 4. How the model is built + +### 4.1 Scenario state and the model builder + +- **`ScenarioState`** (one per fixture) — server-assigned ids (projects, branches, tags, commits, + queries), plus a local **expected model**: the DTOs as they should exist at each commit. +- **`ModelBuilder`** — creates DTOs with readable deterministic ids (UUID v5 of + `"/"`), and wires ownership consistently: owner `ownedRelationship` (ordered) ⇄ + membership `ownedRelatedElement` ⇄ member `owningRelationship`. A step only describes *what* it + adds; the builder produces the `DataVersionRequest`s for the commit. +- Payloads are `Core.DTO` elements (`Core.DTO.IElement` implements `IDataRequest`). `PsmApiClient` + serializes them without derived properties, and `ComparerProvider` (`SysML2.NET.Extensions`) + compares non-derived content — the two agree. + +### 4.2 Modelling rules + +1. Each step's model extends the previous one: later steps type, specialize, redefine and connect + what earlier steps created — so a SysML `PartUsage` in step 6 is typed by a `PartDefinition` + from step 6 and nested in packages from step 2. +2. **Self-contained**: no model-library references (`ScalarValues`, `Parts::Part`, …) — Flexo has no + libraries loaded. Implied relationships (`isImplied = true`) are not sent. +3. Before writing a step, look every metaclass it adds up with **`hypha:metamodel-lookup`** (owned + and inherited features, multiplicities, ordering, redefinitions); use the + **`hypha:metamodel-navigator`** agent for a whole metamodel package; satisfy every lower bound. +4. Write the step's model as textual notation too and validate it with + **`hypha:sysml-validation`**; attach the report to the review, not to the code. +5. Consult **`hypha:spec-citation`** where well-formedness depends on prose (connector ends, + conjugation, `namingFeature`). +6. Across the scenario, every attribute in A.3 gets a non-default value at least once, and every + literal in A.4 appears at least once. + +### 4.3 What every model step asserts + +After each commit: + +- `PostCommitByProjectAsync` returned a commit on the expected branch whose `previousCommits` is + the previous head; the branch `head` moved (`GetBranchesByProjectAndIdAsync`). +- `GetChangesByProjectCommitAsync` / `GetChangeByProjectCommitIdAsync` → exactly the sent + `DataVersion`s. +- `GetElementByProjectCommitIdAsync` for each element of the step → equal to the expected DTO under + `ComparerProvider`. +- `GetElementsByProjectCommitAsync`, paged (`page[size]=25`, following `Link` to the end) → exactly + the expected id set at that commit, no duplicates. +- `GetRootsByProjectCommitAsync` → only the root package. +- `GetRelationshipsByProjectCommitRelatedElementAsync`, `Direction` `in` / `out` / `both`, for the + step's relationship ends. +- History is immutable: one element of an earlier commit is re-read at that commit and is unchanged. + +Comparisons over a list of elements run inside `Assert.EnterMultipleScope`, so one run reports +every failing metaclass, not just the first. + +## 5. The scenario + +`FlexoModelScenarioTestFixture` — `[Category("Integration")]`, one `[Test]` per step ordered with +`[Order(n)]` (precedent: `SqlSchemaBenchmarkTestFixture`). `[SetUp]` ignores a step when an +earlier step failed (`Assert.Ignore("step N failed")`), so a failure is reported once, at its +origin. + +| # | Step | Model content | Operations exercised (Appendix C #) | +|---:|---|---|---| +| 1 | **Empty server** | — | `GET /meta/datatypes` (34), by id (35); `GET /projects` is empty (1); unknown project → 404 `Error` (3) | +| 2 | **Project and root model** | `POST`/`GET`/`PUT` project (2, 3, 4, 1); commit on the default branch: root `Package`, nested `Package`s, `Namespace`, `LibraryPackage`, `AnnotatingElement`, `Comment`, `Documentation`, `TextualRepresentation`, `Annotation`, `OwningMembership`, `Membership`, `NamespaceImport`, `MembershipImport`, `Dependency`, `ElementFilterMembership` (Root, Packages — 14) | 15, 14, 16, 17, 18, 19, 20, 22, 23 | +| 3 | **KerML Core** | `Type`, `Classifier`, `Feature`, `Specialization`, `Subclassification`, `FeatureTyping`, `Subsetting`, `Redefinition`, `ReferenceSubsetting`, `CrossSubsetting`, `Conjugation`, `Disjoining`, `Differencing`, `Intersecting`, `Unioning`, `FeatureChaining`, `FeatureInverting`, `TypeFeaturing`, `FeatureMembership`, `EndFeatureMembership`, `Multiplicity` (21) — typing and specializing step-2 content | as step 2 | +| 4 | **KerML Kernel** | data types, classes, structures, associations, connectors, behaviors, steps, functions, all expression and literal kinds, feature values, multiplicity ranges, interactions, flows, metaclasses and metadata (43); then **tag** `kernel` on this commit | as step 2; `POST`/`GET` tags (11, 10, 12) | +| 5 | **Update the KerML model** | U1–U4 (§6.1) on step 2–4 content | 15, 17, 20; `DiffAsync` `kernel` → head shows `UPDATED` (24) | +| 6 | **Branch, SysML structure** | **branch** `systems` from head (7, 6, 8); commits with `branchId`: definitions and usages, attributes, enumerations, occurrences, items, parts, ports (incl. conjugated), connections, interfaces, allocations, flows (31) | 15 with `branchId`; as step 2 on the branch | +| 7 | **SysML behaviour and requirements** | actions (all node and loop kinds), states and transitions, calculations, constraints, requirements, concerns, cases, analysis / verification / use cases, views, viewpoints, renderings, metadata (58) | as step 6 | +| 8 | **Merge** | update the same element on default and on `systems` → merge reports the conflict (`MergeConflictException`, `MergeResult.conflict`); merge again with a resolution body; then a clean merge of the remaining `systems` work; U1–U2 on SysML content after merge | 25, 24, 8 | +| 9 | **Queries** | `POST` a query with nested `CompositeConstraint` (`AND`, `OR`) and `PrimitiveConstraint`s using all 7 `Operator` literals and `inverse`; `select`, `scope`, `orderBy`; list, get, `PUT`, results three ways, at head and at the `kernel` commit; `DELETE` | 27, 26, 28, 29, 31, 32, 33, 30 | +| 10 | **Project usage** | second project `Library` with a small model; the main model commits a `ProjectUsage` of its head; `excludeUsed` on elements and roots | 2, 15, 21, 19, 22 | +| 11 | **External data** | commit `ExternalData` and `ExternalRelationship`, update both, delete both | 15, 17, 18 | +| 12 | **Delete model elements** | per metamodel package, delete the subjects with their owning memberships (`payload = null`), updating owners' `ownedRelationship` in the same commit; the deleted elements are gone at head and readable at the previous commit; `DiffAsync` shows `DELETED` | 15, 19, 20, 24 | +| 13 | **Tear down** | delete tag (13), branch (9), the `Library` project and the main project (5); each is unreadable afterwards; negative cases (§6.3) | 13, 9, 5, 3, 8, 12 | +| 14 | **Coverage verdict** | — | asserts §7 | + +Step numbers are fixed in Appendix A.1, which assigns every concrete metaclass to the step that +creates it. + +## 6. Update, delete and negative cases + +### 6.1 Update scenarios + +Every concrete metaclass gets U1 and at least one of U2–U4, in step 5 (KerML) or step 8 (SysML). + +| Id | Change | Applies to | +|---|---|---| +| U1 | `declaredName` / `declaredShortName` changed | all 167 | +| U2 | the carried non-derived attribute changed (flip a boolean, another literal value, another enum literal) | every row of A.3 / A.4 | +| U3 | a relationship end retargeted (`FeatureTyping.type`, `Redefinition.redefinedFeature`, …) | the 62 concrete `Relationship` subclasses | +| U4 | an ordered collection reordered, extended and shrunk (`ownedRelationship` of a `Namespace`) | one per metamodel package — ordering survives the round trip | + +### 6.2 Delete scenarios + +- D1 (step 12): a subject deleted together with its owning membership, the owner updated in the + same commit — keeps the model well-formed. +- D2 (step 12): a whole nested package's content deleted in one commit. +- D3 (open question, §9): an owner deleted alone. The API specification does not visibly define a + cascade; read the PIM clause before writing an expectation. + +### 6.3 Negative cases (spread over the steps, every operation has at least one) + +Unknown project / commit / element / branch / tag / query id; commit to an unknown branch; +malformed commit; merge into an unknown branch; reading a deleted project → `PsmApiException` with +status code and parsed `Error` body. + +## 7. Coverage verdict (step 14) + +Computed from what the **server returned**, not from what was sent: + +- **Metaclasses**: the set of `@type`s read back across all commits = every concrete DTO class in + `SysML2.NET.Core.DTO` (generated from the XMI, so a metaclass added to the metamodel fails the + verdict until a step creates it). +- **Attributes**: for every non-derived property (`[Property(isDerived: false)]` on the generated + DTO interfaces), some element read back carried a non-default value, and some update changed it. +- **Literals**: every enumeration literal was read back at least once. +- **Endpoints**: `EndpointRecorder` saw every `(method, path template)` of + `Resources/ptc-25-02-30.json` (35), each with at least one success and one failure status. + +All four lists are self-calibrating: extending the metamodel or the OpenAPI document never needs a +change to the verdict, only to the steps. + +## 8. Handling differences + +| Finding | Action | +|---|---| +| Our client or serializer is wrong per the spec | fix here, with a unit test | +| Flexo diverges from the spec | not a failure of the client, so not a failure of this suite: upstream issue on `Open-MBEE/flexo-mms-sysmlv2`; the case goes in one `KnownServerDivergences` table and is reported through `Assert.Warn` quoting the issue, so later steps still run — the expectation stays spec-based | +| The spec is ambiguous | pick a reading, cite the clause, note in one line that it admits more than one (CLAUDE.md) | + +Known before starting: Flexo's `/meta/datatypes` serves a pre-final schema (`ItemFlow`, +`LifeClass`, …) — step 1 asserts shape only. + +## 9. Open questions + +1. **Delete cascade (D3)** — what the PIM says about deleting an owner without its owned elements. +2. **Query by `@type` and subtypes** — Flexo matches subtypes; check whether the spec requires it. +3. **ProjectUsage / ExternalData / ExternalRelationship on Flexo** — stored generically, untested. +4. **Flexo image** — `v0.2.1` (recommended) or `develop-SNAPSHOT`. +5. **CI** — local only (recommended for now), or a separate opt-in workflow. +6. **One `[Test]` per step vs `TESTING.md` §2** — the scenario's unit is the step, not a client + method; confirm this exception for the integration fixture. + +## 10. Work breakdown + +| Step | Deliverable | Depends on | +|---|---|---| +| 1 | Branch from `origin/development`; `Testcontainers` ``; `FlexoTestHost`, handlers, factory, Flexo resources, `NOTICE` | — | +| 2 | `ScenarioState`, `ModelBuilder`, the step-4.3 read-back assertions; scenario steps 1–2 green | 1 | +| 3 | Step 14 (verdict) — red, listing everything still missing | 2 | +| 4 | Steps 3–4 (KerML), 5 (update) | 2 | +| 5 | Steps 6–8 (SysML, merge) | 4 | +| 6 | Steps 9–13 (queries, usage, external data, delete, teardown) | 2 | +| 7 | Triage (§8): upstream issues, divergence table; verdict green | 3–6 | + +Writing the verdict early (deliverable 3) makes it the to-do list: each later deliverable shrinks +its output. Steps 3, 4, 6 and 7 of the scenario are the bulk of the work (153 of the 167 +metaclasses). + +Per CLAUDE.md: no commits by the agent; the `textual-notation-reviewer` is not required (no +textual-notation paths are touched). + +## Appendix A — metamodel coverage (generated from Hypha, release 2026-07) + +### A.1 Concrete metaclasses (167) + +One row per concrete metaclass. Step = the scenario step (§5) that creates it. Every one is also updated in step 5 or 8 and deleted in step 12. + +| Step | Package | Metaclass | Created | Read back | Updated | Deleted | +|:-:|---|---|:-:|:-:|:-:|:-:| +| 3 | KerML::Core::Classifiers | `Classifier` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Classifiers | `Subclassification` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `CrossSubsetting` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `EndFeatureMembership` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `Feature` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `FeatureChaining` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `FeatureInverting` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `FeatureTyping` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `Redefinition` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `ReferenceSubsetting` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `Subsetting` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Features | `TypeFeaturing` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Conjugation` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Differencing` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Disjoining` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `FeatureMembership` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Intersecting` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Multiplicity` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Specialization` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Type` | ☐ | ☐ | ☐ | ☐ | +| 3 | KerML::Core::Types | `Unioning` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Associations | `Association` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Associations | `AssociationStructure` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Behaviors | `Behavior` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Behaviors | `ParameterMembership` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Behaviors | `Step` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Classes | `Class` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Connectors | `BindingConnector` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Connectors | `Connector` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Connectors | `Succession` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::DataTypes | `DataType` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `CollectExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `ConstructorExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `FeatureChainExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `FeatureReferenceExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `IndexExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `InvocationExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `LiteralBoolean` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `LiteralExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `LiteralInfinity` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `LiteralInteger` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `LiteralRational` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `LiteralString` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `MetadataAccessExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `NullExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `OperatorExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Expressions | `SelectExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::FeatureValues | `FeatureValue` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Functions | `BooleanExpression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Functions | `Expression` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Functions | `Function` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Functions | `Invariant` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Functions | `Predicate` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Functions | `ResultExpressionMembership` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Functions | `ReturnParameterMembership` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Interactions | `Flow` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Interactions | `FlowEnd` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Interactions | `Interaction` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Interactions | `PayloadFeature` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Interactions | `SuccessionFlow` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Metadata | `Metaclass` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Metadata | `MetadataFeature` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Multiplicities | `MultiplicityRange` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Kernel::Packages | `ElementFilterMembership` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Kernel::Packages | `LibraryPackage` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Kernel::Packages | `Package` | ☐ | ☐ | ☐ | ☐ | +| 4 | KerML::Kernel::Structures | `Structure` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Annotations | `AnnotatingElement` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Annotations | `Annotation` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Annotations | `Comment` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Annotations | `Documentation` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Annotations | `TextualRepresentation` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Dependencies | `Dependency` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Namespaces | `Membership` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Namespaces | `MembershipImport` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Namespaces | `Namespace` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Namespaces | `NamespaceImport` | ☐ | ☐ | ☐ | ☐ | +| 2 | KerML::Root::Namespaces | `OwningMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `AcceptActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `ActionDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `ActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `AssignmentActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `DecisionNode` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `ForLoopActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `ForkNode` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `IfActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `JoinNode` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `MergeNode` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `PerformActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `SendActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `TerminateActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `TriggerInvocationExpression` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Actions | `WhileLoopActionUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Allocations | `AllocationDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Allocations | `AllocationUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::AnalysisCases | `AnalysisCaseDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::AnalysisCases | `AnalysisCaseUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Attributes | `AttributeDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Attributes | `AttributeUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Calculations | `CalculationDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Calculations | `CalculationUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Cases | `CaseDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Cases | `CaseUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Cases | `ObjectiveMembership` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Connections | `BindingConnectorAsUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Connections | `ConnectionDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Connections | `ConnectionUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Connections | `SuccessionAsUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Constraints | `AssertConstraintUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Constraints | `ConstraintDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Constraints | `ConstraintUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::DefinitionAndUsage | `Definition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::DefinitionAndUsage | `ReferenceUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::DefinitionAndUsage | `Usage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::DefinitionAndUsage | `VariantMembership` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Enumerations | `EnumerationDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Enumerations | `EnumerationUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Flows | `FlowDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Flows | `FlowUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Flows | `SuccessionFlowUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Interfaces | `InterfaceDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Interfaces | `InterfaceUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Items | `ItemDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Items | `ItemUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Metadata | `MetadataDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Metadata | `MetadataUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Occurrences | `EventOccurrenceUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Occurrences | `OccurrenceDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Occurrences | `OccurrenceUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Parts | `PartDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Parts | `PartUsage` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Ports | `ConjugatedPortDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Ports | `ConjugatedPortTyping` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Ports | `PortConjugation` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Ports | `PortDefinition` | ☐ | ☐ | ☐ | ☐ | +| 6 | SysML::Systems::Ports | `PortUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `ActorMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `ConcernDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `ConcernUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `FramedConcernMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `RequirementConstraintMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `RequirementDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `RequirementUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `SatisfyRequirementUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `StakeholderMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Requirements | `SubjectMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::States | `ExhibitStateUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::States | `StateDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::States | `StateSubactionMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::States | `StateUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::States | `TransitionFeatureMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::States | `TransitionUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::UseCases | `IncludeUseCaseUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::UseCases | `UseCaseDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::UseCases | `UseCaseUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::VerificationCases | `RequirementVerificationMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::VerificationCases | `VerificationCaseDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::VerificationCases | `VerificationCaseUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `MembershipExpose` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `NamespaceExpose` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `RenderingDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `RenderingUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `ViewDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `ViewRenderingMembership` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `ViewUsage` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `ViewpointDefinition` | ☐ | ☐ | ☐ | ☐ | +| 7 | SysML::Systems::Views | `ViewpointUsage` | ☐ | ☐ | ☐ | ☐ | + +### A.2 Abstract metaclasses (8) + +Not instantiable; covered through their concrete subclasses. + +| Package | Metaclass | Concrete subclasses | +|---|---|---| +| KerML::Kernel::Expressions | `InstantiationExpression` | `CollectExpression`, `ConstructorExpression`, `FeatureChainExpression`, `IndexExpression`, `InvocationExpression`, `OperatorExpression` … (8 in total) | +| KerML::Root::Elements | `Element` | `AcceptActionUsage`, `ActionDefinition`, `ActionUsage`, `ActorMembership`, `AllocationDefinition`, `AllocationUsage` … (167 in total) | +| KerML::Root::Elements | `Relationship` | `ActorMembership`, `AllocationDefinition`, `AllocationUsage`, `Annotation`, `Association`, `AssociationStructure` … (62 in total) | +| KerML::Root::Namespaces | `Import` | `MembershipExpose`, `MembershipImport`, `NamespaceExpose`, `NamespaceImport` | +| SysML::Systems::Actions | `ControlNode` | `DecisionNode`, `ForkNode`, `JoinNode`, `MergeNode` | +| SysML::Systems::Actions | `LoopActionUsage` | `ForLoopActionUsage`, `WhileLoopActionUsage` | +| SysML::Systems::Connections | `ConnectorAsUsage` | `AllocationUsage`, `BindingConnectorAsUsage`, `ConnectionUsage`, `FlowUsage`, `InterfaceUsage`, `SuccessionAsUsage` … (7 in total) | +| SysML::Systems::Views | `Expose` | `MembershipExpose`, `NamespaceExpose` | + +### A.3 Non-derived attributes (97) + +Every non-derived attribute declared in the metamodel. Each must be set to a non-default value on at least one created element, and changed on at least one updated element. *Carrier* is the declaring metaclass if it is concrete, otherwise a concrete subclass. + +| Declared on | Attribute | Type | Multiplicity | Carrier | Set | Changed | +|---|---|---|---|---|:-:|:-:| +| `Annotation` | `annotatedElement` | Element | [1..1] | `Annotation` | ☐ | ☐ | +| `CollectExpression` | `operator` | String | [1..1] | `CollectExpression` | ☐ | ☐ | +| `Comment` | `body` | String | [1..1] | `Comment` | ☐ | ☐ | +| `Comment` | `locale` | String | [0..1] | `Comment` | ☐ | ☐ | +| `ConjugatedPortTyping` | `conjugatedPortDefinition` | ConjugatedPortDefinition | [1..1] | `ConjugatedPortTyping` | ☐ | ☐ | +| `Conjugation` | `conjugatedType` | Type | [1..1] | `Conjugation` | ☐ | ☐ | +| `Conjugation` | `originalType` | Type | [1..1] | `Conjugation` | ☐ | ☐ | +| `ConnectionDefinition` | `isSufficient` | Boolean | [1..1] | `ConnectionDefinition` | ☐ | ☐ | +| `CrossSubsetting` | `crossedFeature` | Feature | [1..1] | `CrossSubsetting` | ☐ | ☐ | +| `Definition` | `isVariation` | Boolean | [1..1] | `Definition` | ☐ | ☐ | +| `Dependency` | `client` | Element | [1..*] | `Dependency` | ☐ | ☐ | +| `Dependency` | `supplier` | Element | [1..*] | `Dependency` | ☐ | ☐ | +| `Differencing` | `differencingType` | Type | [1..1] | `Differencing` | ☐ | ☐ | +| `Disjoining` | `disjoiningType` | Type | [1..1] | `Disjoining` | ☐ | ☐ | +| `Disjoining` | `typeDisjoined` | Type | [1..1] | `Disjoining` | ☐ | ☐ | +| `Element` | `aliasIds` | String | [0..*] | `AcceptActionUsage` | ☐ | ☐ | +| `Element` | `declaredName` | String | [0..1] | `AcceptActionUsage` | ☐ | ☐ | +| `Element` | `declaredShortName` | String | [0..1] | `AcceptActionUsage` | ☐ | ☐ | +| `Element` | `elementId` | String | [1..1] | `AcceptActionUsage` | ☐ | ☐ | +| `Element` | `isImpliedIncluded` | Boolean | [1..1] | `AcceptActionUsage` | ☐ | ☐ | +| `Element` | `ownedRelationship` | Relationship (composite) | [0..*] | `AcceptActionUsage` | ☐ | ☐ | +| `Element` | `owningRelationship` | Relationship | [0..1] | `AcceptActionUsage` | ☐ | ☐ | +| `EnumerationDefinition` | `isVariation` | Boolean | [1..1] | `EnumerationDefinition` | ☐ | ☐ | +| `Expose` | `isImportAll` | Boolean | [1..1] | `MembershipExpose` | ☐ | ☐ | +| `Expose` | `visibility` | VisibilityKind | [1..1] | `MembershipExpose` | ☐ | ☐ | +| `Feature` | `direction` | FeatureDirectionKind | [0..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isComposite` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isConstant` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isDerived` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isEnd` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isOrdered` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isPortion` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isUnique` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `Feature` | `isVariable` | Boolean | [1..1] | `Feature` | ☐ | ☐ | +| `FeatureChainExpression` | `operator` | String | [1..1] | `FeatureChainExpression` | ☐ | ☐ | +| `FeatureChaining` | `chainingFeature` | Feature | [1..1] | `FeatureChaining` | ☐ | ☐ | +| `FeatureInverting` | `featureInverted` | Feature | [1..1] | `FeatureInverting` | ☐ | ☐ | +| `FeatureInverting` | `invertingFeature` | Feature | [1..1] | `FeatureInverting` | ☐ | ☐ | +| `FeatureTyping` | `type` | Type | [1..1] | `FeatureTyping` | ☐ | ☐ | +| `FeatureTyping` | `typedFeature` | Feature | [1..1] | `FeatureTyping` | ☐ | ☐ | +| `FeatureValue` | `isDefault` | Boolean | [1..1] | `FeatureValue` | ☐ | ☐ | +| `FeatureValue` | `isInitial` | Boolean | [1..1] | `FeatureValue` | ☐ | ☐ | +| `FramedConcernMembership` | `kind` | RequirementConstraintKind | [1..1] | `FramedConcernMembership` | ☐ | ☐ | +| `Import` | `isImportAll` | Boolean | [1..1] | `MembershipExpose` | ☐ | ☐ | +| `Import` | `isRecursive` | Boolean | [1..1] | `MembershipExpose` | ☐ | ☐ | +| `Import` | `visibility` | VisibilityKind | [1..1] | `MembershipExpose` | ☐ | ☐ | +| `IndexExpression` | `operator` | String | [1..1] | `IndexExpression` | ☐ | ☐ | +| `Intersecting` | `intersectingType` | Type | [1..1] | `Intersecting` | ☐ | ☐ | +| `Invariant` | `isNegated` | Boolean | [1..1] | `Invariant` | ☐ | ☐ | +| `LibraryPackage` | `isStandard` | Boolean | [1..1] | `LibraryPackage` | ☐ | ☐ | +| `LiteralBoolean` | `value` | Boolean | [1..1] | `LiteralBoolean` | ☐ | ☐ | +| `LiteralInteger` | `value` | Integer | [1..1] | `LiteralInteger` | ☐ | ☐ | +| `LiteralRational` | `value` | Real | [1..1] | `LiteralRational` | ☐ | ☐ | +| `LiteralString` | `value` | String | [1..1] | `LiteralString` | ☐ | ☐ | +| `Membership` | `memberElement` | Element | [1..1] | `Membership` | ☐ | ☐ | +| `Membership` | `memberName` | String | [0..1] | `Membership` | ☐ | ☐ | +| `Membership` | `memberShortName` | String | [0..1] | `Membership` | ☐ | ☐ | +| `Membership` | `visibility` | VisibilityKind | [1..1] | `Membership` | ☐ | ☐ | +| `MembershipImport` | `importedMembership` | Membership | [1..1] | `MembershipImport` | ☐ | ☐ | +| `NamespaceImport` | `importedNamespace` | Namespace | [1..1] | `NamespaceImport` | ☐ | ☐ | +| `OccurrenceDefinition` | `isIndividual` | Boolean | [1..1] | `OccurrenceDefinition` | ☐ | ☐ | +| `OccurrenceUsage` | `isIndividual` | Boolean | [1..1] | `OccurrenceUsage` | ☐ | ☐ | +| `OccurrenceUsage` | `portionKind` | PortionKind | [0..1] | `OccurrenceUsage` | ☐ | ☐ | +| `OperatorExpression` | `operator` | String | [1..1] | `OperatorExpression` | ☐ | ☐ | +| `PortConjugation` | `originalPortDefinition` | PortDefinition | [1..1] | `PortConjugation` | ☐ | ☐ | +| `Redefinition` | `redefinedFeature` | Feature | [1..1] | `Redefinition` | ☐ | ☐ | +| `Redefinition` | `redefiningFeature` | Feature | [1..1] | `Redefinition` | ☐ | ☐ | +| `ReferenceSubsetting` | `referencedFeature` | Feature | [1..1] | `ReferenceSubsetting` | ☐ | ☐ | +| `Relationship` | `isImplied` | Boolean | [1..1] | `ActorMembership` | ☐ | ☐ | +| `Relationship` | `ownedRelatedElement` | Element (composite) | [0..*] | `ActorMembership` | ☐ | ☐ | +| `Relationship` | `owningRelatedElement` | Element | [0..1] | `ActorMembership` | ☐ | ☐ | +| `Relationship` | `source` | Element | [0..*] | `ActorMembership` | ☐ | ☐ | +| `Relationship` | `target` | Element | [0..*] | `ActorMembership` | ☐ | ☐ | +| `RequirementConstraintMembership` | `kind` | RequirementConstraintKind | [1..1] | `RequirementConstraintMembership` | ☐ | ☐ | +| `RequirementDefinition` | `reqId` | String | [0..1] | `RequirementDefinition` | ☐ | ☐ | +| `RequirementUsage` | `reqId` | String | [0..1] | `RequirementUsage` | ☐ | ☐ | +| `RequirementVerificationMembership` | `kind` | RequirementConstraintKind | [1..1] | `RequirementVerificationMembership` | ☐ | ☐ | +| `SelectExpression` | `operator` | String | [1..1] | `SelectExpression` | ☐ | ☐ | +| `Specialization` | `general` | Type | [1..1] | `Specialization` | ☐ | ☐ | +| `Specialization` | `specific` | Type | [1..1] | `Specialization` | ☐ | ☐ | +| `StateDefinition` | `isParallel` | Boolean | [1..1] | `StateDefinition` | ☐ | ☐ | +| `StateSubactionMembership` | `kind` | StateSubactionKind | [1..1] | `StateSubactionMembership` | ☐ | ☐ | +| `StateUsage` | `isParallel` | Boolean | [1..1] | `StateUsage` | ☐ | ☐ | +| `Subclassification` | `subclassifier` | Classifier | [1..1] | `Subclassification` | ☐ | ☐ | +| `Subclassification` | `superclassifier` | Classifier | [1..1] | `Subclassification` | ☐ | ☐ | +| `Subsetting` | `subsettedFeature` | Feature | [1..1] | `Subsetting` | ☐ | ☐ | +| `Subsetting` | `subsettingFeature` | Feature | [1..1] | `Subsetting` | ☐ | ☐ | +| `TextualRepresentation` | `body` | String | [1..1] | `TextualRepresentation` | ☐ | ☐ | +| `TextualRepresentation` | `language` | String | [1..1] | `TextualRepresentation` | ☐ | ☐ | +| `TransitionFeatureMembership` | `kind` | TransitionFeatureKind | [1..1] | `TransitionFeatureMembership` | ☐ | ☐ | +| `TriggerInvocationExpression` | `kind` | TriggerKind | [1..1] | `TriggerInvocationExpression` | ☐ | ☐ | +| `Type` | `isAbstract` | Boolean | [1..1] | `Type` | ☐ | ☐ | +| `Type` | `isSufficient` | Boolean | [1..1] | `Type` | ☐ | ☐ | +| `TypeFeaturing` | `featureOfType` | Feature | [1..1] | `TypeFeaturing` | ☐ | ☐ | +| `TypeFeaturing` | `featuringType` | Type | [1..1] | `TypeFeaturing` | ☐ | ☐ | +| `Unioning` | `unioningType` | Type | [1..1] | `Unioning` | ☐ | ☐ | +| `Usage` | `isVariation` | Boolean | [1..1] | `Usage` | ☐ | ☐ | + +### A.4 Enumeration literals (7 enumerations, 21 literals) + +Every literal must appear on at least one created element. + +| Enumeration | Literals | Carried by | +|---|---|---| +| `FeatureDirectionKind` | `in`, `inout`, `out` | `Feature.direction` | +| `PortionKind` | `timeslice`, `snapshot` | `OccurrenceUsage.portionKind` | +| `RequirementConstraintKind` | `assumption`, `requirement` | `FramedConcernMembership.kind`, `RequirementConstraintMembership.kind`, `RequirementVerificationMembership.kind` | +| `StateSubactionKind` | `entry`, `do`, `exit` | `StateSubactionMembership.kind` | +| `TransitionFeatureKind` | `trigger`, `guard`, `effect` | `TransitionFeatureMembership.kind` | +| `TriggerKind` | `when`, `at`, `after` | `TriggerInvocationExpression.kind` | +| `VisibilityKind` | `private`, `protected`, `public` | `Expose.visibility`, `Import.visibility`, `Membership.visibility` | + +## Appendix B — PIM type coverage + +`—` means the API defines no such operation for the type; that is asserted by absence, not tested. + +| PIM type | Create | Read | Update | Delete | Members to assert | +|---|---|---|---|---|---| +| `Project` | `PostProjectAsync` | `GetProjectsAsync`, `GetProjectByIdAsync` | `PutProjectByIdAsync` | `DeleteProjectByIdAsync` | name, description, alias, created, defaultBranch | +| `Branch` | `PostBranchByProjectAsync` | `GetBranchesByProjectAsync`, `GetBranchesByProjectAndIdAsync` | — (head moves by commit / merge) | `DeleteBranchByProjectAndIdAsync` | head, referencedCommit, owningProject, created, deleted | +| `Tag` | `PostTagByProjectAsync` | `GetTagsByProjectAsync`, `GetTagByProjectAndIdAsync` | — | `DeleteTagByProjectAndIdAsync` | taggedCommit / referencedCommit, owningProject, created | +| `CommitReference` (abstract) | via `Branch`, `Tag` | | | | | +| `Record` (abstract) | via every type above | | | | id, name, alias, description, resourceIdentifier | +| `Commit` | `PostCommitByProjectAsync` (with / without `branchId`) | `GetCommitsByProjectAsync`, `GetCommitByProjectAndIdAsync` | — (immutable) | — | owningProject, previousCommits, created, description | +| `DataVersion` | in `Commit.change` | `GetChangesByProjectCommitAsync`, `GetChangeByProjectCommitIdAsync` | new payload, same identity | `payload = null` | identity, payload | +| `DataIdentity` | in `DataVersion.identity` | as above | — | — | id | +| `DataDifference` | — | `DiffAsync` | — | — | baseData, compareData (all three `ChangeType`s) | +| `MergeResult` | `MergeAsync` | — | — | — | mergeCommit, conflict | +| `Query` | `PostQueryByProjectAsync` | `GetQueriesByProjectAsync`, `GetQueryByProjectAndIdAsync` | `PutQueryByProjectAndIdAsync` | `DeleteQueryByProjectAndIdAsync` | select, where, scope, orderBy, project | +| `PrimitiveConstraint` | in `Query.where` | the three query-result operations | via `PUT` query | via `PUT` / `DELETE` query | property, operator (7 literals), value, inverse | +| `CompositeConstraint` | in `Query.where` | as above | as above | as above | constraint (nested), operator (`AND`, `OR`) | +| `ProjectUsage` | commit payload | `GetProjectUsageByProjectCommitElementAsync`, `excludeUsed` | new payload | `payload = null` | usedProject, usedProjectCommit | +| `ExternalData` | commit payload | changes | new payload | `payload = null` | resourceIdentifier | +| `ExternalRelationship` | commit payload | changes | new payload | `payload = null` | elementEnd, externalDataEnd, specification, language | +| `Error` (PSM only) | — | every failing call | — | — | status code, parsed body | + +## Appendix C — operation checklist (35, `IPsmApiClient`) + +*Steps* = scenario steps (§5) that call the operation. Step 14 checks every row has a success and a +failure. + +| # | Operation | Method | Steps | Success | Failure | +|---:|---|---|---|:-:|:-:| +| 1 | `GET /projects` | `GetProjectsAsync` | 1, 2 | ☐ | ☐ | +| 2 | `POST /projects` | `PostProjectAsync` | 2, 10 | ☐ | ☐ | +| 3 | `GET /projects/{projectId}` | `GetProjectByIdAsync` | 1, 2, 13 | ☐ | ☐ | +| 4 | `PUT /projects/{projectId}` | `PutProjectByIdAsync` | 2 | ☐ | ☐ | +| 5 | `DELETE /projects/{projectId}` | `DeleteProjectByIdAsync` | 13 | ☐ | ☐ | +| 6 | `GET …/branches` | `GetBranchesByProjectAsync` | 6 | ☐ | ☐ | +| 7 | `POST …/branches` | `PostBranchByProjectAsync` | 6 | ☐ | ☐ | +| 8 | `GET …/branches/{branchId}` | `GetBranchesByProjectAndIdAsync` | every commit, 13 | ☐ | ☐ | +| 9 | `DELETE …/branches/{branchId}` | `DeleteBranchByProjectAndIdAsync` | 13 | ☐ | ☐ | +| 10 | `GET …/tags` | `GetTagsByProjectAsync` | 4 | ☐ | ☐ | +| 11 | `POST …/tags` | `PostTagByProjectAsync` | 4 | ☐ | ☐ | +| 12 | `GET …/tags/{tagId}` | `GetTagByProjectAndIdAsync` | 4, 13 | ☐ | ☐ | +| 13 | `DELETE …/tags/{tagId}` | `DeleteTagByProjectAndIdAsync` | 13 | ☐ | ☐ | +| 14 | `GET …/commits` | `GetCommitsByProjectAsync` | 2 | ☐ | ☐ | +| 15 | `POST …/commits` | `PostCommitByProjectAsync` | 2–8, 10–12 | ☐ | ☐ | +| 16 | `GET …/commits/{commitId}` | `GetCommitByProjectAndIdAsync` | every commit | ☐ | ☐ | +| 17 | `GET …/commits/{commitId}/changes` | `GetChangesByProjectCommitAsync` | every commit | ☐ | ☐ | +| 18 | `GET …/changes/{changeId}` | `GetChangeByProjectCommitIdAsync` | every commit | ☐ | ☐ | +| 19 | `GET …/commits/{commitId}/elements` | `GetElementsByProjectCommitAsync` | every commit | ☐ | ☐ | +| 20 | `GET …/elements/{elementId}` | `GetElementByProjectCommitIdAsync` | every commit | ☐ | ☐ | +| 21 | `GET …/elements/{elementId}/projectUsage` | `GetProjectUsageByProjectCommitElementAsync` | 10 | ☐ | ☐ | +| 22 | `GET …/commits/{commitId}/roots` | `GetRootsByProjectCommitAsync` | every commit, 10 | ☐ | ☐ | +| 23 | `GET …/elements/{relatedElementId}/relationships` | `GetRelationshipsByProjectCommitRelatedElementAsync` | every commit | ☐ | ☐ | +| 24 | `GET …/commits/{compareCommitId}/diff` | `DiffAsync` | 5, 8, 12 | ☐ | ☐ | +| 25 | `POST …/branches/{targetBranchId}/merge` | `MergeAsync` | 8 | ☐ | ☐ | +| 26 | `GET …/queries` | `GetQueriesByProjectAsync` | 9 | ☐ | ☐ | +| 27 | `POST …/queries` | `PostQueryByProjectAsync` | 9 | ☐ | ☐ | +| 28 | `GET …/queries/{queryId}` | `GetQueryByProjectAndIdAsync` | 9 | ☐ | ☐ | +| 29 | `PUT …/queries/{queryId}` | `PutQueryByProjectAndIdAsync` | 9 | ☐ | ☐ | +| 30 | `DELETE …/queries/{queryId}` | `DeleteQueryByProjectAndIdAsync` | 9 | ☐ | ☐ | +| 31 | `GET …/queries/{queryId}/results` | `GetQueryResultsByProjectIdQueryIdAsync` | 9 | ☐ | ☐ | +| 32 | `GET …/query-results` | `GetQueryResultsByProjectIdQueryAsync` | 9 | ☐ | ☐ | +| 33 | `POST …/query-results` | `GetQueryResultsByProjectIdQueryPostAsync` | 9 | ☐ | ☐ | +| 34 | `GET /meta/datatypes` | `GetDatatypesAsync` | 1 | ☐ | ☐ | +| 35 | `GET /meta/datatypes/{datatypeId}` | `GetDatatypeByIdAsync` | 1 | ☐ | ☐ | + +Every list operation is also exercised with `page[size]`, `page[after]` and `page[before]`. From a3a458f1f1393f68df3de738ed3ac7543fbf9349 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Fri, 6 Nov 2026 16:38:52 +0100 Subject: [PATCH 02/11] [update] test plan --- .../INTEGRATION_TEST_PLAN.md | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index aca146f5d..b48015f2c 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -182,8 +182,15 @@ Every concrete metaclass gets U1 and at least one of U2–U4, in step 5 (KerML) - D1 (step 12): a subject deleted together with its owning membership, the owner updated in the same commit — keeps the model well-formed. - D2 (step 12): a whole nested package's content deleted in one commit. -- D3 (open question, §9): an owner deleted alone. The API specification does not visibly define a - cascade; read the PIM clause before writing an expectation. +- D3 (step 12): **delete cascade**. One commit deletes only an owner with nested content (and its + own owning membership, so its parent stays well-formed); none of its owned elements is listed. At + the new commit, everything in the owner's composition tree is gone: its `ownedRelationship`s, + their `ownedRelatedElement`s, and so on down. Basis: both properties are composite in KerML + (`Element::ownedRelationship`, `Relationship::ownedRelatedElement`; Hypha 2026-07). Asserted on: + - `GetElementByProjectCommitIdAsync` → 404 for every element of the tree; + - `GetElementsByProjectCommitAsync` → the tree's ids are absent, everything else is unchanged; + - `DiffAsync` previous → new commit → `DELETED` for every element of the tree, not only the owner; + - the previous commit still returns the whole tree. ### 6.3 Negative cases (spread over the steps, every operation has at least one) @@ -220,13 +227,11 @@ Known before starting: Flexo's `/meta/datatypes` serves a pre-final schema (`Ite ## 9. Open questions -1. **Delete cascade (D3)** — what the PIM says about deleting an owner without its owned elements. -2. **Query by `@type` and subtypes** — Flexo matches subtypes; check whether the spec requires it. -3. **ProjectUsage / ExternalData / ExternalRelationship on Flexo** — stored generically, untested. -4. **Flexo image** — `v0.2.1` (recommended) or `develop-SNAPSHOT`. -5. **CI** — local only (recommended for now), or a separate opt-in workflow. -6. **One `[Test]` per step vs `TESTING.md` §2** — the scenario's unit is the step, not a client - method; confirm this exception for the integration fixture. +1. **Query by `@type` and subtypes** — Flexo matches subtypes; check whether the spec requires it. +2. **ProjectUsage / ExternalData / ExternalRelationship on Flexo** — stored generically, untested. +3. **Flexo image** — `v0.2.1` (recommended) or `develop-SNAPSHOT`. +4. **CI** — local only (recommended for now), or a separate opt-in workflow. +5. **One `[Test]` per step vs `TESTING.md` §2** — In the scope of this integration test, going again rules defined in the TESTING.md file is accepted. One scenario can be split into multiple [Test] method. A TestOrder need to be correctly settle ## 10. Work breakdown From 95059866b03a2a2eb253783ca6a2dbcc3b245951 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Sat, 7 Nov 2026 20:20:35 +0100 Subject: [PATCH 03/11] =?UTF-8?q?[Add]=20Flexo=20integration=20scenario=20?= =?UTF-8?q?stage=201:=20test=20host,=20OpenAPI=20conformance=20check,=20mo?= =?UTF-8?q?del=20builder,=20steps=20=201=E2=80=932=20and=20coverage=20verd?= =?UTF-8?q?ict=20(#407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Directory.Packages.props | 2 + NOTICE | 6 +- .../Helpers/BearerTokenHandler.cs | 70 + .../Helpers/ContractViolation.cs | 31 + .../Helpers/ContractViolationKind.cs | 57 + .../Helpers/CoverageVerdict.cs | 164 +++ .../Helpers/DeterministicGuid.cs | 60 + SySML2.NET.REST.Tests/Helpers/DtoMetadata.cs | 132 ++ SySML2.NET.REST.Tests/Helpers/EndpointCall.cs | 50 + .../Helpers/EndpointRecorder.cs | 123 ++ SySML2.NET.REST.Tests/Helpers/FlexoJwt.cs | 110 ++ .../Helpers/FlexoTestHost.cs | 389 +++++ .../Helpers/IntegrationHttpClientFactory.cs | 62 + .../Helpers/IsolatedAssertions.cs | 57 + .../Helpers/KnownServerDivergences.cs | 203 +++ .../Helpers/MetamodelProperty.cs | 42 + SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs | 138 ++ .../Helpers/Models/RootModel.cs | 194 +++ .../Helpers/OpenApiConformance.cs | 86 ++ .../Helpers/OpenApiContent.cs | 258 ++++ .../Helpers/OpenApiDocument.cs | 333 +++++ .../Helpers/OpenApiOperation.cs | 232 +++ .../Helpers/OpenApiParameter.cs | 124 ++ .../Helpers/ReadBackAssertions.cs | 366 +++++ .../Helpers/ScenarioState.cs | 50 + .../Helpers/ServerDivergence.cs | 27 + .../BearerTokenHandlerTestFixture.cs | 64 + .../CoverageVerdictTestFixture.cs | 120 ++ .../DeterministicGuidTestFixture.cs | 40 + .../HelpersTests/DtoMetadataTestFixture.cs | 91 ++ .../HelpersTests/EndpointCallTestFixture.cs | 52 + .../EndpointRecorderTestFixture.cs | 106 ++ .../HelpersTests/FlexoJwtTestFixture.cs | 64 + ...IntegrationHttpClientFactoryTestFixture.cs | 77 + .../IsolatedAssertionsTestFixture.cs | 67 + .../KnownServerDivergencesTestFixture.cs | 201 +++ .../HelpersTests/ModelBuilderTestFixture.cs | 90 ++ .../Models/RootModelTestFixture.cs | 56 + .../OpenApiConformanceTestFixture.cs | 70 + .../HelpersTests/OpenApiContentTestFixture.cs | 76 + .../OpenApiDocumentTestFixture.cs | 141 ++ .../OpenApiOperationTestFixture.cs | 144 ++ .../OpenApiParameterTestFixture.cs | 77 + .../ReadBackAssertionsTestFixture.cs | 347 +++++ .../INTEGRATION_TEST_PLAN.md | 158 +- .../FlexoModelScenarioTestFixture.cs | 212 +++ .../Resources/Flexo/cluster.trig | 1311 +++++++++++++++++ .../SySML2.NET.REST.Tests.csproj | 6 + .../TEST_PROJECT_STRUCTURE.md | 167 +++ 49 files changed, 7068 insertions(+), 35 deletions(-) create mode 100644 SySML2.NET.REST.Tests/Helpers/BearerTokenHandler.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/ContractViolation.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/ContractViolationKind.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/DeterministicGuid.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/DtoMetadata.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/EndpointCall.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/FlexoJwt.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/FlexoTestHost.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/IntegrationHttpClientFactory.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/IsolatedAssertions.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/MetamodelProperty.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/OpenApiOperation.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/ScenarioState.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/BearerTokenHandlerTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/DeterministicGuidTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/DtoMetadataTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/EndpointCallTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/FlexoJwtTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/IntegrationHttpClientFactoryTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/IsolatedAssertionsTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/OpenApiConformanceTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/OpenApiParameterTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/Resources/Flexo/cluster.trig create mode 100644 SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md diff --git a/Directory.Packages.props b/Directory.Packages.props index c4ddc91ed..02916f875 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -45,6 +45,7 @@ + @@ -57,6 +58,7 @@ + \ No newline at end of file diff --git a/NOTICE b/NOTICE index 7ff595c78..49bda6c89 100644 --- a/NOTICE +++ b/NOTICE @@ -1,2 +1,6 @@ SysML2.NET -Copyright 2022-2025 Starion Group S.A. \ No newline at end of file +Copyright 2022-2025 Starion Group S.A. + +This product includes the file SySML2.NET.REST.Tests/Resources/Flexo/cluster.trig, taken from +Flexo MMS SysML v2 Microservice (https://github.com/Open-MBEE/flexo-mms-sysmlv2), commit 836d904d, +licensed under the Apache License, Version 2.0. diff --git a/SySML2.NET.REST.Tests/Helpers/BearerTokenHandler.cs b/SySML2.NET.REST.Tests/Helpers/BearerTokenHandler.cs new file mode 100644 index 000000000..64caaa7b9 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/BearerTokenHandler.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading; + using System.Threading.Tasks; + + /// + /// A that adds a bearer token to every request, because the + /// has no authentication option of its own + /// + public sealed class BearerTokenHandler : DelegatingHandler + { + /// + /// The token that is added to every request + /// + private readonly string token; + + /// + /// Initializes a new instance of the class + /// + /// + /// The token that is added to every request + /// + /// + /// The handler that sends the request on + /// + /// + /// Thrown when is null or whitespace + /// + public BearerTokenHandler(string token, HttpMessageHandler innerHandler) : base(innerHandler) + { + if (string.IsNullOrWhiteSpace(token)) + { + throw new ArgumentException("The token may not be null or whitespace", nameof(token)); + } + + this.token = token; + } + + /// + /// Adds the bearer token and sends the request on + /// + /// + /// The request to send + /// + /// + /// The that cancels the operation + /// + /// + /// The response of the server + /// + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.token); + + return base.SendAsync(request, cancellationToken); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ContractViolation.cs b/SySML2.NET.REST.Tests/Helpers/ContractViolation.cs new file mode 100644 index 000000000..79be1caef --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/ContractViolation.cs @@ -0,0 +1,31 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + /// + /// One way in which a request or a response breaks the OpenAPI document + /// + /// + /// The kind of violation + /// + /// + /// What was found, for assertion messages + /// + public sealed record ContractViolation(ContractViolationKind Kind, string Message) + { + /// + /// Returns the violation as Kind: Message + /// + /// + /// The text of the violation + /// + public override string ToString() => $"{this.Kind}: {this.Message}"; + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ContractViolationKind.cs b/SySML2.NET.REST.Tests/Helpers/ContractViolationKind.cs new file mode 100644 index 000000000..7f5965f56 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/ContractViolationKind.cs @@ -0,0 +1,57 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + /// + /// The ways in which a request or a response can break the OpenAPI document + /// + public enum ContractViolationKind + { + /// + /// A query parameter that the operation does not declare + /// + UndeclaredParameter, + + /// + /// A required query parameter that is missing + /// + MissingParameter, + + /// + /// A query parameter whose value does not fit its schema + /// + InvalidParameter, + + /// + /// A status that the operation declares neither explicitly nor through default + /// + UndeclaredStatus, + + /// + /// A body, or its absence, where the document declares the opposite + /// + UnexpectedBody, + + /// + /// A body whose media type is not declared + /// + UndeclaredMediaType, + + /// + /// A body with a JSON media type that is not JSON + /// + InvalidJson, + + /// + /// A JSON body that does not validate against its schema + /// + SchemaMismatch + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs b/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs new file mode 100644 index 000000000..6b268fe24 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs @@ -0,0 +1,164 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + + using SysML2.NET.Common; + using SysML2.NET.Core; + + /// + /// Computes what the scenario has not yet covered, from what the server returned and the requests the client sent, + /// against lists taken from the generated DTOs and the OpenAPI document + /// + public sealed class CoverageVerdict + { + /// + /// A fresh instance per DTO class, holding the default value of every property + /// + private static readonly ConcurrentDictionary Defaults = new(); + + /// + /// Initializes a new instance of the class + /// + /// + /// Every data item the server returned, with the commit it was read at + /// + /// + /// Every request the client sent + /// + /// + /// The operations of the OpenAPI document + /// + public CoverageVerdict(IReadOnlyCollection<(Guid CommitId, IData Data)> readBack, IReadOnlyCollection calls, OpenApiDocument openApi) + { + var elements = readBack.Where(entry => entry.Data != null).ToList(); + + var seenClasses = elements.Select(entry => entry.Data.GetType()).ToHashSet(); + this.MissingMetaclasses = DtoMetadata.ConcreteClasses.Where(type => !seenClasses.Contains(type)).Select(type => type.Name).ToList(); + + this.UnsetProperties = DtoMetadata.DeclaredProperties + .Where(property => !elements.Exists(entry => property.Interface.IsInstanceOfType(entry.Data) && !DtoMetadata.ValueEquals(property.ValueOf(entry.Data), property.ValueOf(DefaultOf(entry.Data.GetType()))))) + .Select(property => property.Name) + .ToList(); + + var versions = elements.GroupBy(entry => entry.Data.Id).ToList(); + + this.UnchangedProperties = DtoMetadata.DeclaredProperties + .Where(property => !versions.Exists(element => property.Interface.IsInstanceOfType(element.First().Data) && element.Select(entry => property.ValueOf(entry.Data)).Skip(1).Any(value => !DtoMetadata.ValueEquals(value, property.ValueOf(element.First().Data))))) + .Select(property => property.Name) + .ToList(); + + this.MissingLiterals = MissingEnumerationLiterals(elements.Select(entry => entry.Data)).ToList(); + + this.UncoveredOperations = openApi.Operations + .SelectMany(operation => + { + var operationCalls = calls.Where(call => call.Operation == operation).ToList(); + var missing = new List(); + + if (!operationCalls.Exists(call => call.IsSuccess)) + { + missing.Add($"{operation} (no 2xx)"); + } + + if (operation.DeclaresClientError && !operationCalls.Exists(call => call.IsClientError)) + { + missing.Add($"{operation} (no 4xx)"); + } + + return missing; + }) + .ToList(); + + this.UnmatchedRequests = calls.Where(call => call.Operation == null).Select(call => call.RequestLine).Distinct().ToList(); + } + + /// + /// Gets the concrete metaclasses of which the server returned no instance + /// + public IReadOnlyList MissingMetaclasses { get; } + + /// + /// Gets the non-derived properties that the server never returned with a non-default value + /// + public IReadOnlyList UnsetProperties { get; } + + /// + /// Gets the non-derived properties that the server never returned with two different values for one element + /// + public IReadOnlyList UnchangedProperties { get; } + + /// + /// Gets the enumeration literals that the server never returned + /// + /// + /// The default literal of a non-nullable property counts as returned, as it cannot be told apart from a value + /// the server omitted. + /// + public IReadOnlyList MissingLiterals { get; } + + /// + /// Gets the OpenAPI operations not yet called with a success answer, or with a client error answer where the + /// document declares one + /// + public IReadOnlyList UncoveredOperations { get; } + + /// + /// Gets the requests that addressed no operation of the OpenAPI document + /// + public IReadOnlyList UnmatchedRequests { get; } + + /// + /// Gets a fresh instance of a DTO class, whose property values are the defaults + /// + /// + /// The DTO class + /// + /// + /// The fresh instance + /// + private static object DefaultOf(Type dtoType) => Defaults.GetOrAdd(dtoType, type => Activator.CreateInstance(type)); + + /// + /// Computes the literals of the metamodel enumerations that no returned element holds; the enumerations are + /// those typing a non-derived property, which excludes + /// + /// + /// The returned elements + /// + /// + /// The missing literals as Enumeration.literal + /// + private static IEnumerable MissingEnumerationLiterals(IEnumerable elements) + { + var enumerationProperties = DtoMetadata.DeclaredProperties + .Where(property => (Nullable.GetUnderlyingType(property.Property.PropertyType) ?? property.Property.PropertyType).IsEnum) + .ToList(); + + var enumerations = enumerationProperties + .Select(property => Nullable.GetUnderlyingType(property.Property.PropertyType) ?? property.Property.PropertyType) + .Distinct(); + + var observed = elements + .SelectMany(element => enumerationProperties.Where(property => property.Interface.IsInstanceOfType(element)).Select(property => property.ValueOf(element))) + .Where(value => value != null) + .ToHashSet(); + + return enumerations + .SelectMany(enumeration => Enum.GetValues(enumeration).Cast()) + .Where(literal => !observed.Contains(literal)) + .Select(literal => $"{literal.GetType().Name}.{literal}"); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/DeterministicGuid.cs b/SySML2.NET.REST.Tests/Helpers/DeterministicGuid.cs new file mode 100644 index 000000000..f706b785c --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/DeterministicGuid.cs @@ -0,0 +1,60 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Security.Cryptography; + using System.Text; + + /// + /// Creates name-based (version 5, SHA-1) UUIDs as specified by RFC 9562, so that the elements of the scenario + /// have the same ids in every run + /// + public static class DeterministicGuid + { + /// + /// The namespace UUID of the scenario's names + /// + private static readonly Guid ScenarioNamespace = new("4b0f3f6e-2a59-4b0a-9a51-407407407407"); + + /// + /// Creates the UUID of a name + /// + /// + /// The name, e.g. root/CoverageModel + /// + /// + /// The version 5 UUID of in the scenario namespace + /// + /// + /// Thrown when is null or whitespace + /// + public static Guid Create(string name) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException("The name may not be null or whitespace", nameof(name)); + } + + var namespaceBytes = ScenarioNamespace.ToByteArray(true); + var nameBytes = Encoding.UTF8.GetBytes(name); + + var input = new byte[namespaceBytes.Length + nameBytes.Length]; + namespaceBytes.CopyTo(input, 0); + nameBytes.CopyTo(input, namespaceBytes.Length); + + var hash = SHA1.HashData(input); + hash[6] = (byte)((hash[6] & 0x0F) | 0x50); + hash[8] = (byte)((hash[8] & 0x3F) | 0x80); + + return new Guid(hash.AsSpan(0, 16), true); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/DtoMetadata.cs b/SySML2.NET.REST.Tests/Helpers/DtoMetadata.cs new file mode 100644 index 000000000..59eb1a6ea --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/DtoMetadata.cs @@ -0,0 +1,132 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using SysML2.NET.Decorators; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + + /// + /// Reads the metamodel facts that the generated DTOs carry in their and + /// decorators, so that coverage is computed from the generated code itself + /// + /// + /// Reflection is used here, in test code only, so that the coverage lists follow the metamodel without upkeep. + /// + public static class DtoMetadata + { + /// + /// The namespace prefix of the generated Core DTOs + /// + private const string DtoNamespace = "SysML2.NET.Core.DTO"; + + /// + /// The non-derived properties per DTO class, cached + /// + private static readonly ConcurrentDictionary> PropertiesByClass = new(); + + /// + /// Gets every concrete DTO class of a metaclass + /// + public static IReadOnlyList ConcreteClasses { get; } = typeof(DtoElement).Assembly.GetTypes() + .Where(type => type.IsClass && !type.IsAbstract && IsDtoType(type) && typeof(DtoElement).IsAssignableFrom(type)) + .OrderBy(type => type.Name) + .ToList(); + + /// + /// Gets every non-derived property of the metamodel, each once, on the DTO interface that declares it + /// + public static IReadOnlyList DeclaredProperties { get; } = typeof(DtoElement).Assembly.GetTypes() + .Where(type => type.IsInterface && IsDtoType(type) && (type == typeof(DtoElement) || typeof(DtoElement).IsAssignableFrom(type))) + .SelectMany(DeclaredNonDerivedProperties) + .OrderBy(property => property.Name) + .ToList(); + + /// + /// Gets the JSON name of every derived property of the metamodel, e.g. owner or qualifiedName + /// + public static IReadOnlySet DerivedPropertyNames { get; } = typeof(DtoElement).Assembly.GetTypes() + .Where(type => type.IsInterface && IsDtoType(type) && (type == typeof(DtoElement) || typeof(DtoElement).IsAssignableFrom(type))) + .SelectMany(type => type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + .Where(property => property.GetCustomAttribute() is { IsDerived: true }) + .Select(property => $"{char.ToLowerInvariant(property.Name[0])}{property.Name[1..]}") + .ToHashSet(StringComparer.Ordinal); + + /// + /// Gets the non-derived properties that a DTO class implements, read through their declaring interfaces + /// + /// + /// The DTO class + /// + /// + /// The s of + /// + public static IReadOnlyList PropertiesOf(Type dtoType) + { + return PropertiesByClass.GetOrAdd(dtoType, type => DeclaredProperties.Where(property => property.Interface.IsAssignableFrom(type)).ToList()); + } + + /// + /// Asserts whether two property values are equal, comparing collections element by element + /// + /// + /// The first value + /// + /// + /// The second value + /// + /// + /// true when the values are equal + /// + public static bool ValueEquals(object first, object second) + { + if (first is IEnumerable firstSequence and not string && second is IEnumerable secondSequence and not string) + { + return firstSequence.Cast().SequenceEqual(secondSequence.Cast()); + } + + return Equals(first, second); + } + + /// + /// Gets the non-derived properties that a DTO interface declares itself + /// + /// + /// The DTO interface + /// + /// + /// The declared s + /// + private static IEnumerable DeclaredNonDerivedProperties(Type dtoInterface) + { + return dtoInterface.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(property => property.GetCustomAttribute() is { IsDerived: false }) + .Select(property => new MetamodelProperty(dtoInterface, property)); + } + + /// + /// Asserts whether a type is one of the generated Core DTO types + /// + /// + /// The type + /// + /// + /// true for a type in a SysML2.NET.Core.DTO namespace + /// + private static bool IsDtoType(Type type) => type.Namespace?.StartsWith(DtoNamespace, StringComparison.Ordinal) == true; + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/EndpointCall.cs b/SySML2.NET.REST.Tests/Helpers/EndpointCall.cs new file mode 100644 index 000000000..27f3fdca0 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/EndpointCall.cs @@ -0,0 +1,50 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System.Collections.Generic; + using System.Net; + + /// + /// One request recorded by the , with how the request and its response break the + /// OpenAPI document + /// + /// + /// The OpenAPI operation the request addressed, or null when it addressed none + /// + /// + /// The method, path and query of the request + /// + /// + /// The status the server answered with + /// + public sealed record EndpointCall(OpenApiOperation Operation, string RequestLine, HttpStatusCode StatusCode) + { + /// + /// Gets a value indicating whether the server answered with a success status (2xx) + /// + public bool IsSuccess => (int)this.StatusCode is >= 200 and < 300; + + /// + /// Gets a value indicating whether the server rejected the request as a client error (4xx) + /// + public bool IsClientError => (int)this.StatusCode is >= 400 and < 500; + + /// + /// Gets the ways in which the request of the client breaks the document, which are client defects + /// + public IReadOnlyList RequestViolations { get; init; } = []; + + /// + /// Gets the ways in which the response of the server breaks the document, which are server divergences + /// + public IReadOnlyList ResponseViolations { get; init; } = []; + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs b/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs new file mode 100644 index 000000000..fdc971b4b --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs @@ -0,0 +1,123 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// A that records which OpenAPI operation every request addressed, with which + /// status it was answered, how the request and the response break the document, and which request bodies + /// reference the empty GUID + /// + public sealed class EndpointRecorder : DelegatingHandler + { + /// + /// The text of the empty GUID; a payload referencing it refers to no element + /// + private const string EmptyGuid = "00000000-0000-0000-0000-000000000000"; + + /// + /// The operations that requests are matched against + /// + private readonly OpenApiDocument openApi; + + /// + /// The recorded calls + /// + private readonly ConcurrentQueue calls = new(); + + /// + /// The requests whose body referenced the empty GUID + /// + private readonly ConcurrentQueue emptyGuidRequests = new(); + + /// + /// Initializes a new instance of the class + /// + /// + /// The operations that requests are matched against + /// + /// + /// The handler that sends the request on + /// + public EndpointRecorder(OpenApiDocument openApi, HttpMessageHandler innerHandler) : base(innerHandler) + { + this.openApi = openApi ?? throw new ArgumentNullException(nameof(openApi)); + } + + /// + /// Gets the recorded calls, in order + /// + public IReadOnlyCollection Calls => this.calls; + + /// + /// Gets the requests, as METHOD path, whose body referenced the empty GUID + /// + public IReadOnlyCollection EmptyGuidRequests => this.emptyGuidRequests; + + /// + /// Gets the call recorded last, or null before the first + /// + public EndpointCall LastCall { get; private set; } + + /// + /// Sends the request on, and records the operation it addressed, the status it was answered with, and how the + /// request and the response break the OpenAPI document + /// + /// + /// The request to send + /// + /// + /// The that cancels the operation + /// + /// + /// The response of the server, with its body buffered so that it can be read again + /// + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var requestLine = $"{request.Method} {request.RequestUri?.PathAndQuery}"; + var requestBody = string.Empty; + + if (request.Content != null) + { + await request.Content.LoadIntoBufferAsync(cancellationToken); + requestBody = await request.Content.ReadAsStringAsync(cancellationToken); + + if (requestBody.Contains(EmptyGuid, StringComparison.OrdinalIgnoreCase)) + { + this.emptyGuidRequests.Enqueue(requestLine); + } + } + + var response = await base.SendAsync(request, cancellationToken); + + await response.Content.LoadIntoBufferAsync(cancellationToken); + var responseBody = await response.Content.ReadAsStringAsync(cancellationToken); + + var operation = this.openApi.Match(request.Method, request.RequestUri?.AbsolutePath ?? string.Empty); + + var call = new EndpointCall(operation, requestLine, response.StatusCode) + { + RequestViolations = operation?.CheckRequest(request.RequestUri?.Query, request.Content?.Headers.ContentType?.MediaType, requestBody) ?? [], + ResponseViolations = operation?.CheckResponse(response.StatusCode, response.Content.Headers.ContentType?.MediaType, responseBody) ?? [] + }; + + this.calls.Enqueue(call); + this.LastCall = call; + + return response; + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/FlexoJwt.cs b/SySML2.NET.REST.Tests/Helpers/FlexoJwt.cs new file mode 100644 index 000000000..3404d1962 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/FlexoJwt.cs @@ -0,0 +1,110 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Security.Cryptography; + using System.Text; + using System.Text.Json; + + /// + /// Creates the HMAC-SHA256 JSON Web Tokens that the Flexo layer1 service accepts, signed with a secret that is + /// generated per test run so that no secret is stored in source + /// + public sealed class FlexoJwt + { + /// + /// The issuer that layer1 is configured to require (its JWT_DOMAIN) + /// + public const string Issuer = "http://flexo-mms-services"; + + /// + /// The audience that layer1 is configured to require (its JWT_AUDIENCE) + /// + public const string Audience = "flexo-mms-audience"; + + /// + /// The realm that layer1 is configured with (its JWT_REALM) + /// + public const string Realm = "flexo-mms"; + + /// + /// The user that cluster.trig grants the super-administrator policy to + /// + public const string UserName = "ldap/user/user01"; + + /// + /// The group that cluster.trig grants the super-administrator policy to + /// + public const string Group = "super_admins"; + + /// + /// Initializes a new instance of the class with a random secret + /// + public FlexoJwt() + { + var secretBytes = RandomNumberGenerator.GetBytes(48); + this.Secret = ToBase64Url(secretBytes); + } + + /// + /// Gets the secret that layer1 must be configured with (its JWT_SECRET) + /// + public string Secret { get; } + + /// + /// Creates a signed token for the super-administrator user + /// + /// + /// The time after which the token expires + /// + /// + /// The compact serialization of the token + /// + public string CreateToken(TimeSpan lifetime) + { + var now = DateTimeOffset.UtcNow; + string[] groups = [Group]; + + var header = JsonSerializer.SerializeToUtf8Bytes(new { alg = "HS256", typ = "JWT" }); + + var payload = JsonSerializer.SerializeToUtf8Bytes(new + { + iss = Issuer, + aud = Audience, + username = UserName, + groups, + iat = now.ToUnixTimeSeconds(), + exp = now.Add(lifetime).ToUnixTimeSeconds() + }); + + var signingInput = $"{ToBase64Url(header)}.{ToBase64Url(payload)}"; + + using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(this.Secret)); + var signature = hmac.ComputeHash(Encoding.ASCII.GetBytes(signingInput)); + + return $"{signingInput}.{ToBase64Url(signature)}"; + } + + /// + /// Encodes bytes as base64url without padding (RFC 7515, section 2) + /// + /// + /// The bytes to encode + /// + /// + /// The encoded text + /// + private static string ToBase64Url(byte[] bytes) + { + return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/FlexoTestHost.cs b/SySML2.NET.REST.Tests/Helpers/FlexoTestHost.cs new file mode 100644 index 000000000..9f23671a6 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/FlexoTestHost.cs @@ -0,0 +1,389 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.IO; + using System.Linq; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + using DotNet.Testcontainers.Builders; + using DotNet.Testcontainers.Containers; + using DotNet.Testcontainers.Networks; + + using NUnit.Framework; + + /// + /// Runs a Flexo MMS SysML v2 server in Docker: a Fuseki quad store, the Flexo layer1 service and the + /// Flexo SysML v2 service on one network, with the sysmlv2 organization created on layer1 + /// + /// + /// Start it from [OneTimeSetUp]: an unreachable Docker ignores the fixture, any later failure fails it. + /// + public sealed class FlexoTestHost : IAsyncDisposable + { + /// + /// The quad store image: atomgraph/fuseki:4.6, pinned by digest + /// + private const string QuadStoreImage = "atomgraph/fuseki@sha256:9eb7a16dbddd35d9e293eed32a4e5b27ab04b6bd8ba4ef827ed00119d6e45bea"; + + /// + /// The layer1 image: openmbee/flexo-mms-layer1-service:v0.3.0, pinned by digest + /// + private const string Layer1Image = "openmbee/flexo-mms-layer1-service@sha256:5e40dbf9318135f9e8097b4268f40f3cbcc1cf0d97c0eea04c4424749467325f"; + + /// + /// The SysML v2 service image: the develop build of commit 836d904d, pinned by digest + /// + private const string SysmlImage = "openmbee/flexo-sysmlv2@sha256:007bd8000a42cf07b76b0773cc351326f4ef5ee2660df2683d976258dbb34fd3"; + + /// + /// The network alias of the quad store, which the layer1 configuration refers to + /// + private const string QuadStoreAlias = "quad-server"; + + /// + /// The network alias of layer1, which cluster.trig and the SysML v2 configuration refer to + /// + private const string Layer1Alias = "layer1-service"; + + /// + /// The layer1 organization that the SysML v2 service stores its projects in + /// + private const string Organization = "sysmlv2"; + + /// + /// The port that Fuseki listens on + /// + private const ushort QuadStorePort = 3030; + + /// + /// The port that layer1 and the SysML v2 service listen on + /// + private const ushort ServicePort = 8080; + + /// + /// The time that each container may take to become ready, including the image pull of a first run + /// + private static readonly TimeSpan ReadinessTimeout = TimeSpan.FromMinutes(5); + + /// + /// The Docker endpoint to use, or null to let Testcontainers probe for one + /// + private readonly string dockerEndpoint = ResolveDockerEndpoint(); + + /// + /// The network that the three containers share + /// + private INetwork network; + + /// + /// The Fuseki quad store container + /// + private IContainer quadStore; + + /// + /// The layer1 container + /// + private IContainer layer1; + + /// + /// The SysML v2 service container + /// + private IContainer sysml; + + /// + /// Gets the whose secret layer1 is configured with + /// + public FlexoJwt Jwt { get; } = new(); + + /// + /// Gets the bearer token accepted by layer1, valid for the duration of a test run + /// + public string Token { get; private set; } + + /// + /// Gets the base address of the SysML v2 API, available once completed + /// + public Uri BaseAddress { get; private set; } + + /// + /// Disposes the containers and the network + /// + /// + /// An awaitable + /// + public async ValueTask DisposeAsync() + { + IContainer[] containers = [this.sysml, this.layer1, this.quadStore]; + + foreach (var container in containers.Where(container => container != null)) + { + await container.DisposeAsync(); + } + + if (this.network != null) + { + await this.network.DisposeAsync(); + } + } + + /// + /// Starts the quad store, then layer1, creates the organization, and then starts the SysML v2 service + /// + /// + /// The that cancels the start + /// + /// + /// An awaitable + /// + public async Task StartAsync(CancellationToken cancellationToken) + { + try + { + var networkBuilder = new NetworkBuilder(); + + if (this.dockerEndpoint != null) + { + networkBuilder = networkBuilder.WithDockerEndpoint(this.dockerEndpoint); + } + + this.network = networkBuilder.Build(); + await this.network.CreateAsync(cancellationToken); + } + catch (Exception exception) + { + Assert.Ignore($"Docker is not available for the Flexo integration tests: {exception.Message}"); + } + + this.Token = this.Jwt.CreateToken(TimeSpan.FromHours(4)); + + Exception startFailure = null; + + try + { + await this.StartQuadStoreAsync(cancellationToken); + await this.StartLayer1Async(cancellationToken); + await this.CreateOrganizationAsync(cancellationToken); + await this.StartSysmlAsync(cancellationToken); + } + catch (Exception exception) + { + startFailure = exception; + } + + if (startFailure != null) + { + var logs = await this.CollectLogsAsync(); + Assert.Fail($"Flexo did not start: {startFailure.Message}{logs}"); + } + } + + /// + /// Resolves the Docker endpoint the way PostgreSqlSchemaTestHost does: DOCKER_HOST when set, + /// otherwise Docker Desktop's Linux engine pipe on Windows, otherwise null + /// + /// + /// The Docker endpoint, or null + /// + private static string ResolveDockerEndpoint() + { + var dockerHost = Environment.GetEnvironmentVariable("DOCKER_HOST"); + + if (!string.IsNullOrWhiteSpace(dockerHost)) + { + return dockerHost; + } + + if (OperatingSystem.IsWindows() && File.Exists(@"\\.\pipe\dockerDesktopLinuxEngine")) + { + return "npipe://./pipe/dockerDesktopLinuxEngine"; + } + + return null; + } + + /// + /// Collects the tail of the logs of every started container, to explain a failed start + /// + /// + /// The logs, one section per container + /// + private async Task CollectLogsAsync() + { + var logs = new StringBuilder(); + + (string Name, IContainer Container)[] containers = [("quad store", this.quadStore), ("layer1", this.layer1), ("sysmlv2", this.sysml)]; + + foreach (var (name, container) in containers.Where(entry => entry.Container != null)) + { + try + { + var (stdout, stderr) = await container.GetLogsAsync(default, default, false, CancellationToken.None); + var output = $"{stdout}{stderr}"; + logs.Append($"{Environment.NewLine}--- {name} ---{Environment.NewLine}{output[Math.Max(0, output.Length - 4000)..]}"); + } + catch (Exception exception) + { + logs.Append($"{Environment.NewLine}--- {name}: logs unavailable ({exception.Message}) ---"); + } + } + + return logs.ToString(); + } + + /// + /// Creates a on the shared network and Docker endpoint + /// + /// + /// The image of the container + /// + /// + /// The alias by which the other containers reach it, or null when none is needed + /// + /// + /// The + /// + private ContainerBuilder CreateContainerBuilder(string image, string networkAlias) + { + var builder = new ContainerBuilder(image).WithNetwork(this.network); + + if (networkAlias != null) + { + builder = builder.WithNetworkAliases(networkAlias); + } + + if (this.dockerEndpoint != null) + { + builder = builder.WithDockerEndpoint(this.dockerEndpoint); + } + + return builder; + } + + /// + /// Creates the organization that the SysML v2 service stores its projects in + /// + /// + /// The that cancels the request + /// + /// + /// An awaitable + /// + /// + /// Thrown when layer1 does not accept the organization + /// + private async Task CreateOrganizationAsync(CancellationToken cancellationToken) + { + using var httpClient = new HttpClient(); + var organizationUri = new Uri($"http://{this.layer1.Hostname}:{this.layer1.GetMappedPublicPort(ServicePort)}/orgs/{Organization}"); + + using var request = new HttpRequestMessage(HttpMethod.Put, organizationUri); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.Token); + request.Content = new StringContent($"<> \"{Organization}\"@en .", Encoding.UTF8, "text/turtle"); + + using var response = await httpClient.SendAsync(request, cancellationToken); + + if (!response.IsSuccessStatusCode) + { + var body = await response.Content.ReadAsStringAsync(cancellationToken); + throw new InvalidOperationException($"layer1 refused the {Organization} organization with {(int)response.StatusCode}: {body}"); + } + } + + /// + /// Starts the layer1 service, configured with the per-run JWT secret + /// + /// + /// The that cancels the start + /// + /// + /// An awaitable + /// + private async Task StartLayer1Async(CancellationToken cancellationToken) + { + var quadStoreUrl = $"http://{QuadStoreAlias}:{QuadStorePort}/ds"; + + this.layer1 = this.CreateContainerBuilder(Layer1Image, Layer1Alias) + .WithEnvironment("JWT_DOMAIN", FlexoJwt.Issuer) + .WithEnvironment("JWT_AUDIENCE", FlexoJwt.Audience) + .WithEnvironment("JWT_REALM", FlexoJwt.Realm) + .WithEnvironment("JWT_SECRET", this.Jwt.Secret) + .WithEnvironment("FLEXO_MMS_ROOT_CONTEXT", $"http://{Layer1Alias}") + .WithEnvironment("FLEXO_MMS_QUERY_URL", $"{quadStoreUrl}/sparql") + .WithEnvironment("FLEXO_MMS_UPDATE_URL", $"{quadStoreUrl}/update") + .WithEnvironment("FLEXO_MMS_GRAPH_STORE_PROTOCOL_URL", $"{quadStoreUrl}/data") + .WithPortBinding(ServicePort, true) + .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded( + request => request.ForPort(ServicePort).ForPath("/").ForStatusCodeMatching(_ => true), + strategy => strategy.WithTimeout(ReadinessTimeout))) + .Build(); + + await this.layer1.StartAsync(cancellationToken); + } + + /// + /// Starts the Fuseki quad store, seeded with cluster.trig + /// + /// + /// The that cancels the start + /// + /// + /// An awaitable + /// + private async Task StartQuadStoreAsync(CancellationToken cancellationToken) + { + var clusterPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "Flexo", "cluster.trig"); + var cluster = await File.ReadAllBytesAsync(clusterPath, cancellationToken); + + this.quadStore = this.CreateContainerBuilder(QuadStoreImage, QuadStoreAlias) + .WithResourceMapping(cluster, "/tmp/mount/cluster.trig") + .WithEnvironment("JAVA_OPTIONS", "-Xmx1g") + .WithEnvironment("JAVA_TOOL_OPTIONS", "-XX:-UseContainerSupport") + .WithCommand("--file=/tmp/mount/cluster.trig", "--update", "/ds") + .WithPortBinding(QuadStorePort, true) + .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("Start Fuseki", strategy => strategy.WithTimeout(ReadinessTimeout))) + .Build(); + + await this.quadStore.StartAsync(cancellationToken); + } + + /// + /// Starts the SysML v2 service; it forwards the client's bearer token to layer1 and has no fallback token + /// + /// + /// The that cancels the start + /// + /// + /// An awaitable + /// + private async Task StartSysmlAsync(CancellationToken cancellationToken) + { + this.sysml = this.CreateContainerBuilder(SysmlImage, null) + .WithEnvironment("FLEXO_HOST", Layer1Alias) + .WithEnvironment("FLEXO_PORT", ServicePort.ToString()) + .WithEnvironment("FLEXO_PROTOCOL", "http") + .WithEnvironment("FLEXO_SYSMLV2_ORG", Organization) + .WithPortBinding(ServicePort, true) + .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded( + request => request.ForPort(ServicePort).ForPath("/meta/datatypes").WithHeader("Authorization", $"Bearer {this.Token}"), + strategy => strategy.WithTimeout(ReadinessTimeout))) + .Build(); + + await this.sysml.StartAsync(cancellationToken); + + this.BaseAddress = new Uri($"http://{this.sysml.Hostname}:{this.sysml.GetMappedPublicPort(ServicePort)}/"); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/IntegrationHttpClientFactory.cs b/SySML2.NET.REST.Tests/Helpers/IntegrationHttpClientFactory.cs new file mode 100644 index 000000000..2c6b40d36 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/IntegrationHttpClientFactory.cs @@ -0,0 +1,62 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Net.Http; + + /// + /// An whose clients share one handler chain: a + /// in front of an + /// + public sealed class IntegrationHttpClientFactory : IHttpClientFactory, IDisposable + { + /// + /// The first handler of the shared chain + /// + private readonly HttpMessageHandler handler; + + /// + /// Initializes a new instance of the class + /// + /// + /// The bearer token added to every request + /// + /// + /// The OpenAPI operations that requests are matched against + /// + public IntegrationHttpClientFactory(string token, OpenApiDocument openApi) + { + this.Recorder = new EndpointRecorder(openApi, new HttpClientHandler()); + this.handler = new BearerTokenHandler(token, this.Recorder); + } + + /// + /// Gets the of the shared chain + /// + public EndpointRecorder Recorder { get; } + + /// + /// Creates an over the shared chain; disposing the client leaves the chain intact + /// + /// + /// The logical name of the client, ignored + /// + /// + /// The + /// + public HttpClient CreateClient(string name) => new(this.handler, false); + + /// + /// Disposes the shared handler chain + /// + public void Dispose() => this.handler.Dispose(); + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/IsolatedAssertions.cs b/SySML2.NET.REST.Tests/Helpers/IsolatedAssertions.cs new file mode 100644 index 000000000..5d1e9f7f5 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/IsolatedAssertions.cs @@ -0,0 +1,57 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + + using NUnit.Framework; + using NUnit.Framework.Interfaces; + using NUnit.Framework.Internal; + + /// + /// Runs a check in an isolated test context, so that the assertions it makes are collected instead of deciding + /// the outcome of the test that runs it + /// + public static class IsolatedAssertions + { + /// + /// Runs a check and collects the failures and warnings it recorded + /// + /// + /// The check to run + /// + /// + /// The failed and warning assertion results, in the order they were recorded + /// + public static async Task> RunAsync(Func check) + { + using (new TestExecutionContext.IsolatedContext()) + { + try + { + await check(); + } + catch (AssertionException) + { + } + catch (MultipleAssertException) + { + } + + return TestExecutionContext.CurrentContext.CurrentResult.AssertionResults + .Where(result => result.Status is AssertionStatus.Failed or AssertionStatus.Warning) + .ToList(); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs new file mode 100644 index 000000000..ae4845364 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs @@ -0,0 +1,203 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Runtime.CompilerServices; + using System.Text.RegularExpressions; + using System.Threading.Tasks; + + using NUnit.Framework; + + using SysML2.NET.REST.Exceptions; + + /// + /// The known ways in which the Flexo server under the scenario diverges from the Systems Modeling API and Services + /// specification; they are reported as warnings because they are no failure of the client under test + /// + /// + /// The expectations of the scenario stay those of the specification; only the outcome is reported differently. + /// + public static class KnownServerDivergences + { + /// + /// The source revision of Flexo that the divergences were found in + /// + private const string FlexoRevision = "Open-MBEE/flexo-mms-sysmlv2@836d904d"; + + /// + /// The properties of the API records that the server leaves out + /// + private static readonly HashSet OmittedRecordProperties = ["alias", "name", "description", "deleted"]; + + /// + /// Matches a schema error that lists missing required properties, capturing their quoted names + /// + private static readonly Regex MissingRequired = new(@"^\S* required: Required properties \[(?[^\]]*)\] are not present$", RegexOptions.Compiled); + + /// + /// Matches a schema error on a list property sent as null + /// + private static readonly Regex NullList = new(@"^\S* type: Value is ""null"" but should be ""array""$", RegexOptions.Compiled); + + /// + /// Gets the divergence that the roots are the elements without an owningRelatedElement, owned through + /// an owningRelationship or not, where Clause 7.2.2 makes them the elements without an owner + /// + public static ServerDivergence RootsIgnoreOwningRelationship { get; } = new("GET /projects/{projectId}/commits/{commitId}/roots answers every element without an owningRelatedElement, ignoring its owningRelationship", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/ElementApi.kt"); + + /// + /// Gets the divergence that a request for an unknown resource is answered with a client error other than + /// 404 Not Found, which the OpenAPI document declares for it + /// + public static ServerDivergence UnknownResourceNotFound { get; } = new("a request for an unknown resource is answered with another client error than 404 Not Found", $"{FlexoRevision}, layer1 access control on a missing repository"); + + /// + /// Gets the divergence that a request naming an unknown resource succeeds, where the OpenAPI document declares + /// 404 Not Found for it + /// + public static ServerDivergence UnknownResourceAccepted { get; } = new("a request naming an unknown resource succeeds instead of answering 404 Not Found", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/RelationshipApi.kt"); + + /// + /// Gets the divergence that an error answer carries an empty or plain-text body, where the OpenAPI document + /// declares an application/json Error body for it + /// + public static ServerDivergence ErrorWithoutErrorBody { get; } = new( + "an error answer carries an empty or text/plain body instead of an application/json Error", + $"{FlexoRevision}, layer1 Http404Exception and the meta datatypes route", + (call, violation) => (int)call.StatusCode >= 400 && violation.Kind is ContractViolationKind.UnexpectedBody or ContractViolationKind.UndeclaredMediaType); + + /// + /// Gets the divergence that a create answers 200 OK, where the OpenAPI document declares 201 Created and no 200 + /// + public static ServerDivergence CreatedAnsweredOk { get; } = new( + "a create answers 200 OK instead of 201 Created", + $"{FlexoRevision}, observed on POST /projects and POST /projects/{{projectId}}/commits", + (call, violation) => call is { StatusCode: HttpStatusCode.OK, Operation: { } operation } && operation.Method == HttpMethod.Post && operation.Responses.ContainsKey("201") && !operation.Responses.ContainsKey("200")); + + /// + /// Gets the divergence that the API records leave out required properties, or send null for an empty + /// list, where the OpenAPI document requires them + /// + public static ServerDivergence RecordsWithoutRequiredProperties { get; } = new( + "projects, branches, commits and data versions leave out the required alias, name, description and deleted, and send null for an empty previousCommit", + $"{FlexoRevision}, observed on every project, branch, commit and change read", + (_, violation) => violation.Kind == ContractViolationKind.SchemaMismatch && (NullList.IsMatch(violation.Message) || MissingNames(violation) is { Count: > 0 } names && names.All(OmittedRecordProperties.Contains))); + + /// + /// Gets the divergence that elements are returned without their derived properties, which the response schemas + /// of the OpenAPI document require + /// + public static ServerDivergence ElementsWithoutDerivedProperties { get; } = new( + "elements are returned without their derived properties, e.g. owner and qualifiedName", + $"{FlexoRevision}, the stored payload is returned as sent", + (_, violation) => violation.Kind == ContractViolationKind.SchemaMismatch && MissingNames(violation) is { Count: > 0 } names && names.All(DtoMetadata.DerivedPropertyNames.Contains)); + + /// + /// Gets the divergence that a datatype is returned with an $id that is not a URI + /// + public static ServerDivergence DatatypeIdNotUri { get; } = new( + "a datatype is returned with an $id that is not a URI", + $"{FlexoRevision}, the meta datatypes route", + (call, violation) => call.Operation?.PathTemplate == "/meta/datatypes/{datatypeId}" && violation.Message.StartsWith("/$id format:", StringComparison.Ordinal)); + + /// + /// Gets every known divergence + /// + public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, ElementsWithoutDerivedProperties, DatatypeIdNotUri]; + + /// + /// Asserts that a call for an unknown resource fails with 404 Not Found, or reports the one tolerated divergence + /// when the server answers the way it describes + /// + /// + /// Whether the body of the answer conforms is checked with every call by ; + /// here, a 404 whose body conforms must reach the caller as a parsed Error. + /// + /// + /// The call for the unknown resource + /// + /// + /// Gets the call that the recorded last, or null + /// + /// + /// The divergence the call may show, either or + /// , or null to tolerate none + /// + /// + /// The description of the call in assertion messages + /// + /// + /// An awaitable + /// + public static async Task ExpectNotFoundAsync(Func call, Func lastCall, ServerDivergence tolerated = null, [CallerArgumentExpression(nameof(call))] string description = null) + { + PsmApiException failure = null; + + try + { + await call(); + } + catch (PsmApiException exception) + { + failure = exception; + } + + var tolerates = tolerated == UnknownResourceAccepted ? failure == null : failure is { StatusCode: not HttpStatusCode.NotFound } && (int)failure.StatusCode is >= 400 and < 500; + + if (tolerated != null && tolerates) + { + Report(tolerated, $"{description} answered {(failure == null ? "a success" : $"{(int)failure.StatusCode} {failure.StatusCode}")}"); + return; + } + + Assert.That(failure?.StatusCode, Is.EqualTo(HttpStatusCode.NotFound), description); + + if (failure is { StatusCode: HttpStatusCode.NotFound } && lastCall?.Invoke() is { ResponseViolations.Count: 0 }) + { + Assert.That(failure.Error, Is.Not.Null, $"{description}: the 404 body conforms to the OpenAPI document, but the client read no Error from it"); + } + } + + /// + /// Reports a known divergence as a warning + /// + /// + /// The divergence that was observed + /// + /// + /// What was observed + /// + public static void Report(ServerDivergence divergence, string detail) + { + Assert.Warn($"Known server divergence: {divergence.Summary} ({divergence.Reference}). Observed: {detail}"); + } + + /// + /// Reads the names of the missing required properties from a schema violation + /// + /// + /// The violation + /// + /// + /// The names, or null when the violation is about something else + /// + private static IReadOnlyList MissingNames(ContractViolation violation) + { + var match = MissingRequired.Match(violation.Message); + + return match.Success ? match.Groups["names"].Value.Split(',').Select(name => name.Trim('"')).ToList() : null; + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/MetamodelProperty.cs b/SySML2.NET.REST.Tests/Helpers/MetamodelProperty.cs new file mode 100644 index 000000000..29916b5c7 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/MetamodelProperty.cs @@ -0,0 +1,42 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Reflection; + + /// + /// A non-derived property of the metamodel, as declared on a generated DTO interface + /// + /// + /// The DTO interface that declares the property, e.g. IMembership + /// + /// + /// The declared property + /// + public sealed record MetamodelProperty(Type Interface, PropertyInfo Property) + { + /// + /// Gets the name of the property as Metaclass.property, e.g. Membership.MemberElement + /// + public string Name => $"{this.Interface.Name[1..]}.{this.Property.Name}"; + + /// + /// Reads the value of the property from a DTO, through the declaring interface + /// + /// + /// The DTO, which implements + /// + /// + /// The value of the property + /// + public object ValueOf(object dto) => this.Property.GetValue(dto); + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs new file mode 100644 index 000000000..5e54c1553 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs @@ -0,0 +1,138 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using SysML2.NET.PSM.DTO; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + + /// + /// Builds the part of the model that one scenario step commits: POCOs with deterministic ids, wired by the + /// caller with AssignOwnership, then converted to DTOs, including derived values, once the step is complete + /// + /// + /// The DTOs are produced from POCOs because a DTO cannot hold the values of members that a derived property + /// redefines, such as OwningMembership.memberElement, which the payload must still carry. + /// + public sealed class ModelBuilder + { + /// + /// The prefix of the names that the ids are derived from + /// + private readonly string scope; + + /// + /// The created elements with their conversion, in creation order + /// + private readonly List<(string Name, PocoElement Poco, Func Convert)> entries = []; + + /// + /// Initializes a new instance of the class + /// + /// + /// The prefix of the names that the ids are derived from, e.g. the step name + /// + public ModelBuilder(string scope) + { + this.scope = scope; + } + + /// + /// Creates the commit request that creates or replaces the given elements + /// + /// + /// The DTOs to commit + /// + /// + /// The description of the commit + /// + /// + /// The , one change per element + /// + public static CommitRequest ToCommitRequest(IEnumerable elements, string description) + { + return new CommitRequest + { + Description = description, + Change = elements.Select(element => new DataVersionRequest + { + Identity = new DataIdentityRequest { Id = element.Id }, + Payload = element + }).ToList() + }; + } + + /// + /// Creates a POCO with a deterministic Id and ElementId, and records its conversion to a DTO + /// + /// + /// The POCO type + /// + /// + /// The name the id is derived from, unique within the scope + /// + /// + /// The generated ToDto extension of , e.g. PackageExtensions.ToDto + /// + /// + /// The created POCO + /// + /// + /// Thrown when is already used in the scope + /// + public TPoco Create(string name, Func toDto) where TPoco : PocoElement, new() + { + if (this.entries.Exists(entry => entry.Name == name)) + { + throw new ArgumentException($"The name {name} is already used in scope {this.scope}", nameof(name)); + } + + var poco = new TPoco + { + Id = DeterministicGuid.Create($"{this.scope}/{name}") + }; + + poco.ElementId = poco.Id.ToString(); + + this.entries.Add((name, poco, () => toDto(poco, true))); + + return poco; + } + + /// + /// Converts every created POCO to its DTO, including derived values + /// + /// + /// The DTOs, in creation order + /// + /// + /// Thrown when an element cannot be converted, naming that element + /// + public IReadOnlyList ToDtos() + { + return this.entries.Select(entry => + { + try + { + return entry.Convert(); + } + catch (Exception exception) + { + throw new InvalidOperationException($"{this.scope}/{entry.Name} ({entry.Poco.GetType().Name}) cannot be converted to a DTO: {exception.Message}", exception); + } + }).ToList(); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs new file mode 100644 index 000000000..825b14b13 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs @@ -0,0 +1,194 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + + using SysML2.NET.Core.Core.Types; + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Kernel.Expressions; + using SysML2.NET.Core.POCO.Kernel.Functions; + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Core.POCO.Root.Annotations; + using SysML2.NET.Core.POCO.Root.Dependencies; + using SysML2.NET.Core.POCO.Root.Namespaces; + using SysML2.NET.Core.Root.Namespaces; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + + /// + /// The model of scenario step 2: the root package and the KerML Root and Packages metaclasses + /// + /// + /// + /// package <cvm> CoverageModel { + /// package <nst> Nested { + /// private import all Library::*::**; + /// public import Space::LibAlias; + /// } + /// namespace <spc> Space { + /// protected alias <la> LibAlias for Library; + /// } + /// standard library package <lib> Library { + /// filter true; + /// } + /// comment <cmt> Note about Nested locale "en-US" /* A comment about Nested. */ + /// doc <dcm> /* The coverage model. */ + /// rep <rpr> Representation language "natural" /* The coverage model, in words. */ + /// dependency <dep> Uses from Nested to Library; + /// } + /// + /// plus an about Library, which has no textual notation of its own, and the + /// result parameter of the filter condition, which KerML requires of every Expression (result [1..1]). + /// + public sealed class RootModel + { + /// + /// Initializes a new instance of the class and builds the model + /// + public RootModel() + { + this.Builder = new ModelBuilder("root"); + + this.Root = this.CreateNamed("CoverageModel", "cvm", PackageExtensions.ToDto); + + this.Nested = this.CreateNamed("Nested", "nst", PackageExtensions.ToDto); + this.OwnMember(this.Root, this.Nested); + + var space = this.CreateNamed("Space", "spc", NamespaceExtensions.ToDto); + this.OwnMember(this.Root, space); + + var library = this.CreateNamed("Library", "lib", LibraryPackageExtensions.ToDto); + library.IsStandard = true; + this.OwnMember(this.Root, library); + + var namespaceImport = this.Builder.Create("Nested/import Library", NamespaceImportExtensions.ToDto); + namespaceImport.ImportedNamespace = library; + namespaceImport.IsImportAll = true; + namespaceImport.IsRecursive = true; + namespaceImport.Visibility = VisibilityKind.Private; + this.Nested.AssignOwnership(namespaceImport); + + var alias = this.Builder.Create("Space/LibAlias", MembershipExtensions.ToDto); + alias.MemberElement = library; + alias.MemberName = "LibAlias"; + alias.MemberShortName = "la"; + alias.Visibility = VisibilityKind.Protected; + space.AssignOwnership(alias); + + var membershipImport = this.Builder.Create("Nested/import LibAlias", MembershipImportExtensions.ToDto); + membershipImport.ImportedMembership = alias; + membershipImport.Visibility = VisibilityKind.Public; + this.Nested.AssignOwnership(membershipImport); + + var filter = this.Builder.Create("Library/filter", ElementFilterMembershipExtensions.ToDto); + var condition = this.Builder.Create("Library/filter/condition", LiteralBooleanExtensions.ToDto); + condition.Value = true; + library.AssignOwnership(filter, condition); + + var conditionResult = this.Builder.Create("Library/filter/condition/result", FeatureExtensions.ToDto); + conditionResult.Direction = FeatureDirectionKind.Out; + var resultMembership = this.Builder.Create("Library/filter/condition/result/membership", ReturnParameterMembershipExtensions.ToDto); + condition.AssignOwnership(resultMembership, conditionResult); + + var comment = this.CreateNamed("Note", "cmt", CommentExtensions.ToDto); + comment.Locale = "en-US"; + comment.Body = "A comment about Nested."; + this.OwnMember(this.Root, comment); + + var commentAnnotation = this.Builder.Create("Note/about Nested", AnnotationExtensions.ToDto); + commentAnnotation.AnnotatedElement = this.Nested; + comment.AssignOwnership(commentAnnotation); + + var documentation = this.Builder.Create("doc", DocumentationExtensions.ToDto); + documentation.DeclaredShortName = "dcm"; + documentation.Body = "The coverage model."; + this.OwnMember(this.Root, documentation); + + var representation = this.CreateNamed("Representation", "rpr", TextualRepresentationExtensions.ToDto); + representation.Language = "natural"; + representation.Body = "The coverage model, in words."; + this.OwnMember(this.Root, representation); + + var annotator = this.CreateNamed("Annotator", "ann", AnnotatingElementExtensions.ToDto); + this.OwnMember(this.Root, annotator); + + var annotatorAnnotation = this.Builder.Create("Annotator/about Library", AnnotationExtensions.ToDto); + annotatorAnnotation.AnnotatedElement = library; + annotator.AssignOwnership(annotatorAnnotation); + + var dependency = this.CreateNamed("Uses", "dep", DependencyExtensions.ToDto); + dependency.Client.Add(this.Nested); + dependency.Supplier.Add(library); + this.OwnMember(this.Root, dependency); + } + + /// + /// Gets the holding every element of the model + /// + public ModelBuilder Builder { get; } + + /// + /// Gets the root package + /// + public Package Root { get; } + + /// + /// Gets the nested package, which owns the imports and is annotated by the comment + /// + public Package Nested { get; } + + /// + /// Creates an element with a declared name, short name and alias id + /// + /// + /// The POCO type + /// + /// + /// The declared name, also the name its id is derived from + /// + /// + /// The declared short name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The created POCO + /// + private TPoco CreateNamed(string name, string shortName, Func toDto) where TPoco : PocoElement, new() + { + var element = this.Builder.Create(name, toDto); + element.DeclaredName = name; + element.DeclaredShortName = shortName; + element.AliasIds = [$"urn:coverage-model:{name}"]; + + return element; + } + + /// + /// Makes an element an owned member of a namespace through a new + /// + /// + /// The owning namespace + /// + /// + /// The owned member + /// + private void OwnMember(PocoElement owner, PocoElement member) + { + var membership = this.Builder.Create($"{member.ElementId}/membership", OwningMembershipExtensions.ToDto); + owner.AssignOwnership(membership, member); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs new file mode 100644 index 000000000..51fe5fd29 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs @@ -0,0 +1,86 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + + using NUnit.Framework; + + /// + /// The assertions that the recorded calls conform to the OpenAPI document: a request that breaks it is a client + /// defect and fails; a response that breaks it is reported as the known divergence that explains it, or fails + /// + /// + /// Violations are grouped by operation, status, kind and message, with array indices folded, so that one shape of + /// violation is reported once with its count and an example request. + /// + public static class OpenApiConformance + { + /// + /// Matches an array index in an instance location, e.g. the /3 of /3/identity + /// + private static readonly Regex ArrayIndex = new(@"/\d+(?=[/ ])", RegexOptions.Compiled); + + /// + /// Verifies that recorded calls conform to the OpenAPI document, and writes every violation to the test output + /// + /// + /// The calls to verify + /// + /// + /// The known divergences that may explain a response violation + /// + public static void Verify(IReadOnlyCollection calls, IReadOnlyList divergences) + { + var requestViolations = Group(calls.SelectMany(call => call.RequestViolations.Select(violation => (Call: call, Violation: violation)))); + + var responseViolations = calls + .SelectMany(call => call.ResponseViolations.Select(violation => (Call: call, Violation: violation, Divergence: divergences.FirstOrDefault(divergence => divergence.Explains?.Invoke(call, violation) == true)))) + .ToList(); + + foreach (var explained in responseViolations.Where(entry => entry.Divergence != null).GroupBy(entry => entry.Divergence)) + { + KnownServerDivergences.Report(explained.Key, string.Join("; ", Group(explained.Select(entry => (entry.Call, entry.Violation))))); + } + + var unexplained = Group(responseViolations.Where(entry => entry.Divergence == null).Select(entry => (entry.Call, entry.Violation))); + + foreach (var line in requestViolations.Select(line => $"request: {line}").Concat(unexplained.Select(line => $"response: {line}"))) + { + TestContext.Out.WriteLine($"OpenAPI violation, {line}"); + } + + using (Assert.EnterMultipleScope()) + { + Assert.That(requestViolations, Is.Empty, "requests of the client that break the OpenAPI document"); + Assert.That(unexplained, Is.Empty, "responses of the server that break the OpenAPI document and match no known divergence"); + } + } + + /// + /// Groups violations by operation, status, kind and message with array indices folded + /// + /// + /// The violations and the calls they were found in + /// + /// + /// One line per group: the shape of the violation, its count and an example request + /// + private static List Group(IEnumerable<(EndpointCall Call, ContractViolation Violation)> violations) + { + return violations + .GroupBy(entry => $"{entry.Call.Operation?.ToString() ?? entry.Call.RequestLine} answered {(int)entry.Call.StatusCode}: {entry.Violation.Kind}: {ArrayIndex.Replace(entry.Violation.Message, "/*")}") + .Select(group => $"{group.Key} ({group.Count()}x, e.g. {group.First().Call.RequestLine})") + .ToList(); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs new file mode 100644 index 000000000..1e6cfb5ec --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs @@ -0,0 +1,258 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text.Json; + + using Json.Schema; + + /// + /// The body that an OpenAPI request body or response declares: a schema per media type, or no body at all + /// + public sealed class OpenApiContent + { + /// + /// The number of schema errors reported for one body + /// + private const int ReportedErrors = 5; + + /// + /// The options that bodies are evaluated with: format is asserted, as for uuid identifiers + /// + private static readonly EvaluationOptions Evaluation = new() { OutputFormat = OutputFormat.Hierarchical, RequireFormatValidation = true }; + + /// + /// Initializes a new instance of the class + /// + /// + /// The schema of the body per declared media type; empty when no body is declared + /// + public OpenApiContent(IReadOnlyDictionary schemasByMediaType) + { + this.SchemasByMediaType = schemasByMediaType ?? throw new ArgumentNullException(nameof(schemasByMediaType)); + } + + /// + /// Gets the schema of the body per declared media type; empty when no body is declared + /// + public IReadOnlyDictionary SchemasByMediaType { get; } + + /// + /// Checks a body against the declared media types and their schemas + /// + /// + /// The media type of the body without parameters, or null when none was sent + /// + /// + /// The body, empty when there was none + /// + /// + /// The violations found, empty when the body conforms + /// + public IReadOnlyList Check(string mediaType, string body) + { + if (this.SchemasByMediaType.Count == 0) + { + return string.IsNullOrEmpty(body) ? [] : [new ContractViolation(ContractViolationKind.UnexpectedBody, "a body where the document declares none")]; + } + + var declared = this.SchemasByMediaType.Keys.FirstOrDefault(candidate => Accepts(candidate, mediaType)); + + if (declared == null && string.IsNullOrEmpty(body)) + { + return [new ContractViolation(ContractViolationKind.UnexpectedBody, $"no body where the document declares {string.Join(", ", this.SchemasByMediaType.Keys)}")]; + } + + if (declared == null) + { + return [new ContractViolation(ContractViolationKind.UndeclaredMediaType, $"media type {mediaType ?? "(none)"} where the document declares {string.Join(", ", this.SchemasByMediaType.Keys)}")]; + } + + if (!string.IsNullOrEmpty(body) && !IsJson(mediaType)) + { + return []; + } + + JsonDocument instance; + + try + { + instance = JsonDocument.Parse(string.IsNullOrEmpty(body) ? "null" : body); + } + catch (JsonException exception) + { + return [new ContractViolation(ContractViolationKind.InvalidJson, $"a {mediaType} body that is not JSON: {exception.Message}")]; + } + + using (instance) + { + var results = this.SchemasByMediaType[declared].Evaluate(instance.RootElement, Evaluation); + + return results.IsValid ? [] : [.. Summarize(results).Select(error => new ContractViolation(ContractViolationKind.SchemaMismatch, error))]; + } + } + + /// + /// Asserts whether a declared media type, which may be a range such as */*, accepts a media type + /// + /// + /// The declared media type or range + /// + /// + /// The media type of the body, or null + /// + /// + /// true when accepts + /// + private static bool Accepts(string declared, string mediaType) + { + if (declared == "*/*") + { + return true; + } + + if (mediaType == null) + { + return false; + } + + return declared.EndsWith("/*", StringComparison.Ordinal) + ? mediaType.StartsWith(declared[..^1], StringComparison.OrdinalIgnoreCase) + : string.Equals(declared, mediaType, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Gets the innermost anyOf or oneOf branch of an evaluation path, e.g. /$ref/anyOf/3/ + /// + /// + /// The evaluation path + /// + /// + /// The path of the branch with a trailing /, or null when the path is in no branch + /// + private static string BranchOf(string evaluationPath) + { + var segments = evaluationPath.Split('/'); + var branch = Array.FindLastIndex(segments, segment => segment is "anyOf" or "oneOf"); + + return branch < 0 || branch + 1 >= segments.Length ? null : $"{string.Join('/', segments[..(branch + 2)])}/"; + } + + /// + /// Collects the errors of a failed node and of its failed descendants; a node that passes, such as the + /// oneOf of a nullable property, contributes none of the errors of its rejected alternatives + /// + /// + /// The node, in the hierarchical output format + /// + /// + /// The errors, with the evaluation path and the instance location of their node + /// + private static IEnumerable<(string Path, string Location, string Keyword, string Message)> ErrorsOf(EvaluationResults node) + { + if (node.IsValid) + { + return []; + } + + var own = (node.Errors ?? new Dictionary()).Select(error => (node.EvaluationPath.ToString(), node.InstanceLocation.ToString(), error.Key, error.Value)); + + return own.Concat((node.Details ?? []).SelectMany(ErrorsOf)); + } + + /// + /// Asserts whether a media type is JSON, application/json or a +json suffix + /// + /// + /// The media type, or null + /// + /// + /// true for a JSON media type + /// + private static bool IsJson(string mediaType) + { + return mediaType != null && (string.Equals(mediaType, "application/json", StringComparison.OrdinalIgnoreCase) || mediaType.EndsWith("+json", StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Asserts whether an error is the rejection of the null alternative of a nullable value + /// + /// + /// The error + /// + /// + /// true for a type error that asks for null + /// + private static bool IsNullAlternative((string Path, string Location, string Keyword, string Message) error) + { + return error.Keyword == "type" && error.Message.EndsWith("should be \"null\"", StringComparison.Ordinal); + } + + /// + /// Asserts whether an instance location is an instance or lies within it + /// + /// + /// The instance location + /// + /// + /// The location of the instance + /// + /// + /// true when is or below it + /// + private static bool IsWithin(string location, string instance) + { + return location == instance || location.StartsWith($"{instance}/", StringComparison.Ordinal); + } + + /// + /// Summarizes the errors of a failed evaluation, one line per error: the errors inside an anyOf or + /// oneOf branch that an instance rejected on its @type are left out, as is the null + /// alternative of a nullable value that has errors of its own; when no branch accepts the @type, the + /// @type mismatches are reported + /// + /// + /// The results, in the hierarchical output format + /// + /// + /// At most lines of the form location keyword: message + /// + private static IReadOnlyList Summarize(EvaluationResults results) + { + var errors = ErrorsOf(results) + .Where(error => error.Keyword is not ("anyOf" or "oneOf" or "allOf" or "properties" or "items" or "$ref" or "")) + .Distinct() + .ToList(); + + var typeMismatches = errors.Where(error => error.Keyword == "const" && error.Location.EndsWith("/@type", StringComparison.Ordinal)).ToList(); + + var rejectedBranches = typeMismatches + .Select(error => (Instance: error.Location[..^"/@type".Length], Branch: BranchOf(error.Path))) + .Where(rejected => rejected.Branch != null) + .ToHashSet(); + + var locationsWithOtherErrors = errors.Where(error => !IsNullAlternative(error)).Select(error => error.Location).ToHashSet(); + + var specific = errors + .Where(error => !rejectedBranches.Any(rejected => IsWithin(error.Location, rejected.Instance) && $"{error.Path}/".StartsWith(rejected.Branch, StringComparison.Ordinal))) + .Where(error => !(IsNullAlternative(error) && locationsWithOtherErrors.Contains(error.Location))) + .ToList(); + + var reported = specific.Count > 0 ? specific : typeMismatches.Count > 0 ? typeMismatches : errors; + + return errors.Count == 0 + ? ["the body does not validate"] + : [.. reported.Take(ReportedErrors).Select(error => $"{(error.Location.Length == 0 ? "/" : error.Location)} {error.Keyword}: {error.Message}")]; + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs new file mode 100644 index 000000000..a6b83d534 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs @@ -0,0 +1,333 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net.Http; + using System.Text.Json; + using System.Text.Json.Nodes; + + using Json.Schema; + + /// + /// The operations of an OpenAPI 3.1 document, with their parameters, request bodies and responses as JSON + /// Schema 2020-12, and the matching of request paths to operations + /// + /// + /// The component schemas carry $ids, some relative, and are referenced both as + /// #/components/schemas/… and by those $ids; the $ids are removed and every reference made + /// absolute before any schema is built. + /// + public sealed class OpenApiDocument + { + /// + /// The base URI under which the component schemas are registered + /// + private const string DefinitionsUri = "urn:sysml2-net:openapi"; + + /// + /// The prefix of a reference to a component schema + /// + private const string SchemaReferencePrefix = "#/components/schemas/"; + + /// + /// The HTTP methods that OpenAPI path items can declare as operations + /// + private static readonly HashSet OperationMethods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]; + + /// + /// Initializes a new instance of the class + /// + /// + /// The operations of the document + /// + private OpenApiDocument(IReadOnlyList operations) + { + this.Operations = operations; + } + + /// + /// Gets the operations of the document + /// + public IReadOnlyList Operations { get; } + + /// + /// Reads an OpenAPI 3.1 document + /// + /// + /// The path of the OpenAPI JSON document + /// + /// + /// The + /// + public static OpenApiDocument Load(string path) + { + var root = JsonNode.Parse(File.ReadAllText(path))!.AsObject(); + var components = root["components"]?.AsObject() ?? []; + var schemas = components["schemas"]?.AsObject() ?? []; + + var keysById = schemas + .Where(schema => schema.Value?["$id"] is JsonValue) + .GroupBy(schema => (string)schema.Value["$id"], schema => schema.Key, StringComparer.Ordinal) + .Where(keys => keys.Count() == 1) + .ToDictionary(keys => keys.Key, keys => keys.Single(), StringComparer.Ordinal); + + RemoveIds(schemas); + RewriteSchemaReferences(root, keysById); + + var reader = new SchemaReader(); + + reader.Build(new JsonObject + { + ["$schema"] = "https://json-schema.org/draft/2020-12/schema", + ["$id"] = DefinitionsUri, + ["$defs"] = schemas.DeepClone() + }, new Uri(DefinitionsUri)); + + var operations = root["paths"]!.AsObject() + .SelectMany(pathItem => pathItem.Value!.AsObject() + .Where(operation => OperationMethods.Contains(operation.Key)) + .Select(operation => ReadOperation(pathItem.Key, pathItem.Value.AsObject(), operation.Key, operation.Value!.AsObject(), components, reader))) + .ToList(); + + return new OpenApiDocument(operations); + } + + /// + /// Finds the operation that a request addresses; where several templates match, the one with the most + /// literal segments wins + /// + /// + /// The method of the request + /// + /// + /// The path of the request relative to the base address of the API, without query + /// + /// + /// The matching , or null when none matches + /// + public OpenApiOperation Match(HttpMethod method, string relativePath) + { + var segments = relativePath.Split('/', StringSplitOptions.RemoveEmptyEntries); + + return this.Operations + .Where(operation => operation.Method == method && operation.Matches(segments)) + .OrderByDescending(operation => operation.LiteralSegmentCount) + .FirstOrDefault(); + } + + /// + /// Reads the body declared by a request body or response object: a schema per media type + /// + /// + /// The request body or response object, or null + /// + /// + /// The reader that builds the schemas + /// + /// + /// The , empty when no content is declared + /// + private static OpenApiContent ReadContent(JsonObject declaration, SchemaReader reader) + { + var content = declaration?["content"]?.AsObject() ?? []; + + return new OpenApiContent(content.ToDictionary( + mediaType => mediaType.Key, + mediaType => reader.Build(mediaType.Value?["schema"] ?? new JsonObject()), + StringComparer.OrdinalIgnoreCase)); + } + + /// + /// Reads one operation + /// + /// + /// The path template of the operation + /// + /// + /// The path item that declares the operation + /// + /// + /// The lower-case method of the operation + /// + /// + /// The operation object + /// + /// + /// The components that $refs to parameters and responses resolve against + /// + /// + /// The reader that builds the schemas + /// + /// + /// The + /// + private static OpenApiOperation ReadOperation(string pathTemplate, JsonObject pathItem, string method, JsonObject operation, JsonObject components, SchemaReader reader) + { + var parameters = (pathItem["parameters"]?.AsArray() ?? []).Concat(operation["parameters"]?.AsArray() ?? []) + .Select(parameter => Resolve(parameter!.AsObject(), components)) + .Select(parameter => new OpenApiParameter( + (string)parameter["name"], + (string)parameter["in"], + parameter["required"]?.GetValue() ?? false, + parameter["schema"]?["type"]?.GetValueKind() == JsonValueKind.String ? (string)parameter["schema"]["type"] : null, + reader.Build(parameter["schema"] ?? new JsonObject()))) + .ToList(); + + var requestBody = operation["requestBody"] is JsonObject body ? Resolve(body, components) : null; + + var responses = (operation["responses"]?.AsObject() ?? []) + .ToDictionary(response => response.Key, response => ReadContent(Resolve(response.Value!.AsObject(), components), reader), StringComparer.OrdinalIgnoreCase); + + return new OpenApiOperation( + new HttpMethod(method.ToUpperInvariant()), + pathTemplate, + parameters, + requestBody == null ? null : ReadContent(requestBody, reader), + requestBody?["required"]?.GetValue() ?? false, + responses); + } + + /// + /// Removes every $id from a tree of schemas + /// + /// + /// The root of the tree + /// + private static void RemoveIds(JsonNode node) + { + switch (node) + { + case JsonObject jsonObject: + jsonObject.Remove("$id"); + + foreach (var child in jsonObject.Select(property => property.Value).ToList()) + { + RemoveIds(child); + } + + break; + case JsonArray jsonArray: + foreach (var child in jsonArray) + { + RemoveIds(child); + } + + break; + } + } + + /// + /// Resolves an object that is a $ref to a component, e.g. #/components/responses/404 + /// + /// + /// The object, a reference or not + /// + /// + /// The components of the document + /// + /// + /// The referenced component, or when it is no reference + /// + /// + /// Thrown when the reference does not name a component of the document + /// + private static JsonObject Resolve(JsonObject declaration, JsonObject components) + { + if (declaration["$ref"]?.GetValue() is not { } reference) + { + return declaration; + } + + var parts = reference.Split('/'); + + return parts is ["#", "components", var kind, var name] && components[kind]?[name] is JsonObject component + ? component + : throw new InvalidOperationException($"The reference {reference} names no component of the document"); + } + + /// + /// Makes every reference to a component schema, by JSON pointer or by $id, absolute under + /// + /// + /// + /// The root of the tree + /// + /// + /// The key of every component schema, by its $id + /// + private static void RewriteSchemaReferences(JsonNode node, IReadOnlyDictionary keysById) + { + switch (node) + { + case JsonObject jsonObject: + if (jsonObject["$ref"] is JsonValue reference && reference.GetValue() is { } target) + { + var key = target.StartsWith(SchemaReferencePrefix, StringComparison.Ordinal) ? target[SchemaReferencePrefix.Length..] : keysById.GetValueOrDefault(target); + + if (key != null) + { + jsonObject["$ref"] = $"{DefinitionsUri}#/$defs/{key}"; + } + } + + foreach (var child in jsonObject.Select(property => property.Value).ToList()) + { + RewriteSchemaReferences(child, keysById); + } + + break; + case JsonArray jsonArray: + foreach (var child in jsonArray) + { + RewriteSchemaReferences(child, keysById); + } + + break; + } + } + + /// + /// Builds schemas against one registry that holds the component schemas, each under a base URI of its own + /// + private sealed class SchemaReader + { + /// + /// The options that every schema of the document is built with + /// + private readonly BuildOptions options = new() { SchemaRegistry = new SchemaRegistry() }; + + /// + /// The number of schemas built so far, which names the base URI of the next one + /// + private int count; + + /// + /// Builds a schema + /// + /// + /// The schema + /// + /// + /// The base URI of the schema, or null for a new one + /// + /// + /// The built + /// + public JsonSchema Build(JsonNode schema, Uri baseUri = null) + { + return JsonSchema.Build(JsonSerializer.SerializeToElement(schema), this.options, baseUri ?? new Uri($"{DefinitionsUri}:{++this.count}")); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiOperation.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiOperation.cs new file mode 100644 index 000000000..1eb723f04 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiOperation.cs @@ -0,0 +1,232 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Net; + using System.Net.Http; + + /// + /// One operation of an OpenAPI document: an HTTP method on a path template, with the parameters, request body and + /// responses it declares + /// + public sealed class OpenApiOperation + { + /// + /// The key of the response that covers every status the operation does not declare explicitly + /// + private const string DefaultResponse = "default"; + + /// + /// The segments of + /// + private readonly string[] segments; + + /// + /// Initializes a new instance of the class + /// + /// + /// The HTTP method + /// + /// + /// The path template, e.g. /projects/{projectId} + /// + /// + /// The parameters the operation declares + /// + /// + /// The request body the operation declares, or null when it declares none + /// + /// + /// Whether the request body is required + /// + /// + /// The responses the operation declares, by status code, status range such as 4XX, or default + /// + public OpenApiOperation(HttpMethod method, string pathTemplate, IReadOnlyList parameters, OpenApiContent requestBody, bool isRequestBodyRequired, IReadOnlyDictionary responses) + { + this.Method = method ?? throw new ArgumentNullException(nameof(method)); + this.PathTemplate = pathTemplate ?? throw new ArgumentNullException(nameof(pathTemplate)); + this.Parameters = parameters ?? throw new ArgumentNullException(nameof(parameters)); + this.RequestBody = requestBody; + this.IsRequestBodyRequired = isRequestBodyRequired; + this.Responses = responses ?? throw new ArgumentNullException(nameof(responses)); + this.segments = pathTemplate.Split('/', StringSplitOptions.RemoveEmptyEntries); + this.LiteralSegmentCount = this.segments.Count(segment => !IsParameter(segment)); + } + + /// + /// Gets the HTTP method + /// + public HttpMethod Method { get; } + + /// + /// Gets the path template + /// + public string PathTemplate { get; } + + /// + /// Gets the parameters the operation declares + /// + public IReadOnlyList Parameters { get; } + + /// + /// Gets the request body the operation declares, or null when it declares none + /// + public OpenApiContent RequestBody { get; } + + /// + /// Gets a value indicating whether the request body is required + /// + public bool IsRequestBodyRequired { get; } + + /// + /// Gets the responses the operation declares, by status code, status range such as 4XX, or default + /// + public IReadOnlyDictionary Responses { get; } + + /// + /// Gets a value indicating whether the document declares a client error (4xx) response for the operation + /// + public bool DeclaresClientError => this.Responses.Keys.Any(status => status.StartsWith('4')); + + /// + /// Gets the number of segments of that are not parameters + /// + public int LiteralSegmentCount { get; } + + /// + /// Checks a request against the query parameters and the request body the operation declares + /// + /// + /// The query of the request, with or without its leading ? + /// + /// + /// The media type of the body without parameters, or null when none was sent + /// + /// + /// The body, empty when there was none + /// + /// + /// The violations found, empty when the request conforms + /// + public IReadOnlyList CheckRequest(string query, string mediaType, string body) + { + var declared = this.Parameters.Where(parameter => parameter.Location == "query").ToDictionary(parameter => parameter.Name, StringComparer.Ordinal); + var sent = ParseQuery(query); + var violations = new List(); + + foreach (var (name, value) in sent) + { + violations.AddRange(declared.TryGetValue(name, out var parameter) + ? parameter.Check(value) + : [new ContractViolation(ContractViolationKind.UndeclaredParameter, $"query parameter {name} is not declared")]); + } + + violations.AddRange(declared.Values + .Where(parameter => parameter.IsRequired && !sent.Exists(pair => pair.Name == parameter.Name)) + .Select(parameter => new ContractViolation(ContractViolationKind.MissingParameter, $"required query parameter {parameter.Name} is missing"))); + + if (this.RequestBody == null) + { + violations.AddRange(string.IsNullOrEmpty(body) ? [] : [new ContractViolation(ContractViolationKind.UnexpectedBody, "a request body where the document declares none")]); + } + else if (!string.IsNullOrEmpty(body) || this.IsRequestBodyRequired) + { + violations.AddRange(this.RequestBody.Check(mediaType, body)); + } + + return violations; + } + + /// + /// Checks a response against the response the operation declares for its status + /// + /// + /// The status of the response + /// + /// + /// The media type of the body without parameters, or null when there was none + /// + /// + /// The body, empty when there was none + /// + /// + /// The violations found, empty when the response conforms + /// + public IReadOnlyList CheckResponse(HttpStatusCode statusCode, string mediaType, string body) + { + var status = ((int)statusCode).ToString(CultureInfo.InvariantCulture); + + var response = this.Responses.GetValueOrDefault(status) + ?? this.Responses.GetValueOrDefault($"{status[0]}XX") + ?? this.Responses.GetValueOrDefault(DefaultResponse); + + return response == null + ? [new ContractViolation(ContractViolationKind.UndeclaredStatus, $"status {status} is not declared")] + : response.Check(mediaType, body); + } + + /// + /// Asserts whether the segments of a request path fit + /// + /// + /// The segments of the request path + /// + /// + /// true when every literal segment is equal and every parameter segment is filled + /// + public bool Matches(string[] pathSegments) + { + return pathSegments.Length == this.segments.Length + && this.segments.Zip(pathSegments).All(pair => IsParameter(pair.First) || string.Equals(pair.First, pair.Second, StringComparison.Ordinal)); + } + + /// + /// Returns the operation as METHOD /path/template + /// + /// + /// The text of the operation + /// + public override string ToString() => $"{this.Method} {this.PathTemplate}"; + + /// + /// Asserts whether a template segment is a parameter, e.g. {projectId} + /// + /// + /// The template segment + /// + /// + /// true for a parameter segment + /// + private static bool IsParameter(string segment) => segment.StartsWith('{') && segment.EndsWith('}'); + + /// + /// Splits a query into its unescaped name and value pairs + /// + /// + /// The query, with or without its leading ? + /// + /// + /// The pairs, in order + /// + private static List<(string Name, string Value)> ParseQuery(string query) + { + return (query ?? string.Empty).TrimStart('?') + .Split('&', StringSplitOptions.RemoveEmptyEntries) + .Select(pair => pair.Split('=', 2)) + .Select(parts => (Uri.UnescapeDataString(parts[0]), parts.Length == 2 ? Uri.UnescapeDataString(parts[1]) : string.Empty)) + .ToList(); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs new file mode 100644 index 000000000..49e30a8fa --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs @@ -0,0 +1,124 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text.Json; + using System.Text.Json.Nodes; + + using Json.Schema; + + /// + /// One parameter that an OpenAPI operation declares + /// + public sealed class OpenApiParameter + { + /// + /// The options that values are evaluated with: format is asserted, as for uuid identifiers + /// + private static readonly EvaluationOptions Evaluation = new() { RequireFormatValidation = true }; + + /// + /// Initializes a new instance of the class + /// + /// + /// The name of the parameter, e.g. page[size] + /// + /// + /// Where the parameter goes: path, query, header or cookie + /// + /// + /// Whether the parameter is required + /// + /// + /// The type of the schema of the parameter, or null when it has none + /// + /// + /// The schema of the parameter + /// + public OpenApiParameter(string name, string location, bool isRequired, string type, JsonSchema schema) + { + this.Name = name ?? throw new ArgumentNullException(nameof(name)); + this.Location = location ?? throw new ArgumentNullException(nameof(location)); + this.IsRequired = isRequired; + this.Type = type; + this.Schema = schema ?? throw new ArgumentNullException(nameof(schema)); + } + + /// + /// Gets the name of the parameter + /// + public string Name { get; } + + /// + /// Gets where the parameter goes: path, query, header or cookie + /// + public string Location { get; } + + /// + /// Gets a value indicating whether the parameter is required + /// + public bool IsRequired { get; } + + /// + /// Gets the type of the schema of the parameter, or null when it has none + /// + public string Type { get; } + + /// + /// Gets the schema of the parameter + /// + public JsonSchema Schema { get; } + + /// + /// Checks the text of a value against the schema, reading an array as the comma-separated form style + /// that the document uses for its array parameters + /// + /// + /// The unescaped text of the value + /// + /// + /// The violations found, empty when the value conforms + /// + public IReadOnlyList Check(string value) + { + var instance = JsonSerializer.SerializeToElement(this.ToNode(value)); + + return this.Schema.Evaluate(instance, Evaluation).IsValid + ? [] + : [new ContractViolation(ContractViolationKind.InvalidParameter, $"{this.Name}={value} does not fit a {this.Type ?? "value"} of the declared schema")]; + } + + /// + /// Converts the text of a value to the JSON value that its schema describes; text that does not parse stays a + /// string, which the schema then rejects + /// + /// + /// The text of the value + /// + /// + /// The JSON value + /// + private JsonNode ToNode(string value) + { + return this.Type switch + { + "integer" when long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var integer) => JsonValue.Create(integer), + "number" when double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) => JsonValue.Create(number), + "boolean" when bool.TryParse(value, out var boolean) && value == value.ToLowerInvariant() => JsonValue.Create(boolean), + "array" => new JsonArray([.. value.Split(',').Select(item => (JsonNode)JsonValue.Create(item))]), + _ => JsonValue.Create(value) + }; + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs new file mode 100644 index 000000000..f940bb9f5 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs @@ -0,0 +1,366 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + + using NUnit.Framework; + + using SySML2.NET.REST; + + using SysML2.NET.Common; + using SysML2.NET.Core.DTO.Root.Elements; + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.Extensions.Core.DTO.Comparers; + using SysML2.NET.PSM; + using SysML2.NET.PSM.DTO; + + using Direction = SysML2.NET.PSM.Enumerations.Direction; + + /// + /// The assertions that every model step makes after a commit: the commit, its changes, and the model read back + /// through every read operation, against the model that was sent + /// + public sealed class ReadBackAssertions + { + /// + /// The page size used to read lists, small enough that a step's model spans several pages + /// + private const int PageSize = 10; + + /// + /// The maximum number of pages read from one list, guarding against a server that never ends a list + /// + private const int MaximumPages = 1000; + + /// + /// The client under test + /// + private readonly IPsmApiClient client; + + /// + /// The scenario state that read-back data is recorded in + /// + private readonly ScenarioState state; + + /// + /// Initializes a new instance of the class + /// + /// + /// The client under test + /// + /// + /// The scenario state that read-back data is recorded in + /// + public ReadBackAssertions(IPsmApiClient client, ScenarioState state) + { + this.client = client; + this.state = state; + } + + /// + /// Reads every page of a list operation, following + /// + /// + /// The type of the records + /// + /// + /// Reads one page for the given + /// + /// + /// The records of every page, in order, and the number of pages read + /// + /// + /// Thrown when the server repeats a page cursor or the list does not end within the page limit + /// + public static async Task<(IReadOnlyList Records, int Pages)> ReadAllPagesAsync(Func>> readPage) + { + var records = new List(); + var cursors = new HashSet(); + var parameters = new QueryParameters { PageSize = PageSize }; + + for (var pages = 1; pages <= MaximumPages; pages++) + { + var page = await readPage(parameters); + records.AddRange(page.Records); + + if (page.Next == null) + { + return (records, pages); + } + + if (!cursors.Add(page.Next.Value.Token)) + { + throw new InvalidOperationException($"The server repeated the page cursor {page.Next.Value.Token} after {pages} pages"); + } + + parameters = new QueryParameters { PageSize = PageSize, PageAfter = page.Next }; + } + + throw new InvalidOperationException($"The list did not end within {MaximumPages} pages"); + } + + /// + /// Verifies a commit on a branch: the commit itself, its place in the history, the branch head and its changes + /// + /// + /// The commit that PostCommitByProjectAsync returned + /// + /// + /// The branch the commit was made on + /// + /// + /// The head of the branch before the commit, or null for the first commit + /// + /// + /// The elements the commit created or replaced + /// + /// + /// An awaitable + /// + public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previousCommitId, IReadOnlyList changed) + { + var projectId = this.state.ProjectId!.Value; + + Guid[] expectedPrevious = previousCommitId.HasValue ? [previousCommitId.Value] : []; + + var commitById = await this.client.GetCommitByProjectAndIdAsync(projectId, commit.Id); + var (commits, _) = await ReadAllPagesAsync(parameters => this.client.GetCommitsByProjectAsync(projectId, parameters)); + var branch = await this.client.GetBranchesByProjectAndIdAsync(projectId, branchId); + var (changes, changePages) = await ReadAllPagesAsync(parameters => this.client.GetChangesByProjectCommitAsync(projectId, commit.Id, parameters)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(commitById.Id, Is.EqualTo(commit.Id)); + Assert.That(commitById.OwningProject, Is.EqualTo(projectId)); + Assert.That(commitById.PreviousCommit, Is.EqualTo(expectedPrevious)); + Assert.That(commits.Select(record => record.Id), Does.Contain(commit.Id)); + Assert.That(branch.Head, Is.EqualTo(commit.Id)); + Assert.That(changes.Select(change => change.Identity.Id), Is.EquivalentTo(changed.Select(element => element.Id))); + Assert.That(changePages, Is.GreaterThan(1), "the changes did not span several pages, so paging is untested"); + + var sentById = changed.ToDictionary(element => element.Id); + + foreach (var change in changes.Where(change => sentById.ContainsKey(change.Identity.Id))) + { + VerifySame(sentById[change.Identity.Id], change.Payload as IElement, $"the payload of change {change.Id}"); + } + } + + if (changes.Count == 0) + { + return; + } + + var firstChange = changes[0]; + var changeById = await this.client.GetChangeByProjectCommitIdAsync(projectId, commit.Id, firstChange.Id); + + using (Assert.EnterMultipleScope()) + { + Assert.That(changeById.Id, Is.EqualTo(firstChange.Id)); + Assert.That(changeById.Identity.Id, Is.EqualTo(firstChange.Identity.Id)); + + if (firstChange.Payload is IElement firstPayload) + { + VerifySame(firstPayload, changeById.Payload as IElement, $"the payload of change {changeById.Id} read by id"); + } + } + } + + /// + /// Verifies the model at a commit through every element read operation, recording what the server returned + /// + /// + /// The commit to read the model at + /// + /// + /// The complete model expected at + /// + /// + /// The element whose relationships are read in each direction + /// + /// + /// An awaitable + /// + public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expected, Guid relationshipSubjectId) + { + var projectId = this.state.ProjectId!.Value; + var readById = new Dictionary(); + + foreach (var element in expected) + { + readById[element.Id] = await this.client.GetElementByProjectCommitIdAsync(projectId, commitId, element.Id); + } + + this.state.ReadBack.AddRange(readById.Values.Select(element => (commitId, (IData)element))); + + var (listed, listPages) = await ReadAllPagesAsync(parameters => this.client.GetElementsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)); + var (roots, _) = await ReadAllPagesAsync(parameters => this.client.GetRootsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)); + + using (Assert.EnterMultipleScope()) + { + foreach (var element in expected) + { + VerifySame(element, readById[element.Id], $"{element.GetType().Name} {element.Id}"); + } + + Assert.That(listed.Select(element => element.Id), Is.EquivalentTo(expected.Select(element => element.Id))); + Assert.That(listPages, Is.GreaterThan(1), "the elements did not span several pages, so paging is untested"); + VerifyRoots(roots, expected); + + VerifyMemberships(expected, readById); + VerifyNoEmptyReferences(readById.Values); + } + + await this.VerifyRelationshipsAsync(commitId, expected, relationshipSubjectId); + } + + /// + /// Verifies that every membership read back names the member element and member name that were sent, + /// which the generated comparers do not compare + /// + /// + /// The model that was sent + /// + /// + /// The elements read back, by id + /// + private static void VerifyMemberships(IReadOnlyList expected, IReadOnlyDictionary readById) + { + foreach (var membership in expected.OfType()) + { + var actual = readById[membership.Id] as IMembership; + + Assert.That(actual?.MemberElement, Is.EqualTo(membership.MemberElement), $"{membership.GetType().Name} {membership.Id} lost its memberElement (#424)"); + Assert.That(actual?.MemberName, Is.EqualTo(membership.MemberName), $"{membership.GetType().Name} {membership.Id} lost its memberName (#424)"); + } + } + + /// + /// Verifies that no non-derived reference read back is the empty GUID, which refers to no element + /// + /// + /// The elements read back + /// + private static void VerifyNoEmptyReferences(IEnumerable elements) + { + foreach (var element in elements.Where(element => element != null)) + { + var emptyReferences = DtoMetadata.PropertiesOf(element.GetType()) + .Where(property => property.ValueOf(element) switch + { + Guid reference => reference == Guid.Empty, + IEnumerable references => references.Contains(Guid.Empty), + _ => false + }) + .Select(property => property.Name) + .ToList(); + + Assert.That(emptyReferences, Is.Empty, $"{element.GetType().Name} {element.Id} holds empty references (#424)"); + } + } + + /// + /// Verifies the roots read back: exactly the elements without an owner, or, as the known divergence + /// , exactly the elements without an + /// owningRelatedElement + /// + /// + /// The roots read back + /// + /// + /// The model that was sent + /// + private static void VerifyRoots(IReadOnlyList roots, IReadOnlyList model) + { + var rootIds = roots.Select(element => element.Id).ToHashSet(); + var unowned = model.Where(element => element.owner == null).Select(element => element.Id).ToList(); + var notOwnedRelated = model.Where(element => element is not IRelationship { OwningRelatedElement: not null }).Select(element => element.Id).ToList(); + + if (!rootIds.SetEquals(unowned) && roots.Count == notOwnedRelated.Count && rootIds.SetEquals(notOwnedRelated)) + { + KnownServerDivergences.Report(KnownServerDivergences.RootsIgnoreOwningRelationship, $"{roots.Count} roots for {unowned.Count} elements without an owner"); + return; + } + + Assert.That(roots.Select(element => element.Id), Is.EquivalentTo(unowned), "the roots are the elements without an owner"); + } + + /// + /// Verifies that an element read back is of the metaclass that was sent and equal to it, naming the + /// properties that differ + /// + /// + /// The element that was sent + /// + /// + /// The element read back, or null + /// + /// + /// The description of the element in assertion messages + /// + private static void VerifySame(IElement sent, IElement actual, string description) + { + Assert.That(actual, Is.TypeOf(sent.GetType()), $"{description} was read back as another metaclass"); + + if (actual?.GetType() != sent.GetType() || ComparerProvider.Resolve(sent).Equals(sent, actual)) + { + return; + } + + var differing = DtoMetadata.PropertiesOf(sent.GetType()) + .Where(property => !DtoMetadata.ValueEquals(property.ValueOf(sent), property.ValueOf(actual))) + .Select(property => property.Name) + .ToList(); + + Assert.Fail($"{description} differs from what was sent: {(differing.Count == 0 ? "a member that only its comparer compares" : string.Join(", ", differing))}"); + } + + /// + /// Verifies the relationships of an element in each direction against the sources and targets that were sent + /// + /// + /// The commit to read at + /// + /// + /// The model that was sent + /// + /// + /// The related element + /// + /// + /// An awaitable + /// + private async Task VerifyRelationshipsAsync(Guid commitId, IReadOnlyList expected, Guid subjectId) + { + var projectId = this.state.ProjectId!.Value; + var relationships = expected.OfType().ToList(); + + var outgoing = relationships.Where(relationship => relationship.Source.Contains(subjectId)).Select(relationship => relationship.Id).ToList(); + var incoming = relationships.Where(relationship => relationship.Target.Contains(subjectId)).Select(relationship => relationship.Id).ToList(); + + var (readOut, _) = await ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, Direction.@out, queryParameters: parameters)); + var (readIn, _) = await ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, Direction.@in, queryParameters: parameters)); + var (readBoth, _) = await ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, Direction.both, queryParameters: parameters)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(outgoing, Is.Not.Empty, "the subject is the source of no relationship, so the out direction is untested"); + Assert.That(incoming, Is.Not.Empty, "the subject is the target of no relationship, so the in direction is untested"); + Assert.That(readOut.Select(relationship => relationship.Id), Is.EquivalentTo(outgoing)); + Assert.That(readIn.Select(relationship => relationship.Id), Is.EquivalentTo(incoming)); + Assert.That(readBoth.Select(relationship => relationship.Id), Is.EquivalentTo(outgoing.Union(incoming))); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs new file mode 100644 index 000000000..fc7e88770 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs @@ -0,0 +1,50 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + using System.Collections.Generic; + + using SysML2.NET.Common; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + + /// + /// The state that the steps of the scenario hand on to each other: the ids the server assigned, the model as it + /// should be at each commit, and everything the server returned + /// + public sealed class ScenarioState + { + /// + /// Gets or sets the id of the project the model is built in, or null before it is created + /// + public Guid? ProjectId { get; set; } + + /// + /// Gets or sets the id of the default branch of the project + /// + public Guid? DefaultBranchId { get; set; } + + /// + /// Gets or sets the id of the latest commit on the default branch, or null before the first commit + /// + public Guid? HeadCommitId { get; set; } + + /// + /// Gets the expected model at each commit, by commit id + /// + public Dictionary> ExpectedModels { get; } = []; + + /// + /// Gets every data item the server returned, with the commit it was read at + /// + public List<(Guid CommitId, IData Data)> ReadBack { get; } = []; + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs b/SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs new file mode 100644 index 000000000..ad6f512a5 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs @@ -0,0 +1,27 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System; + + /// + /// A way in which the server under the scenario diverges from the specification + /// + /// + /// What the server does differently + /// + /// + /// Where the behaviour was found, or the upstream issue that reports it + /// + /// + /// Whether the divergence explains a contract violation of a response, or null when it explains none + /// + public sealed record ServerDivergence(string Summary, string Reference, Func Explains = null); +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/BearerTokenHandlerTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/BearerTokenHandlerTestFixture.cs new file mode 100644 index 000000000..106cafde2 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/BearerTokenHandlerTestFixture.cs @@ -0,0 +1,64 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading.Tasks; + + using NUnit.Framework; + + using RichardSzalay.MockHttp; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class BearerTokenHandlerTestFixture + { + [Test] + public void VerifyBearerTokenHandler() + { + using var inner = new MockHttpMessageHandler(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(() => new BearerTokenHandler(null, inner), Throws.ArgumentException.With.Property(nameof(ArgumentException.ParamName)).EqualTo("token")); + Assert.That(() => new BearerTokenHandler(string.Empty, inner), Throws.ArgumentException); + Assert.That(() => new BearerTokenHandler(" ", inner), Throws.ArgumentException); + Assert.That(() => new BearerTokenHandler("abc", inner).Dispose(), Throws.Nothing); + } + } + + [Test] + public async Task VerifySendAsync() + { + using var inner = new MockHttpMessageHandler(); + inner.When("http://localhost/*").WithHeaders("Authorization", "Bearer abc").Respond("application/json", "{}"); + inner.Fallback.Respond(System.Net.HttpStatusCode.Unauthorized); + + using var httpClient = new HttpClient(new BearerTokenHandler("abc", inner)) { BaseAddress = new Uri("http://localhost/") }; + + using var withoutHeader = new HttpRequestMessage(HttpMethod.Get, "projects"); + using var withOtherHeader = new HttpRequestMessage(HttpMethod.Get, "projects"); + withOtherHeader.Headers.Authorization = new AuthenticationHeaderValue("Basic", "x"); + + using var first = await httpClient.SendAsync(withoutHeader); + using var second = await httpClient.SendAsync(withOtherHeader); + + using (Assert.EnterMultipleScope()) + { + Assert.That(first.IsSuccessStatusCode, Is.True); + Assert.That(second.IsSuccessStatusCode, Is.True); + Assert.That(withOtherHeader.Headers.Authorization?.ToString(), Is.EqualTo("Bearer abc")); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs new file mode 100644 index 000000000..c8003d879 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs @@ -0,0 +1,120 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.IO; + using System.Linq; + using System.Net; + + using NUnit.Framework; + + using SysML2.NET.Common; + using SysML2.NET.Core.DTO.Core.Features; + using SysML2.NET.Core.DTO.Kernel.Packages; + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.Core.Root.Namespaces; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class CoverageVerdictTestFixture + { + private OpenApiDocument openApi; + + [SetUp] + public void SetUp() + { + this.openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + } + + [Test] + public void VerifyCoverageVerdict() + { + var packageId = Guid.NewGuid(); + var firstCommit = Guid.NewGuid(); + var secondCommit = Guid.NewGuid(); + + (Guid CommitId, IData Data)[] packagesOnly = + [ + (firstCommit, new Package { Id = packageId, DeclaredName = "A" }), + (secondCommit, new Package { Id = packageId, DeclaredName = "B" }), + (secondCommit, null) + ]; + + var getProjects = this.Operation("GET /projects"); + var getProject = this.Operation("GET /projects/{projectId}"); + var deleteProject = this.Operation("DELETE /projects/{projectId}"); + + EndpointCall[] calls = + [ + new(getProjects, "GET /projects", HttpStatusCode.OK), + new(getProject, "GET /projects/p", HttpStatusCode.OK), + new(getProject, "GET /projects/r", HttpStatusCode.InternalServerError), + new(deleteProject, "DELETE /projects/r", HttpStatusCode.InternalServerError), + new(null, "GET /unknown", HttpStatusCode.NotFound), + new(null, "GET /unknown", HttpStatusCode.NotFound) + ]; + + var verdict = new CoverageVerdict(packagesOnly, calls, this.openApi); + + using (Assert.EnterMultipleScope()) + { + Assert.That(verdict.MissingMetaclasses, Does.Contain(nameof(OwningMembership)).And.Not.Contain(nameof(Package))); + Assert.That(verdict.UnsetProperties, Does.Not.Contain("Element.DeclaredName").And.Contain("Element.DeclaredShortName")); + Assert.That(verdict.UnchangedProperties, Does.Not.Contain("Element.DeclaredName").And.Contain("Element.DeclaredShortName")); + Assert.That(verdict.MissingLiterals, Does.Contain("VisibilityKind.Private")); + Assert.That(verdict.MissingLiterals, Has.None.StartsWith("ClassKind.")); + Assert.That(verdict.UncoveredOperations, Has.None.StartsWith("GET /projects (")); + Assert.That(verdict.UncoveredOperations, Does.Contain("GET /projects/{projectId} (no 4xx)").And.Not.Contain("GET /projects/{projectId} (no 2xx)")); + Assert.That(verdict.UncoveredOperations, Does.Contain("DELETE /projects/{projectId} (no 2xx)")); + Assert.That(verdict.UnmatchedRequests, Is.EqualTo((string[])["GET /unknown"])); + } + + (Guid CommitId, IData Data)[] withMembership = + [ + .. packagesOnly, + (secondCommit, new OwningMembership { Id = Guid.NewGuid(), Visibility = VisibilityKind.Private }) + ]; + + EndpointCall[] withNotFound = [.. calls, new(getProject, "GET /projects/q", HttpStatusCode.NotFound)]; + + var completer = new CoverageVerdict(withMembership, withNotFound, this.openApi); + + using (Assert.EnterMultipleScope()) + { + Assert.That(completer.MissingMetaclasses, Does.Not.Contain(nameof(OwningMembership))); + Assert.That(completer.UnsetProperties, Does.Not.Contain("Membership.Visibility")); + Assert.That(completer.MissingLiterals, Does.Not.Contain("VisibilityKind.Private")); + Assert.That(completer.UncoveredOperations, Has.None.StartsWith("GET /projects/{projectId} (")); + } + + (Guid CommitId, IData Data)[] distinctElements = + [ + (firstCommit, new Package { Id = Guid.NewGuid(), DeclaredName = "X" }), + (firstCommit, new Package { Id = Guid.NewGuid(), DeclaredName = "Y" }), + (firstCommit, new OwningMembership { Id = Guid.NewGuid() }), + (firstCommit, new Feature { Id = Guid.NewGuid(), Direction = null }) + ]; + + var distinct = new CoverageVerdict(distinctElements, [], this.openApi); + + using (Assert.EnterMultipleScope()) + { + Assert.That(distinct.UnchangedProperties, Does.Contain("Element.DeclaredName")); + Assert.That(distinct.MissingLiterals, Does.Not.Contain("VisibilityKind.Public").And.Contain("VisibilityKind.Private")); + Assert.That(distinct.MissingLiterals, Does.Contain("FeatureDirectionKind.In").And.Contain("FeatureDirectionKind.Inout").And.Contain("FeatureDirectionKind.Out")); + Assert.That(distinct.UnsetProperties, Does.Contain("Feature.Direction")); + } + } + + private OpenApiOperation Operation(string text) => this.openApi.Operations.Single(operation => operation.ToString() == text); + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/DeterministicGuidTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/DeterministicGuidTestFixture.cs new file mode 100644 index 000000000..5f9692de7 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/DeterministicGuidTestFixture.cs @@ -0,0 +1,40 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class DeterministicGuidTestFixture + { + [Test] + public void VerifyCreate() + { + var guid = DeterministicGuid.Create("root/CoverageModel"); + var bytes = guid.ToByteArray(true); + + using (Assert.EnterMultipleScope()) + { + Assert.That(guid, Is.EqualTo(new Guid("9ca3add6-05b7-5b0f-9012-32f191129875")), "the version 5 UUID that RFC 9562 gives for the name in the scenario namespace"); + Assert.That(bytes[6] >> 4, Is.EqualTo(5), "version"); + Assert.That(bytes[8] >> 6, Is.EqualTo(0b10), "variant"); + Assert.That(DeterministicGuid.Create("root/CoverageModel"), Is.EqualTo(guid)); + Assert.That(DeterministicGuid.Create("root/Nested"), Is.Not.EqualTo(guid)); + Assert.That(() => DeterministicGuid.Create(null), Throws.ArgumentException); + Assert.That(() => DeterministicGuid.Create(string.Empty), Throws.ArgumentException); + Assert.That(() => DeterministicGuid.Create(" "), Throws.ArgumentException); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/DtoMetadataTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/DtoMetadataTestFixture.cs new file mode 100644 index 000000000..cc7a3b931 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/DtoMetadataTestFixture.cs @@ -0,0 +1,91 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using NUnit.Framework; + + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.Extensions.Core.DTO.Comparers; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class DtoMetadataTestFixture + { + [Test] + public void VerifyConcreteClasses() + { + Assert.That(() => DtoMetadata.ConcreteClasses.Select(ComparerProvider.Resolve).ToList(), Throws.Nothing, "every concrete DTO class has a generated comparer"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(DtoMetadata.ConcreteClasses, Does.Contain(typeof(OwningMembership))); + Assert.That(DtoMetadata.ConcreteClasses, Has.None.Matches(type => type.IsAbstract || type.IsInterface)); + } + } + + [Test] + public void VerifyDeclaredProperties() + { + var names = DtoMetadata.DeclaredProperties.Select(property => property.Name).ToList(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(names, Is.Unique); + Assert.That(names, Does.Contain("Membership.MemberElement")); + Assert.That(names, Does.Contain("Element.DeclaredName")); + Assert.That(names, Does.Not.Contain("Element.name")); + Assert.That(names, Does.Not.Contain("OwningMembership.ownedMemberElement")); + } + } + + [Test] + public void VerifyDerivedPropertyNames() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(DtoMetadata.DerivedPropertyNames, Does.Contain("owner").And.Contain("qualifiedName").And.Contain("ownedMemberElement")); + Assert.That(DtoMetadata.DerivedPropertyNames, Does.Not.Contain("declaredName").And.Not.Contain("alias").And.Not.Contain("aliasIds")); + Assert.That(DtoMetadata.DerivedPropertyNames, Has.None.Matches(name => char.IsUpper(name[0]))); + } + } + + [Test] + public void VerifyPropertiesOf() + { + var names = DtoMetadata.PropertiesOf(typeof(OwningMembership)).Select(property => property.Name).ToList(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(names, Does.Contain("Membership.MemberElement")); + Assert.That(names, Does.Contain("Relationship.OwnedRelatedElement")); + Assert.That(names, Does.Not.Contain("Dependency.Client")); + } + } + + [Test] + public void VerifyValueEquals() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(DtoMetadata.ValueEquals((List)[1, 2], (int[])[1, 2]), Is.True); + Assert.That(DtoMetadata.ValueEquals((List)[1, 2], (int[])[2, 1]), Is.False); + Assert.That(DtoMetadata.ValueEquals("abc", "abc"), Is.True); + Assert.That(DtoMetadata.ValueEquals("abc", "abd"), Is.False); + Assert.That(DtoMetadata.ValueEquals(null, null), Is.True); + Assert.That(DtoMetadata.ValueEquals(null, false), Is.False); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/EndpointCallTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/EndpointCallTestFixture.cs new file mode 100644 index 000000000..ee1a17ed9 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/EndpointCallTestFixture.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System.Linq; + using System.Net; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class EndpointCallTestFixture + { + private static readonly int[] Statuses = [199, 200, 299, 300, 304, 399, 400, 499, 500]; + + [Test] + public void VerifyEndpointCall() + { + var call = new EndpointCall(null, "GET /projects", HttpStatusCode.OK); + + using (Assert.EnterMultipleScope()) + { + Assert.That(call.RequestViolations, Is.Empty); + Assert.That(call.ResponseViolations, Is.Empty); + } + } + + [Test] + public void VerifyIsClientError() + { + var clientErrors = Statuses.Where(status => new EndpointCall(null, "GET /", (HttpStatusCode)status).IsClientError); + + Assert.That(clientErrors, Is.EqualTo((int[])[400, 499])); + } + + [Test] + public void VerifyIsSuccess() + { + var successes = Statuses.Where(status => new EndpointCall(null, "GET /", (HttpStatusCode)status).IsSuccess); + + Assert.That(successes, Is.EqualTo((int[])[200, 299])); + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs new file mode 100644 index 000000000..4729dc0f4 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs @@ -0,0 +1,106 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + + using NUnit.Framework; + + using RichardSzalay.MockHttp; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class EndpointRecorderTestFixture + { + private const string ProjectBody = "{\"@id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\",\"@type\":\"Project\",\"alias\":[],\"created\":\"1970-01-01T00:00:00.000Z\",\"defaultBranch\":{\"@id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa7\"},\"description\":null,\"name\":\"p\"}"; + + private MockHttpMessageHandler mockHttp; + + private OpenApiDocument openApi; + + private EndpointRecorder recorder; + + private HttpClient httpClient; + + [SetUp] + public void SetUp() + { + this.openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + this.mockHttp = new MockHttpMessageHandler(); + this.recorder = new EndpointRecorder(this.openApi, this.mockHttp); + this.httpClient = new HttpClient(this.recorder) { BaseAddress = new Uri("http://localhost/") }; + } + + [TearDown] + public void TearDown() + { + this.httpClient.Dispose(); + } + + [Test] + public void VerifyEndpointRecorder() + { + Assert.That(() => new EndpointRecorder(null, this.mockHttp), Throws.ArgumentNullException); + + using (Assert.EnterMultipleScope()) + { + Assert.That(this.recorder.Calls, Is.Empty); + Assert.That(this.recorder.EmptyGuidRequests, Is.Empty); + Assert.That(this.recorder.LastCall, Is.Null); + } + } + + [Test] + public async Task VerifySendAsync() + { + this.mockHttp.When(HttpMethod.Get, "http://localhost/projects/p").Respond(HttpStatusCode.NotFound); + this.mockHttp.When(HttpMethod.Post, "http://localhost/projects").Respond(HttpStatusCode.Created, "application/json", ProjectBody); + this.mockHttp.When(HttpMethod.Get, "http://localhost/projects").Respond("application/json", "[{}]"); + this.mockHttp.When(HttpMethod.Get, "http://localhost/unknown").Respond(HttpStatusCode.OK); + + var notFound = await this.httpClient.GetAsync("projects/p"); + var created = await this.httpClient.PostAsync("projects", new StringContent("{\"@type\":\"Project\",\"name\":\"p\",\"defaultBranch\":{\"@id\":\"00000000-0000-0000-0000-000000000000\"}}", Encoding.UTF8, "application/json")); + await this.httpClient.PostAsync("projects?name=x", new StringContent("{\"@type\":\"Project\",\"name\":5}", Encoding.UTF8, "application/json")); + await this.httpClient.GetAsync("projects?page%5Bsize%5D=10"); + await this.httpClient.GetAsync("unknown"); + + var calls = this.recorder.Calls.ToList(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(notFound.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); + Assert.That(await created.Content.ReadAsStringAsync(), Is.EqualTo(ProjectBody), "the client can still read the buffered body"); + Assert.That(calls, Has.Count.EqualTo(5)); + Assert.That(this.recorder.LastCall, Is.SameAs(calls[^1])); + Assert.That(calls[0].Operation?.PathTemplate, Is.EqualTo("/projects/{projectId}")); + Assert.That(calls[0].StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); + Assert.That(calls[0].RequestLine, Is.EqualTo("GET /projects/p")); + Assert.That(calls[0].RequestViolations, Is.Empty); + Assert.That(calls[0].ResponseViolations.Select(violation => violation.Kind), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UnexpectedBody])); + Assert.That(calls[1].Operation?.ToString(), Is.EqualTo("POST /projects")); + Assert.That(calls[1].RequestViolations, Is.Empty); + Assert.That(calls[1].ResponseViolations, Is.Empty); + Assert.That(calls[2].RequestViolations.Select(violation => violation.Kind), Is.EquivalentTo((ContractViolationKind[])[ContractViolationKind.UndeclaredParameter, ContractViolationKind.SchemaMismatch])); + Assert.That(calls[3].RequestViolations, Is.Empty); + Assert.That(calls[3].ResponseViolations.Select(violation => violation.Kind), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.SchemaMismatch])); + Assert.That(calls[4].Operation, Is.Null); + Assert.That(calls[4].ResponseViolations, Is.Empty); + Assert.That(this.recorder.EmptyGuidRequests, Is.EqualTo((string[])["POST /projects"])); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/FlexoJwtTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/FlexoJwtTestFixture.cs new file mode 100644 index 000000000..e7411f15b --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/FlexoJwtTestFixture.cs @@ -0,0 +1,64 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Text.Json; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class FlexoJwtTestFixture + { + [Test] + public void VerifyCreateToken() + { + var jwt = new FlexoJwt(); + var token = jwt.CreateToken(TimeSpan.FromHours(1)); + var parts = token.Split('.'); + + Assert.That(parts, Has.Length.EqualTo(3)); + + using var header = JsonDocument.Parse(FromBase64Url(parts[0])); + using var payload = JsonDocument.Parse(FromBase64Url(parts[1])); + + using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(jwt.Secret)); + var signature = hmac.ComputeHash(Encoding.ASCII.GetBytes($"{parts[0]}.{parts[1]}")); + var tamperedSignature = hmac.ComputeHash(Encoding.ASCII.GetBytes($"{parts[0]}.{parts[1]}x")); + + using (Assert.EnterMultipleScope()) + { + Assert.That(token, Does.Not.Contain("=").And.Not.Contain("+").And.Not.Contain("/")); + Assert.That(header.RootElement.GetProperty("alg").GetString(), Is.EqualTo("HS256")); + Assert.That(header.RootElement.GetProperty("typ").GetString(), Is.EqualTo("JWT")); + Assert.That(payload.RootElement.GetProperty("iss").GetString(), Is.EqualTo(FlexoJwt.Issuer)); + Assert.That(payload.RootElement.GetProperty("aud").GetString(), Is.EqualTo(FlexoJwt.Audience)); + Assert.That(payload.RootElement.GetProperty("username").GetString(), Is.EqualTo(FlexoJwt.UserName)); + Assert.That(payload.RootElement.GetProperty("groups").EnumerateArray().Select(group => group.GetString()), Is.EqualTo((string[])[FlexoJwt.Group])); + Assert.That(payload.RootElement.GetProperty("exp").GetInt64() - payload.RootElement.GetProperty("iat").GetInt64(), Is.EqualTo(3600)); + Assert.That(FromBase64Url(parts[2]), Is.EqualTo(signature)); + Assert.That(FromBase64Url(parts[2]), Is.Not.EqualTo(tamperedSignature)); + Assert.That(jwt.Secret, Has.Length.GreaterThanOrEqualTo(32)); + Assert.That(new FlexoJwt().Secret, Is.Not.EqualTo(jwt.Secret)); + } + } + + private static byte[] FromBase64Url(string text) + { + var base64 = text.Replace('-', '+').Replace('_', '/'); + return Convert.FromBase64String(base64.PadRight(base64.Length + ((4 - (base64.Length % 4)) % 4), '=')); + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/IntegrationHttpClientFactoryTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/IntegrationHttpClientFactoryTestFixture.cs new file mode 100644 index 000000000..203a3451a --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/IntegrationHttpClientFactoryTestFixture.cs @@ -0,0 +1,77 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.IO; + using System.Net.Http; + using System.Threading.Tasks; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class IntegrationHttpClientFactoryTestFixture + { + private static readonly Uri Unreachable = new("http://127.0.0.1:1/projects"); + + private OpenApiDocument openApi; + + [SetUp] + public void SetUp() + { + this.openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + } + + [Test] + public async Task VerifyCreateClient() + { + using var factory = new IntegrationHttpClientFactory("token", this.openApi); + + var first = factory.CreateClient("first"); + var second = factory.CreateClient("second"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(second, Is.Not.SameAs(first)); + Assert.That(factory.Recorder, Is.Not.Null); + } + + first.Dispose(); + + await Assert.ThatAsync(() => second.GetAsync(Unreachable), Throws.InstanceOf(), "disposing one client leaves the shared chain intact"); + Assert.That(factory.Recorder.Calls, Is.Empty); + + second.Dispose(); + } + + [Test] + public async Task VerifyDispose() + { + var factory = new IntegrationHttpClientFactory("token", this.openApi); + using var client = factory.CreateClient(string.Empty); + + factory.Dispose(); + + await Assert.ThatAsync(() => client.GetAsync(Unreachable), Throws.InstanceOf()); + } + + [Test] + public void VerifyIntegrationHttpClientFactory() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(() => new IntegrationHttpClientFactory(" ", this.openApi), Throws.ArgumentException); + Assert.That(() => new IntegrationHttpClientFactory("token", null), Throws.ArgumentNullException); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/IsolatedAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/IsolatedAssertionsTestFixture.cs new file mode 100644 index 000000000..d195a149c --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/IsolatedAssertionsTestFixture.cs @@ -0,0 +1,67 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System.Linq; + using System.Threading.Tasks; + + using NUnit.Framework; + using NUnit.Framework.Interfaces; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class IsolatedAssertionsTestFixture + { + [Test] + public async Task VerifyRunAsync() + { + var passed = await IsolatedAssertions.RunAsync(() => + { + Assert.That(1, Is.EqualTo(1)); + return Task.CompletedTask; + }); + + var warned = await IsolatedAssertions.RunAsync(() => + { + Assert.Warn("warned"); + return Task.CompletedTask; + }); + + var failed = await IsolatedAssertions.RunAsync(async () => + { + await Task.Yield(); + Assert.That(1, Is.EqualTo(2), "failed"); + }); + + var failedTwice = await IsolatedAssertions.RunAsync(() => + { + using (Assert.EnterMultipleScope()) + { + Assert.That(1, Is.EqualTo(2), "first"); + Assert.That(1, Is.EqualTo(3), "second"); + } + + return Task.CompletedTask; + }); + + using (Assert.EnterMultipleScope()) + { + Assert.That(passed, Is.Empty); + Assert.That(warned.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(warned[0].Message, Does.Contain("warned")); + Assert.That(failed.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(failed[0].Message, Does.Contain("failed")); + Assert.That(failedTwice, Has.Count.EqualTo(2)); + Assert.That(failedTwice[1].Message, Does.Contain("second")); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs new file mode 100644 index 000000000..8b78af677 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs @@ -0,0 +1,201 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Threading.Tasks; + + using NUnit.Framework; + using NUnit.Framework.Interfaces; + + using SySML2.NET.REST.Tests.Helpers; + + using SysML2.NET.PSM.DTO; + using SysML2.NET.REST.Exceptions; + + [TestFixture] + public class KnownServerDivergencesTestFixture + { + private static readonly EndpointCall Conforming = new(null, "GET /projects/p", HttpStatusCode.NotFound); + + private static readonly EndpointCall Breaking = Conforming with { ResponseViolations = [new ContractViolation(ContractViolationKind.UnexpectedBody, "no body")] }; + + [Test] + public void VerifyAll() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri])); + Assert.That(KnownServerDivergences.All.Select(divergence => divergence.Reference), Has.All.Contains("Open-MBEE/flexo-mms-sysmlv2@836d904d")); + } + } + + [Test] + public void VerifyCreatedAnsweredOk() + { + var openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + var postProject = openApi.Operations.Single(operation => operation.ToString() == "POST /projects"); + var postQueryResults = openApi.Operations.Single(operation => operation.ToString() == "POST /projects/{projectId}/query-results"); + var getProject = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}"); + var explains = KnownServerDivergences.CreatedAnsweredOk.Explains; + var mismatch = new ContractViolation(ContractViolationKind.SchemaMismatch, "/@type const: Expected \"Error\""); + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(new EndpointCall(postProject, "POST /projects", HttpStatusCode.OK), mismatch), Is.True); + Assert.That(explains(new EndpointCall(postProject, "POST /projects", HttpStatusCode.Created), mismatch), Is.False); + Assert.That(explains(new EndpointCall(postQueryResults, "POST /projects/p/query-results", HttpStatusCode.OK), mismatch), Is.False); + Assert.That(explains(new EndpointCall(getProject, "GET /projects/p", HttpStatusCode.OK), mismatch), Is.False); + Assert.That(explains(new EndpointCall(null, "POST /unknown", HttpStatusCode.OK), mismatch), Is.False); + } + } + + [Test] + public void VerifyDatatypeIdNotUri() + { + var openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + var getDatatype = openApi.Operations.Single(operation => operation.ToString() == "GET /meta/datatypes/{datatypeId}"); + var getProject = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}"); + var explains = KnownServerDivergences.DatatypeIdNotUri.Explains; + var idNotUri = new ContractViolation(ContractViolationKind.SchemaMismatch, "/$id format: Value does not match format \"uri\""); + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(new EndpointCall(getDatatype, "GET /meta/datatypes/Project", HttpStatusCode.OK), idNotUri), Is.True); + Assert.That(explains(new EndpointCall(getDatatype, "GET /meta/datatypes/Project", HttpStatusCode.OK), new ContractViolation(ContractViolationKind.SchemaMismatch, "/type const: Expected \"object\"")), Is.False); + Assert.That(explains(new EndpointCall(getProject, "GET /projects/p", HttpStatusCode.OK), idNotUri), Is.False); + } + } + + [Test] + public void VerifyElementsWithoutDerivedProperties() + { + var explains = KnownServerDivergences.ElementsWithoutDerivedProperties.Explains; + var call = Conforming with { StatusCode = HttpStatusCode.OK }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(call, Missing("/", "\"owner\",\"qualifiedName\"")), Is.True); + Assert.That(explains(call, Missing("/3/payload", "\"documentation\"")), Is.True); + Assert.That(explains(call, Missing("/", "\"owner\",\"declaredName\"")), Is.False); + Assert.That(explains(call, Missing("/", "\"alias\"")), Is.False); + Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/ additionalProperties: [\"owner\"]")), Is.False); + Assert.That(explains(call, new ContractViolation(ContractViolationKind.InvalidParameter, "/ required: Required properties [\"owner\"] are not present")), Is.False); + } + } + + [Test] + public void VerifyErrorWithoutErrorBody() + { + var explains = KnownServerDivergences.ErrorWithoutErrorBody.Explains; + var forbidden = Conforming with { StatusCode = HttpStatusCode.Forbidden }; + var success = Conforming with { StatusCode = HttpStatusCode.OK }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(Conforming, new ContractViolation(ContractViolationKind.UnexpectedBody, "no body")), Is.True); + Assert.That(explains(forbidden, new ContractViolation(ContractViolationKind.UndeclaredMediaType, "text/plain")), Is.True); + Assert.That(explains(Conforming, new ContractViolation(ContractViolationKind.SchemaMismatch, "an Error without description")), Is.False); + Assert.That(explains(success, new ContractViolation(ContractViolationKind.UnexpectedBody, "no body")), Is.False); + Assert.That(KnownServerDivergences.UnknownResourceNotFound.Explains, Is.Null); + } + } + + [Test] + public async Task VerifyExpectNotFoundAsync() + { + var notFound = KnownServerDivergences.UnknownResourceNotFound; + var accepted = KnownServerDivergences.UnknownResourceAccepted; + + using (Assert.EnterMultipleScope()) + { + Assert.That(await Outcome(Answer(HttpStatusCode.NotFound), null, Conforming), Is.Empty); + Assert.That(await Outcome(Answer(HttpStatusCode.NotFound, withError: false), null, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(await Outcome(Answer(HttpStatusCode.NotFound, withError: false), null, Breaking), Is.Empty); + Assert.That(await Outcome(Answer(HttpStatusCode.NotFound, withError: false), null, null), Is.Empty); + Assert.That(await Outcome(Answer(HttpStatusCode.Forbidden), null, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(await Outcome(Succeed, null, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + + Assert.That(await Outcome(Answer(HttpStatusCode.Forbidden), notFound, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(await Outcome(Answer(HttpStatusCode.NotFound), notFound, Conforming), Is.Empty); + Assert.That(await Outcome(Answer(HttpStatusCode.InternalServerError), notFound, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(await Outcome(Succeed, notFound, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + + Assert.That(await Outcome(Succeed, accepted, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(await Outcome(Answer(HttpStatusCode.NotFound), accepted, Conforming), Is.Empty); + Assert.That(await Outcome(Answer(HttpStatusCode.Forbidden), accepted, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + } + + var warning = await IsolatedAssertions.RunAsync(() => KnownServerDivergences.ExpectNotFoundAsync(Answer(HttpStatusCode.Forbidden), () => Conforming, notFound, "the call")); + var lostError = await IsolatedAssertions.RunAsync(() => KnownServerDivergences.ExpectNotFoundAsync(Answer(HttpStatusCode.NotFound, withError: false), () => Conforming, null, "the call")); + + using (Assert.EnterMultipleScope()) + { + Assert.That(warning[0].Message, Does.Contain("the call answered 403 Forbidden").And.Contain(notFound.Summary)); + Assert.That(lostError[0].Message, Does.Contain("the call: the 404 body conforms to the OpenAPI document, but the client read no Error from it")); + } + + await Assert.ThatAsync(() => KnownServerDivergences.ExpectNotFoundAsync(() => throw new InvalidOperationException("a client defect"), () => Conforming, notFound), Throws.InvalidOperationException); + } + + [Test] + public void VerifyRecordsWithoutRequiredProperties() + { + var explains = KnownServerDivergences.RecordsWithoutRequiredProperties.Explains; + var call = Conforming with { StatusCode = HttpStatusCode.OK }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(call, Missing("/", "\"alias\",\"deleted\",\"description\"")), Is.True); + Assert.That(explains(call, Missing("/0/identity", "\"alias\",\"name\"")), Is.True); + Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/0/previousCommit type: Value is \"null\" but should be \"array\"")), Is.True); + Assert.That(explains(call, Missing("/", "\"alias\",\"created\"")), Is.False); + Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/previousCommit type: Value is \"string\" but should be \"array\"")), Is.False); + } + } + + [Test] + public async Task VerifyReport() + { + var divergence = new ServerDivergence("the summary", "the reference"); + + var results = await IsolatedAssertions.RunAsync(() => + { + KnownServerDivergences.Report(divergence, "the detail"); + return Task.CompletedTask; + }); + + using (Assert.EnterMultipleScope()) + { + Assert.That(results, Has.Count.EqualTo(1)); + Assert.That(results[0].Status, Is.EqualTo(AssertionStatus.Warning)); + Assert.That(results[0].Message, Does.Contain("the summary").And.Contain("the reference").And.Contain("the detail")); + } + } + + private static Func Answer(HttpStatusCode statusCode, bool withError = true) => + () => throw new PsmApiException(statusCode, withError ? new Error { Description = "unknown" } : null); + + private static async Task> Outcome(Func call, ServerDivergence tolerated, EndpointCall lastCall) + { + var results = await IsolatedAssertions.RunAsync(() => KnownServerDivergences.ExpectNotFoundAsync(call, () => lastCall, tolerated)); + + return results.Select(result => result.Status).ToList(); + } + + private static ContractViolation Missing(string location, string names) => new(ContractViolationKind.SchemaMismatch, $"{location} required: Required properties [{names}] are not present"); + + private static Task Succeed() => Task.CompletedTask; + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs new file mode 100644 index 000000000..88dc9cc89 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs @@ -0,0 +1,90 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.Linq; + + using NUnit.Framework; + + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Dal; + + using SySML2.NET.REST.Tests.Helpers; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + + [TestFixture] + public class ModelBuilderTestFixture + { + [Test] + public void VerifyCreate() + { + var builder = new ModelBuilder("first"); + var package = builder.Create("Package", PackageExtensions.ToDto); + var other = new ModelBuilder("second").Create("Package", PackageExtensions.ToDto); + + using (Assert.EnterMultipleScope()) + { + Assert.That(package.Id, Is.EqualTo(DeterministicGuid.Create("first/Package"))); + Assert.That(package.ElementId, Is.EqualTo(package.Id.ToString())); + Assert.That(other.Id, Is.Not.EqualTo(package.Id)); + Assert.That(() => builder.Create("Package", PackageExtensions.ToDto), Throws.ArgumentException); + } + } + + [Test] + public void VerifyToDtos() + { + var builder = new ModelBuilder("scope"); + var package = builder.Create("Package", PackageExtensions.ToDto); + package.DeclaredName = "Package"; + + var dtos = builder.ToDtos(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos, Has.Count.EqualTo(1)); + Assert.That(dtos[0], Is.TypeOf()); + Assert.That(dtos[0].Id, Is.EqualTo(package.Id)); + Assert.That(dtos[0].DeclaredName, Is.EqualTo("Package")); + } + + var failing = new ModelBuilder("scope"); + failing.Create("Broken", (_, _) => throw new NotSupportedException("no conversion")); + + Assert.That(failing.ToDtos, Throws.InvalidOperationException + .With.Message.Contains("scope/Broken").And.Message.Contains(nameof(Package)) + .And.InnerException.TypeOf()); + } + + [Test] + public void VerifyToCommitRequest() + { + var builder = new ModelBuilder("scope"); + builder.Create("First", PackageExtensions.ToDto); + builder.Create("Second", PackageExtensions.ToDto); + var dtos = builder.ToDtos(); + + var request = ModelBuilder.ToCommitRequest(dtos, "description"); + var empty = ModelBuilder.ToCommitRequest(Enumerable.Empty(), "empty"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(request.Description, Is.EqualTo("description")); + Assert.That(request.Change, Has.Count.EqualTo(2)); + Assert.That(request.Change.Select(change => change.Identity.Id), Is.EqualTo(dtos.Select(dto => dto.Id))); + Assert.That(request.Change[0].Payload, Is.SameAs(dtos[0])); + Assert.That(request.Change[1].Payload, Is.SameAs(dtos[1])); + Assert.That(empty.Change, Is.Empty); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs new file mode 100644 index 000000000..f2e44511d --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System.IO; + using System.Linq; + using System.Text; + using System.Text.Json; + + using NUnit.Framework; + + using SysML2.NET.Core.DTO.Kernel.Packages; + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.Serializer.Json; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + [TestFixture] + public class RootModelTestFixture + { + [Test] + public void VerifyRootModel() + { + var model = new RootModel(); + + var dtos = model.Builder.ToDtos(); + + var owningMemberships = dtos.OfType().ToList(); + var commitRequest = ModelBuilder.ToCommitRequest(dtos, "root model"); + + using var stream = new MemoryStream(); + new Serializer().SerializeRequest(commitRequest, SerializationModeKind.JSON, false, stream, new JsonWriterOptions()); + var json = Encoding.UTF8.GetString(stream.ToArray()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(dtos.OfType().Select(package => package.DeclaredName), Is.EquivalentTo(["CoverageModel", "Nested"])); + Assert.That(owningMemberships, Has.Count.EqualTo(10)); + Assert.That(owningMemberships.Select(membership => ((IMembership)membership).MemberElement), Is.EquivalentTo(owningMemberships.Select(membership => membership.OwnedRelatedElement[0]))); + Assert.That(commitRequest.Change, Has.Count.EqualTo(dtos.Count)); + Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); + } + + Assert.That(new RootModel().Builder.ToDtos().Select(dto => dto.Id), Is.EqualTo(dtos.Select(dto => dto.Id))); + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiConformanceTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiConformanceTestFixture.cs new file mode 100644 index 000000000..4c5a8101a --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiConformanceTestFixture.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading.Tasks; + + using NUnit.Framework; + using NUnit.Framework.Interfaces; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class OpenApiConformanceTestFixture + { + [Test] + public async Task VerifyVerify() + { + var divergence = new ServerDivergence("no Error body", "the reference", (call, violation) => call.StatusCode == HttpStatusCode.NotFound && violation.Kind == ContractViolationKind.UnexpectedBody); + var getProjects = new OpenApiOperation(HttpMethod.Get, "/projects", [], null, false, new Dictionary()); + var getProject = new OpenApiOperation(HttpMethod.Get, "/projects/{projectId}", [], null, false, new Dictionary()); + var conforming = new EndpointCall(getProjects, "GET /projects", HttpStatusCode.OK); + var badRequest = conforming with { RequestLine = "GET /projects?page%5Bsize%5D=ten", RequestViolations = [new ContractViolation(ContractViolationKind.InvalidParameter, "page[size]=ten")] }; + var explained = new EndpointCall(getProject, "GET /projects/p", HttpStatusCode.NotFound) { ResponseViolations = [new ContractViolation(ContractViolationKind.UnexpectedBody, "no body")] }; + var alsoExplained = explained with { RequestLine = "GET /projects/q" }; + var unexplained = conforming with { ResponseViolations = [new ContractViolation(ContractViolationKind.SchemaMismatch, "/0 required: alias"), new ContractViolation(ContractViolationKind.SchemaMismatch, "/1 required: alias")] }; + + var none = await Run([], divergence); + var clean = await Run([conforming], divergence); + var clientDefect = await Run([conforming, badRequest], divergence); + var known = await Run([explained, alsoExplained], divergence); + var unknown = await Run([unexplained], divergence); + var mixed = await Run([badRequest, explained, unexplained], divergence); + var withoutDivergences = await Run([explained]); + + using (Assert.EnterMultipleScope()) + { + Assert.That(none, Is.Empty); + Assert.That(clean, Is.Empty); + Assert.That(clientDefect.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(clientDefect[0].Message, Does.Contain("requests of the client").And.Contain("GET /projects answered 200: InvalidParameter: page[size]=ten (1x, e.g. GET /projects?page%5Bsize%5D=ten)")); + Assert.That(known.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(known[0].Message, Does.Contain("no Error body").And.Contain("GET /projects/{projectId} answered 404: UnexpectedBody: no body (2x, e.g. GET /projects/p)")); + Assert.That(unknown.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(unknown[0].Message, Does.Contain("match no known divergence").And.Contain("GET /projects answered 200: SchemaMismatch: /* required: alias (2x, e.g. GET /projects)")); + Assert.That(mixed.Select(result => result.Status), Is.EquivalentTo((AssertionStatus[])[AssertionStatus.Warning, AssertionStatus.Failed, AssertionStatus.Failed])); + Assert.That(withoutDivergences.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + } + } + + private static Task> Run(EndpointCall[] calls, params ServerDivergence[] divergences) + { + return IsolatedAssertions.RunAsync(() => + { + OpenApiConformance.Verify(calls, divergences); + return Task.CompletedTask; + }); + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs new file mode 100644 index 000000000..8b2b64a09 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs @@ -0,0 +1,76 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System.Collections.Generic; + using System.Linq; + + using Json.Schema; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class OpenApiContentTestFixture + { + private const string MetaclassSchema = """ + { + "anyOf": [ + { "type": "object", "properties": { "@type": { "const": "A" }, "a": { "type": "string" } }, "required": ["@type", "a"] }, + { "type": "object", "properties": { "@type": { "const": "B" }, "b": { "type": "string" }, "id": { "type": "string", "format": "uuid" }, "note": { "oneOf": [{ "type": "string" }, { "type": "null" }] } }, "required": ["@type", "b"] } + ] + } + """; + + [Test] + public void VerifyCheck() + { + Assert.That(() => new OpenApiContent(null), Throws.ArgumentNullException); + + var none = new OpenApiContent(new Dictionary()); + var anything = new OpenApiContent(new Dictionary { ["*/*"] = JsonSchema.FromText("{\"type\":\"null\"}") }); + var anyApplication = new OpenApiContent(new Dictionary { ["application/*"] = JsonSchema.FromText("true") }); + var metaclasses = new OpenApiContent(new Dictionary { ["application/json"] = JsonSchema.FromText(MetaclassSchema) }); + + using (Assert.EnterMultipleScope()) + { + Assert.That(none.Check(null, string.Empty), Is.Empty); + Assert.That(Kinds(none.Check("application/json", "{}")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UnexpectedBody])); + Assert.That(anything.Check(null, string.Empty), Is.Empty); + Assert.That(anything.Check("text/plain", "ignored"), Is.Empty); + Assert.That(anyApplication.Check("application/xml", ""), Is.Empty); + Assert.That(Kinds(anyApplication.Check("text/plain", "a")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UndeclaredMediaType])); + Assert.That(Kinds(metaclasses.Check(null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UnexpectedBody])); + Assert.That(Kinds(metaclasses.Check("application/ld+json", "{}")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UndeclaredMediaType])); + Assert.That(Kinds(metaclasses.Check("application/json", "{")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.InvalidJson])); + Assert.That(metaclasses.Check("APPLICATION/JSON", "{\"@type\":\"A\",\"a\":\"x\"}"), Is.Empty); + Assert.That(metaclasses.Check("application/json", "{\"@type\":\"B\",\"b\":\"x\",\"note\":null,\"id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\"}"), Is.Empty); + } + + var missingInB = metaclasses.Check("application/json", "{\"@type\":\"B\"}"); + var unknownType = metaclasses.Check("application/json", "{\"@type\":\"C\"}"); + var badNote = metaclasses.Check("application/json", "{\"@type\":\"B\",\"b\":\"x\",\"note\":5}"); + var badId = metaclasses.Check("application/json", "{\"@type\":\"B\",\"b\":\"x\",\"id\":\"nope\"}"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(Kinds(missingInB), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.SchemaMismatch])); + Assert.That(missingInB[0].Message, Does.Contain("\"b\"").And.Not.Contain("\"a\"")); + Assert.That(unknownType[0].Message, Does.Contain("@type const")); + Assert.That(badNote[0].Message, Does.Contain("/note")); + Assert.That(badId[0].Message, Does.Contain("/id format")); + Assert.That(missingInB[0].ToString(), Does.StartWith("SchemaMismatch: ")); + } + } + + private static IReadOnlyList Kinds(IReadOnlyList violations) => violations.Select(violation => violation.Kind).ToList(); + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs new file mode 100644 index 000000000..d68cf96f1 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs @@ -0,0 +1,141 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class OpenApiDocumentTestFixture + { + private const string SmallDocument = """ + { + "openapi": "3.1.0", + "paths": { + "/a/{x}": { + "get": { + "parameters": [{ "$ref": "#/components/parameters/x" }], + "responses": { + "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Thing" } } } }, + "404": { "$ref": "#/components/responses/404" } + } + } + }, + "/a/b": { "get": {} } + }, + "components": { + "parameters": { "x": { "name": "x", "in": "path", "required": true, "schema": { "type": "string" } } }, + "responses": { "404": { "content": { "application/json": { "schema": { "$ref": "relative/Name" } } } } }, + "schemas": { + "Thing": { + "$id": "relative/Thing", + "type": "object", + "properties": { "name": { "$ref": "#/components/schemas/Name" }, "other": { "$ref": "relative/Name" } }, + "required": ["name"], + "additionalProperties": false + }, + "Name": { "$id": "relative/Name", "type": "string" } + } + } + } + """; + + private OpenApiDocument openApi; + + private string smallDocumentPath; + + [SetUp] + public void SetUp() + { + this.openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + this.smallDocumentPath = Path.Combine(TestContext.CurrentContext.WorkDirectory, $"{Guid.NewGuid()}.json"); + } + + [TearDown] + public void TearDown() + { + File.Delete(this.smallDocumentPath); + } + + [Test] + public void VerifyLoad() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(this.openApi.Operations, Has.Count.EqualTo(35)); + Assert.That(this.openApi.Operations.Select(operation => operation.ToString()), Is.Unique); + Assert.That(this.openApi.Operations.Single(operation => operation.ToString() == "GET /projects").DeclaresClientError, Is.False); + Assert.That(this.openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}").DeclaresClientError, Is.True); + Assert.That(this.openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}").Responses["404"].SchemasByMediaType.Keys, Is.EqualTo((string[])["application/json"])); + Assert.That(this.openApi.Operations.Single(operation => operation.ToString() == "DELETE /projects/{projectId}").Responses["204"].SchemasByMediaType.Keys, Is.EqualTo((string[])["*/*"])); + } + + File.WriteAllText(this.smallDocumentPath, SmallDocument); + + var small = OpenApiDocument.Load(this.smallDocumentPath); + var thing = small.Operations.Single(operation => operation.PathTemplate == "/a/{x}"); + var bare = small.Operations.Single(operation => operation.PathTemplate == "/a/b"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(small.Operations, Has.Count.EqualTo(2)); + Assert.That(thing.Parameters.Select(parameter => parameter.Name), Is.EqualTo((string[])["x"])); + Assert.That(thing.CheckResponse(HttpStatusCode.OK, "application/json", "{\"name\":\"n\",\"other\":\"o\"}"), Is.Empty); + Assert.That(thing.CheckResponse(HttpStatusCode.OK, "application/json", "{\"name\":5}").Select(violation => violation.Kind), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.SchemaMismatch])); + Assert.That(thing.CheckResponse(HttpStatusCode.OK, "application/json", "{\"name\":\"n\",\"other\":5}").Select(violation => violation.Kind), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.SchemaMismatch])); + Assert.That(thing.CheckResponse(HttpStatusCode.NotFound, "application/json", "\"missing\""), Is.Empty); + Assert.That(thing.DeclaresClientError, Is.True); + Assert.That(bare.Responses, Is.Empty); + Assert.That(bare.DeclaresClientError, Is.False); + Assert.That(bare.CheckResponse(HttpStatusCode.OK, null, string.Empty).Select(violation => violation.Kind), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UndeclaredStatus])); + } + + File.WriteAllText(this.smallDocumentPath, SmallDocument.Replace("#/components/responses/404", "#/components/responses/410")); + + Assert.That(() => OpenApiDocument.Load(this.smallDocumentPath), Throws.InvalidOperationException.With.Message.Contains("#/components/responses/410")); + } + + [Test] + public void VerifyMatch() + { + var commitId = "5d2c1a3e-0000-4000-8000-000000000001"; + + using (Assert.EnterMultipleScope()) + { + Assert.That(this.openApi.Match(HttpMethod.Get, "/projects")?.PathTemplate, Is.EqualTo("/projects")); + Assert.That(this.openApi.Match(HttpMethod.Post, "/projects")?.Method, Is.EqualTo(HttpMethod.Post)); + Assert.That(this.openApi.Match(HttpMethod.Get, $"/projects/p/commits/{commitId}/elements/e")?.PathTemplate, Is.EqualTo("/projects/{projectId}/commits/{commitId}/elements/{elementId}")); + Assert.That(this.openApi.Match(HttpMethod.Get, $"/projects/p/commits/{commitId}/elements/e/relationships")?.PathTemplate, Is.EqualTo("/projects/{projectId}/commits/{commitId}/elements/{relatedElementId}/relationships")); + Assert.That(this.openApi.Match(HttpMethod.Get, $"/projects/p/commits/{commitId}/elements/e/projectUsage")?.PathTemplate, Is.EqualTo("/projects/{projectId}/commits/{commitId}/elements/{elementId}/projectUsage")); + Assert.That(this.openApi.Match(HttpMethod.Get, $"/projects/p/commits/{commitId}/diff")?.PathTemplate, Is.EqualTo("/projects/{projectId}/commits/{compareCommitId}/diff")); + Assert.That(this.openApi.Match(HttpMethod.Patch, "/projects"), Is.Null); + Assert.That(this.openApi.Match(HttpMethod.Get, "/projects/p/unknown"), Is.Null); + Assert.That(this.openApi.Match(HttpMethod.Get, "/"), Is.Null); + } + + File.WriteAllText(this.smallDocumentPath, SmallDocument); + + var small = OpenApiDocument.Load(this.smallDocumentPath); + + using (Assert.EnterMultipleScope()) + { + Assert.That(small.Match(HttpMethod.Get, "/a/b")?.PathTemplate, Is.EqualTo("/a/b")); + Assert.That(small.Match(HttpMethod.Get, "/a/c")?.PathTemplate, Is.EqualTo("/a/{x}")); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs new file mode 100644 index 000000000..ea3f69d77 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs @@ -0,0 +1,144 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Text.Json; + + using Json.Schema; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class OpenApiOperationTestFixture + { + private const string ErrorBody = "{\"@type\":\"Error\",\"description\":\"Resource not found\"}"; + + private const string DeleteCommitBody = "{\"@type\":\"Commit\",\"change\":[{\"@type\":\"DataVersion\",\"identity\":{\"@id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\"},\"payload\":null}]}"; + + private string documentPath; + + private OpenApiDocument openApi; + + [OneTimeSetUp] + public void OneTimeSetUp() + { + this.documentPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json"); + this.openApi = OpenApiDocument.Load(this.documentPath); + } + + [Test] + public void VerifyCheckRequest() + { + var getElements = this.Operation("GET /projects/{projectId}/commits/{commitId}/elements"); + var getRelationships = this.Operation("GET /projects/{projectId}/commits/{commitId}/elements/{relatedElementId}/relationships"); + var postProject = this.Operation("POST /projects"); + var postCommit = this.Operation("POST /projects/{projectId}/commits"); + var merge = this.Operation("POST /projects/{projectId}/branches/{targetBranchId}/merge"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(getElements.CheckRequest("?page%5Bsize%5D=10&page%5Bafter%5D=abc&excludeUsed=true", null, string.Empty), Is.Empty); + Assert.That(getElements.CheckRequest(null, null, string.Empty), Is.Empty); + Assert.That(Kinds(getElements.CheckRequest("page%5Bsize%5D=ten", null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.InvalidParameter])); + Assert.That(Kinds(getElements.CheckRequest("?excludeUsed=True", null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.InvalidParameter])); + Assert.That(Kinds(getElements.CheckRequest("?page%5Bnumber%5D=2", null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UndeclaredParameter])); + Assert.That(Kinds(getElements.CheckRequest(string.Empty, "application/json", "{}")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UnexpectedBody])); + Assert.That(getRelationships.CheckRequest("?direction=in", null, string.Empty), Is.Empty); + Assert.That(Kinds(getRelationships.CheckRequest("?direction=sideways", null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.InvalidParameter])); + Assert.That(postProject.CheckRequest(string.Empty, "application/json", this.Example("ProjectRequest")), Is.Empty); + Assert.That(postProject.CheckRequest(string.Empty, null, string.Empty), Is.Empty); + Assert.That(Kinds(postProject.CheckRequest(string.Empty, "application/json", "{\"@type\":\"Project\",\"name\":5}")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.SchemaMismatch])); + Assert.That(Kinds(postProject.CheckRequest(string.Empty, "text/plain", "name")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UndeclaredMediaType])); + Assert.That(postCommit.CheckRequest("?branchId=3fa85f64-5717-4562-b3fc-2c963f66afa6", "application/json", DeleteCommitBody), Is.Empty); + Assert.That(Kinds(postCommit.CheckRequest("?branchId=main", "application/json", DeleteCommitBody)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.InvalidParameter])); + Assert.That(Kinds(postCommit.CheckRequest(string.Empty, null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UnexpectedBody])); + Assert.That(Kinds(merge.CheckRequest(string.Empty, null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.MissingParameter])); + Assert.That(merge.CheckRequest("?sourceCommitId=3fa85f64-5717-4562-b3fc-2c963f66afa6,3fa85f64-5717-4562-b3fc-2c963f66afa7", null, string.Empty), Is.Empty); + } + } + + [Test] + public void VerifyCheckResponse() + { + var getProject = this.Operation("GET /projects/{projectId}"); + var deleteProject = this.Operation("DELETE /projects/{projectId}"); + var json = new Dictionary { ["application/json"] = JsonSchema.FromText("{\"type\":\"object\"}") }; + var withoutDefault = new OpenApiOperation(HttpMethod.Get, "/things", [], null, false, new Dictionary { ["200"] = new(json), ["4XX"] = new(json) }); + + using (Assert.EnterMultipleScope()) + { + Assert.That(getProject.CheckResponse(HttpStatusCode.OK, "application/json", this.Example("Project")), Is.Empty); + Assert.That(Kinds(getProject.CheckResponse(HttpStatusCode.OK, "application/json", "{\"@type\":\"Project\"}")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.SchemaMismatch])); + Assert.That(getProject.CheckResponse(HttpStatusCode.NotFound, "application/json", ErrorBody), Is.Empty); + Assert.That(getProject.CheckResponse(HttpStatusCode.Forbidden, "application/json", ErrorBody), Is.Empty); + Assert.That(Kinds(getProject.CheckResponse(HttpStatusCode.NotFound, null, string.Empty)), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UnexpectedBody])); + Assert.That(Kinds(getProject.CheckResponse(HttpStatusCode.NotFound, "text/plain", "org.openmbee.flexo.mms.Http404Exception")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UndeclaredMediaType])); + Assert.That(Kinds(getProject.CheckResponse(HttpStatusCode.NotFound, "application/json", "not json")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.InvalidJson])); + Assert.That(deleteProject.CheckResponse(HttpStatusCode.NoContent, null, string.Empty), Is.Empty); + Assert.That(withoutDefault.CheckResponse(HttpStatusCode.NotFound, "application/json", "{}"), Is.Empty); + Assert.That(Kinds(withoutDefault.CheckResponse(HttpStatusCode.InternalServerError, "application/json", "{}")), Is.EqualTo((ContractViolationKind[])[ContractViolationKind.UndeclaredStatus])); + } + } + + [Test] + public void VerifyMatches() + { + var getElement = this.Operation("GET /projects/{projectId}/commits/{commitId}/elements/{elementId}"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(getElement.Matches(["projects", "p", "commits", "c", "elements", "e"]), Is.True); + Assert.That(getElement.Matches(["projects", "p", "commits", "c", "roots", "e"]), Is.False); + Assert.That(getElement.Matches(["projects", "p", "commits", "c", "elements"]), Is.False); + Assert.That(getElement.Matches(["Projects", "p", "commits", "c", "elements", "e"]), Is.False); + } + } + + [Test] + public void VerifyOpenApiOperation() + { + Assert.That(() => new OpenApiOperation(null, "/things", [], null, false, new Dictionary()), Throws.ArgumentNullException); + + var getProject = this.Operation("GET /projects/{projectId}"); + var postBranch = this.Operation("POST /projects/{projectId}/branches"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(getProject.ToString(), Is.EqualTo("GET /projects/{projectId}")); + Assert.That(getProject.LiteralSegmentCount, Is.EqualTo(1)); + Assert.That(getProject.DeclaresClientError, Is.True); + Assert.That(getProject.RequestBody, Is.Null); + Assert.That(getProject.Parameters.Select(parameter => (parameter.Name, parameter.Location, parameter.IsRequired)), Is.EqualTo(((string, string, bool)[])[("projectId", "path", true)])); + Assert.That(postBranch.DeclaresClientError, Is.False); + Assert.That(postBranch.IsRequestBodyRequired, Is.True); + Assert.That(postBranch.RequestBody?.SchemasByMediaType.Keys, Is.EqualTo((string[])["application/json"])); + } + } + + private static IReadOnlyList Kinds(IReadOnlyList violations) => violations.Select(violation => violation.Kind).ToList(); + + private string Example(string name) + { + using var document = JsonDocument.Parse(File.ReadAllText(this.documentPath)); + + return document.RootElement.GetProperty("components").GetProperty("examples").GetProperty(name).GetProperty("value").GetRawText(); + } + + private OpenApiOperation Operation(string text) => this.openApi.Operations.Single(operation => operation.ToString() == text); + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiParameterTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiParameterTestFixture.cs new file mode 100644 index 000000000..e23e12ba5 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiParameterTestFixture.cs @@ -0,0 +1,77 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using Json.Schema; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + [TestFixture] + public class OpenApiParameterTestFixture + { + [Test] + public void VerifyCheck() + { + var pageSize = Parameter("integer", "{\"type\":\"integer\"}"); + var ratio = Parameter("number", "{\"type\":\"number\"}"); + var excludeUsed = Parameter("boolean", "{\"type\":\"boolean\"}"); + var sources = Parameter("array", "{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}}"); + var direction = Parameter("string", "{\"type\":\"string\",\"enum\":[\"in\",\"out\",\"both\"]}"); + var untyped = Parameter(null, "{}"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(pageSize.Check("10"), Is.Empty); + Assert.That(pageSize.Check("-1"), Is.Empty); + Assert.That(pageSize.Check("ten"), Has.Count.EqualTo(1)); + Assert.That(pageSize.Check("1.5"), Has.Count.EqualTo(1)); + Assert.That(ratio.Check("1.5"), Is.Empty); + Assert.That(ratio.Check("half"), Has.Count.EqualTo(1)); + Assert.That(excludeUsed.Check("true"), Is.Empty); + Assert.That(excludeUsed.Check("True"), Has.Count.EqualTo(1)); + Assert.That(sources.Check("3fa85f64-5717-4562-b3fc-2c963f66afa6,3fa85f64-5717-4562-b3fc-2c963f66afa7"), Is.Empty); + Assert.That(sources.Check("3fa85f64-5717-4562-b3fc-2c963f66afa6,nope"), Has.Count.EqualTo(1)); + Assert.That(direction.Check("out"), Is.Empty); + Assert.That(direction.Check("sideways"), Has.Count.EqualTo(1)); + Assert.That(untyped.Check("anything"), Is.Empty); + Assert.That(pageSize.Check("ten")[0].Kind, Is.EqualTo(ContractViolationKind.InvalidParameter)); + Assert.That(pageSize.Check("ten")[0].Message, Does.Contain("page[size]=ten").And.Contain("integer")); + } + } + + [Test] + public void VerifyOpenApiParameter() + { + var schema = JsonSchema.FromText("{}"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(() => new OpenApiParameter(null, "query", false, null, schema), Throws.ArgumentNullException); + Assert.That(() => new OpenApiParameter("name", null, false, null, schema), Throws.ArgumentNullException); + Assert.That(() => new OpenApiParameter("name", "query", false, null, null), Throws.ArgumentNullException); + } + + var parameter = new OpenApiParameter("projectId", "path", true, "string", schema); + + using (Assert.EnterMultipleScope()) + { + Assert.That(parameter.Name, Is.EqualTo("projectId")); + Assert.That(parameter.Location, Is.EqualTo("path")); + Assert.That(parameter.IsRequired, Is.True); + Assert.That(parameter.Type, Is.EqualTo("string")); + Assert.That(parameter.Schema, Is.SameAs(schema)); + } + } + + private static OpenApiParameter Parameter(string type, string schema) => new("page[size]", "query", false, type, JsonSchema.FromText(schema)); + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs new file mode 100644 index 000000000..03c2057f9 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs @@ -0,0 +1,347 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using System.Threading; + using System.Threading.Tasks; + + using Moq; + + using NUnit.Framework; + using NUnit.Framework.Interfaces; + + using SySML2.NET.REST; + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + using SysML2.NET.Common; + using SysML2.NET.Core.DTO.Kernel.Packages; + using SysML2.NET.Core.DTO.Root.Dependencies; + using SysML2.NET.Core.DTO.Root.Elements; + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.PSM; + using SysML2.NET.PSM.DTO; + + using Direction = SysML2.NET.PSM.Enumerations.Direction; + + [TestFixture] + public class ReadBackAssertionsTestFixture + { + private static readonly MethodInfo CloneMethod = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic); + + private readonly Guid projectId = Guid.NewGuid(); + + private readonly Guid commitId = Guid.NewGuid(); + + private Mock client; + + private ScenarioState state; + + private ReadBackAssertions assertions; + + [SetUp] + public void SetUp() + { + this.client = new Mock(); + this.state = new ScenarioState { ProjectId = this.projectId }; + this.assertions = new ReadBackAssertions(this.client.Object, this.state); + } + + [Test] + public async Task VerifyReadAllPagesAsync() + { + var requests = new List(); + + var (records, pages) = await ReadBackAssertions.ReadAllPagesAsync(parameters => + { + requests.Add(parameters); + var index = requests.Count; + + return Task.FromResult(new PagedResult + { + Records = [index * 10, (index * 10) + 1], + Next = index < 3 ? new Page($"cursor-{index}") : null + }); + }); + + var (single, singlePages) = await ReadBackAssertions.ReadAllPagesAsync(_ => Task.FromResult(new PagedResult { Records = [7] })); + + using (Assert.EnterMultipleScope()) + { + Assert.That(records, Is.EqualTo((int[])[10, 11, 20, 21, 30, 31])); + Assert.That(pages, Is.EqualTo(3)); + Assert.That(requests[0].PageAfter, Is.Null); + Assert.That(requests[1].PageAfter?.Token, Is.EqualTo("cursor-1")); + Assert.That(requests[2].PageAfter?.Token, Is.EqualTo("cursor-2")); + Assert.That(requests.TrueForAll(parameters => parameters.PageSize == 10), Is.True); + Assert.That(single, Is.EqualTo((int[])[7])); + Assert.That(singlePages, Is.EqualTo(1)); + } + + var counter = 0; + + await Assert.ThatAsync(() => ReadBackAssertions.ReadAllPagesAsync(_ => Task.FromResult(new PagedResult { Records = [], Next = new Page("same") })), Throws.InvalidOperationException.With.Message.Contains("repeated")); + await Assert.ThatAsync(() => ReadBackAssertions.ReadAllPagesAsync(_ => Task.FromResult(new PagedResult { Records = [], Next = new Page($"cursor-{++counter}") })), Throws.InvalidOperationException.With.Message.Contains("did not end")); + } + + [Test] + public async Task VerifyVerifyCommitAsync() + { + var branchId = Guid.NewGuid(); + var previousId = Guid.NewGuid(); + + List changed = [.. Enumerable.Range(0, 25).Select(index => new Package { Id = Guid.NewGuid(), DeclaredName = $"P{index}" })]; + var changes = changed.Select(element => new DataVersion { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = element.Id }, Payload = Clone(element) }).ToList(); + var commit = new Commit { Id = this.commitId, OwningProject = this.projectId }; + List commits = [commit]; + DataVersion changeById = null; + Guid? head = this.commitId; + + this.client.Setup(api => api.GetCommitByProjectAndIdAsync(this.projectId, this.commitId, It.IsAny())).ReturnsAsync(() => commit); + this.client.Setup(api => api.GetCommitsByProjectAsync(this.projectId, It.IsAny(), It.IsAny())).Returns((Guid _, QueryParameters parameters, CancellationToken _) => Paged(commits, parameters)); + this.client.Setup(api => api.GetBranchesByProjectAndIdAsync(this.projectId, branchId, It.IsAny())).ReturnsAsync(() => new Branch { Id = branchId, Head = head }); + this.client.Setup(api => api.GetChangesByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).Returns((Guid _, Guid _, QueryParameters parameters, CancellationToken _) => Paged(changes, parameters)); + this.client.Setup(api => api.GetChangeByProjectCommitIdAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).ReturnsAsync((Guid _, Guid _, Guid changeId, CancellationToken _) => changeById ?? changes.Single(change => change.Id == changeId)); + + var firstCommit = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, null, changed)); + + this.client.Verify(api => api.GetChangeByProjectCommitIdAsync(this.projectId, this.commitId, changes[0].Id, It.IsAny()), Times.Once); + + var unexpectedPrevious = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + commit.PreviousCommit = [previousId]; + + var laterCommit = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + head = previousId; + + var headNotMoved = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + head = this.commitId; + commits = []; + + var notListed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + commits = [commit]; + commit.OwningProject = Guid.NewGuid(); + + var otherProject = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + commit.OwningProject = this.projectId; + var renamed = (Package)Clone(changed[3]); + renamed.DeclaredName = "Changed"; + changes[3].Payload = renamed; + var renamedChangeId = changes[3].Id; + + var payloadChanged = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + changes[3].Payload = Clone(changed[3]); + changeById = new DataVersion { Id = changes[0].Id, Identity = new DataIdentity { Id = Guid.NewGuid() }, Payload = changes[0].Payload }; + + var changeByIdOther = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + changeById = null; + changes = changes[..5]; + + var onePage = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed[..5])); + var missingChanges = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + changes = []; + this.client.Invocations.Clear(); + + var noChanges = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, [])); + + using (Assert.EnterMultipleScope()) + { + Assert.That(firstCommit, Is.Empty); + Assert.That(unexpectedPrevious, Has.Count.EqualTo(1)); + Assert.That(laterCommit, Is.Empty); + Assert.That(headNotMoved, Has.Count.EqualTo(1)); + Assert.That(notListed, Has.Count.EqualTo(1)); + Assert.That(otherProject, Has.Count.EqualTo(1)); + Assert.That(payloadChanged, Has.Count.EqualTo(1)); + Assert.That(payloadChanged[0].Message, Does.Contain($"the payload of change {renamedChangeId} differs from what was sent: Element.DeclaredName")); + Assert.That(changeByIdOther, Has.Count.EqualTo(1)); + Assert.That(onePage, Has.Count.EqualTo(1)); + Assert.That(onePage[0].Message, Does.Contain("paging is untested")); + Assert.That(missingChanges, Has.Count.EqualTo(2)); + Assert.That(noChanges, Has.Count.EqualTo(1)); + } + + this.client.Verify(api => api.GetChangeByProjectCommitIdAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Test] + public async Task VerifyVerifyModelAsync() + { + var model = new RootModel(); + var elements = model.Builder.ToDtos(); + var relationships = elements.OfType().ToList(); + var readBack = elements.ToDictionary(element => element.Id, Clone); + var unowned = elements.Where(element => element.owner == null).ToList(); + IReadOnlyList roots = unowned; + IReadOnlyList listed = elements; + var onePage = false; + var dropIncoming = false; + + this.client.Setup(api => api.GetElementByProjectCommitIdAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync((Guid _, Guid _, Guid elementId, bool? _, CancellationToken _) => readBack[elementId]); + + this.client.Setup(api => api.GetElementsByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Guid _, Guid _, bool? _, QueryParameters parameters, CancellationToken _) => Paged(listed, onePage ? null : parameters)); + + this.client.Setup(api => api.GetRootsByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Guid _, Guid _, bool? _, QueryParameters parameters, CancellationToken _) => Paged(roots, parameters)); + + this.client.Setup(api => api.GetRelationshipsByProjectCommitRelatedElementAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Guid _, Guid _, Guid subjectId, Direction? direction, bool? _, QueryParameters parameters, CancellationToken _) => + Paged(relationships.Where(relationship => direction switch + { + Direction.@out => relationship.Source.Contains(subjectId), + Direction.@in => !dropIncoming && relationship.Target.Contains(subjectId), + _ => relationship.Source.Contains(subjectId) || relationship.Target.Contains(subjectId) + }).ToList(), parameters)); + + var firstRead = elements.Select(element => readBack[element.Id]).ToList(); + var identical = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var recorded = this.state.ReadBack.ToList(); + + roots = elements; + + var everyElementRoot = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + roots = [.. elements.Where(element => element is not IRelationship { OwningRelatedElement: not null })]; + + var notOwnedRelatedRoots = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + roots = [.. elements.Where(element => element is not IRelationship)]; + + var nonRelationshipRoots = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + roots = [.. unowned.Where(element => element.Id != model.Root.Id)]; + + var rootMissing = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + roots = [.. unowned, new Package { Id = Guid.NewGuid() }]; + + var foreignRoot = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + roots = unowned; + var renamed = (Package)Clone(readBack[model.Nested.Id]); + renamed.DeclaredName = "Changed"; + readBack[model.Nested.Id] = renamed; + + var elementChanged = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + readBack[model.Nested.Id] = new Namespace { Id = model.Nested.Id }; + + var otherMetaclass = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + readBack[model.Nested.Id] = null; + + var nothingRead = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + readBack[model.Nested.Id] = Clone(elements.Single(element => element.Id == model.Nested.Id)); + listed = elements.Skip(1).ToList(); + + var elementNotListed = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + listed = [.. elements, elements[0]]; + + var elementListedTwice = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + listed = elements; + onePage = true; + + var listOnOnePage = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + onePage = false; + dropIncoming = true; + + var incomingLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + dropIncoming = false; + + var unrelatedSubject = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, Guid.NewGuid())); + + var alias = elements.Single(element => element.GetType() == typeof(Membership)); + var lostMember = (Membership)Clone(alias); + lostMember.MemberElement = Guid.Empty; + readBack[alias.Id] = lostMember; + + var memberElementLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + var lostName = (Membership)Clone(alias); + lostName.MemberName = null; + readBack[alias.Id] = lostName; + + var memberNameLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + readBack[alias.Id] = Clone(alias); + var dependency = elements.OfType().Single(); + var emptyClient = (Dependency)Clone(dependency); + emptyClient.Client = [Guid.Empty]; + readBack[dependency.Id] = emptyClient; + + var emptyReference = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(identical, Is.Empty); + Assert.That(recorded.TrueForAll(entry => entry.CommitId == this.commitId), Is.True); + Assert.That(recorded.Select(entry => entry.Data), Is.EqualTo(firstRead.Cast()).Using((actual, expected) => ReferenceEquals(actual, expected))); + Assert.That(unowned, Has.Count.GreaterThan(1), "owned relationships have no owner, so they are roots"); + Assert.That(everyElementRoot.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(notOwnedRelatedRoots.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(notOwnedRelatedRoots[0].Message, Does.Contain(KnownServerDivergences.RootsIgnoreOwningRelationship.Summary)); + Assert.That(nonRelationshipRoots.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(rootMissing.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(foreignRoot.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(elementChanged.Select(result => result.Message), Is.EqualTo((string[])[$"Package {model.Nested.Id} differs from what was sent: Element.DeclaredName"])); + Assert.That(otherMetaclass.Select(result => result.Message), Has.Some.Contains($"Package {model.Nested.Id} was read back as another metaclass")); + Assert.That(nothingRead.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(elementNotListed, Has.Count.EqualTo(1)); + Assert.That(elementListedTwice, Has.Count.EqualTo(1)); + Assert.That(listOnOnePage, Has.Count.EqualTo(1)); + Assert.That(listOnOnePage[0].Message, Does.Contain("the elements did not span several pages, so paging is untested")); + Assert.That(incomingLost, Has.Count.EqualTo(1)); + Assert.That(unrelatedSubject.Select(result => result.Message), Has.Some.Contains("out direction is untested")); + Assert.That(unrelatedSubject.Select(result => result.Message), Has.Some.Contains("in direction is untested")); + Assert.That(memberElementLost.Select(result => result.Message), Has.Some.Contains("lost its memberElement (#424)")); + Assert.That(memberElementLost.Select(result => result.Message), Has.Some.Contains("holds empty references (#424)")); + Assert.That(memberElementLost.Select(result => result.Message), Has.None.Contains("lost its memberName")); + Assert.That(memberNameLost.Select(result => result.Message), Has.Some.Contains("lost its memberName (#424)")); + Assert.That(memberNameLost.Select(result => result.Message), Has.None.Contains("holds empty references")); + Assert.That(emptyReference.Select(result => result.Message), Has.Some.Contains($"Dependency {dependency.Id} holds empty references (#424)")); + } + } + + private static IElement Clone(IElement element) => (IElement)CloneMethod.Invoke(element, null); + + private static Task> Paged(IReadOnlyList records, QueryParameters parameters) + { + var start = parameters?.PageAfter is { } after ? int.Parse(after.Token) : 0; + var size = parameters is { PageSize: > 0 } ? parameters.PageSize : records.Count; + var end = Math.Min(start + size, records.Count); + + return Task.FromResult(new PagedResult + { + Records = records.Skip(start).Take(end - start).ToList(), + Next = end < records.Count ? new Page(end.ToString()) : null + }); + } + + private Func VerifyModel(IReadOnlyList elements, Guid relationshipSubjectId) => () => this.assertions.VerifyModelAsync(this.commitId, elements, relationshipSubjectId); + } +} diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index b48015f2c..db57a473a 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -24,9 +24,13 @@ merge-conflict handling. **Flexo is the counterpart, not the subject.** It is there because the client can only be checked against a real server; it stands in for any compliant implementation. So: -- Expectations come from the specifications, never from what Flexo happens to do. +- Expectations come from the specifications, the OpenAPI document `Resources/ptc-25-02-30.json` + first, never from what Flexo happens to do. - A difference is triaged (§8) and never absorbed by weakening an assertion: either our client is - wrong (we fix it), or Flexo is (we record it, report it upstream, and keep the scenario running). + wrong (we file an issue and the check stays red), or Flexo is (we record it, report it upstream, + and keep the scenario running). +- The client is not changed while the scenario is built. The scenario is the complete fixture the + client is fixed against later, so its checks must tell a client defect from a server divergence. ### Non-goals @@ -55,50 +59,89 @@ The appendices are the progress checklist; the final step (§5, step 14) enforce ## 3. Test environment -### 3.1 Flexo host — `Integration/FlexoTestHost.cs` +### 3.1 Flexo host — `Helpers/FlexoTestHost.cs` Testcontainers, three containers on one network, following `TESTING.md` §10 and `PostgreSqlSchemaTestHost`: | Container | Image (pinned) | Role | |---|---|---| -| quad store | `atomgraph/fuseki:4.6` | triplestore, loaded from `cluster.trig` | -| layer1 | `openmbee/flexo-mms-layer1-service:v0.3.0` | Flexo MMS core | -| SysML v2 | `openmbee/flexo-sysmlv2:v0.2.1` | the API under test | +| quad store | `atomgraph/fuseki:4.6`, pinned by digest | triplestore, loaded from `cluster.trig` | +| layer1 | `openmbee/flexo-mms-layer1-service:v0.3.0`, pinned by digest | Flexo MMS core | +| SysML v2 | `openmbee/flexo-sysmlv2@sha256:007bd800…` (the `develop` build of commit `836d904d`, pinned by digest) | the API under test | -- `cluster.trig` and the env values are copied from the Flexo `v0.2.1` tag into +`v0.2.1` is not used: it has no paging, no commit changes and no 404 for a missing element. The +pinned `develop` build has all three and stays reproducible; its error answers still carry no +`Error` JSON (§8). + +- `cluster.trig` is copied verbatim from Flexo commit `836d904d` into `SySML2.NET.REST.Tests/Resources/Flexo/` (Apache-2.0; attribution in `NOTICE`). The file holds only users, access control and the metaclass vocabulary — no model data. -- Readiness: poll `GET /projects` until 200. Bootstrap: `PUT {layer1}/orgs/sysmlv2` through a plain - `HttpClient` — layer1 is not the SysML v2 API and stays outside the client under test. -- Docker unavailable → `Assert.Ignore`. `[Category("Integration")]`, which CI already excludes. +- Network aliases `quad-server` and `layer1-service`, which `cluster.trig` and the layer1 + configuration name. Containers start in order: Fuseki (ready on its `Start Fuseki` log line) → + layer1 (ready on any HTTP answer) → `PUT {layer1}/orgs/sysmlv2` through a plain `HttpClient` → + SysML v2 service (ready on `GET /meta/datatypes`). layer1 is not the SysML v2 API and stays + outside the client under test. +- Docker unreachable → `Assert.Ignore`; any later start failure → `Assert.Fail` with the container + logs. `[Category("Integration")]`, which CI already excludes. - Fresh containers per run: every run starts from an empty server. ### 3.2 Client wiring A test `IHttpClientFactory` returns an `HttpClient` whose handler chain is: -1. **`BearerTokenHandler`** — adds `Authorization: Bearer `, the token generated in the test - from the shared HMAC secret (Flexo requires it; `Session` has no auth option — separate issue). +1. **`BearerTokenHandler`** — adds `Authorization: Bearer ` (Flexo requires it; `Session` has + no auth option — separate issue). `FlexoJwt` generates a random secret per run, configures layer1 + with it and signs an HS256 token, so no secret is stored in source. The SysML v2 service gets no + `FLEXO_AUTH` fallback token, so only the client's own token reaches layer1. 2. **`EndpointRecorder`** — records `(method, path template, status)` of every request by matching - the URL against the path templates of `Resources/ptc-25-02-30.json`. Step 14 uses it. + the URL against the path templates of `Resources/ptc-25-02-30.json`, and every request body that + references the empty GUID. Step 14 uses it. It also checks every request and every response + against the OpenAPI document (§3.3). The scenario then uses the production entry point unchanged: `new Session(factory, deSerializer, serializer).Open(flexoUri, …)`. +### 3.3 OpenAPI conformance of every call + +The measure of the client is the OpenAPI document. `OpenApiDocument` reads it as JSON Schema 2020-12 +(OpenAPI 3.1) with JsonSchema.Net, and the recorder checks the raw HTTP traffic of every call: + +- **request** (the client's side): query parameters declared, required ones present, values of the + declared type (`page[size]` an integer, `direction` one of its literals, ids in `uuid` format); + the body of a declared media type and valid against the request schema; +- **response** (the server's side): the status declared, explicitly or by `default`; the body of a + declared media type and valid against the response schema. + +After each step, `OpenApiConformance` fails on any request violation: it is a client defect. A +response violation is reported as the known divergence that explains it (§8), or fails. So a +client defect and a server divergence never pass for each other: a 404 whose body conforms but +reaches the caller without a parsed `Error` fails as a client defect. + +The document is read as published, with two adjustments the validator needs, neither of which +changes what it allows: the component schemas carry `$id`s, some relative, and are referenced both as +`#/components/schemas/…` and by those `$id`s, so the `$id`s are removed and every reference is made +absolute. `PrimitiveConstraintRequest` carries the `$id` of `PrimitiveConstraint`; nothing +references it by that `$id`. + ## 4. How the model is built ### 4.1 Scenario state and the model builder - **`ScenarioState`** (one per fixture) — server-assigned ids (projects, branches, tags, commits, queries), plus a local **expected model**: the DTOs as they should exist at each commit. -- **`ModelBuilder`** — creates DTOs with readable deterministic ids (UUID v5 of - `"/"`), and wires ownership consistently: owner `ownedRelationship` (ordered) ⇄ - membership `ownedRelatedElement` ⇄ member `owningRelationship`. A step only describes *what* it - adds; the builder produces the `DataVersionRequest`s for the commit. +- **`ModelBuilder`** — creates **POCOs** with deterministic ids (UUID v5 of `"/"`); the + step wires ownership with `AssignOwnership` (`SysML2.NET/Extensions/ElementExtensions.cs`). Once + the step is wired, the builder converts every POCO with its generated Dal + `ToDto(includeDerivedProperties: true)`, naming the element when a conversion fails, and produces + the `DataVersionRequest`s for the commit. +- Why POCOs: a DTO cannot hold the value of a non-derived member that a derived property redefines + (`OwningMembership.memberElement`, `Import.source`, … — 173 no-op setters in 90 DTO classes), so a + hand-built DTO would send the empty GUID for it. Only the POCO conversion fills those values. - Payloads are `Core.DTO` elements (`Core.DTO.IElement` implements `IDataRequest`). `PsmApiClient` serializes them without derived properties, and `ComparerProvider` (`SysML2.NET.Extensions`) - compares non-derived content — the two agree. + compares non-derived content — the two agree, except for the redefined members above, which the + comparers skip; §4.3 checks those separately. ### 4.2 Modelling rules @@ -124,30 +167,48 @@ After each commit: - `PostCommitByProjectAsync` returned a commit on the expected branch whose `previousCommits` is the previous head; the branch `head` moved (`GetBranchesByProjectAndIdAsync`). - `GetChangesByProjectCommitAsync` / `GetChangeByProjectCommitIdAsync` → exactly the sent - `DataVersion`s. + `DataVersion`s: one per element, its payload equal to the element sent. - `GetElementByProjectCommitIdAsync` for each element of the step → equal to the expected DTO under `ComparerProvider`. -- `GetElementsByProjectCommitAsync`, paged (`page[size]=25`, following `Link` to the end) → exactly - the expected id set at that commit, no duplicates. -- `GetRootsByProjectCommitAsync` → only the root package. +- `GetElementsByProjectCommitAsync`, paged (`page[size]=10`, following `Link` to the end, so that + every step's model spans several pages) → exactly the expected id set at that commit, no + duplicates. +- `GetRootsByProjectCommitAsync` → exactly the elements without an `owner`. Systems Modeling API and + Services, Clause 7.2.2, Table 2: "A root element is an element that does not have any other element + as an owner. Hence, Element.owner is not specified for a root element." KerML derives `owner` as + `owningRelationship.owningRelatedElement`, so a relationship owned through its + `owningRelatedElement` has no `owner` and is a root. The clause admits a second reading ("owned by + no other element"); this one follows its `Element.owner` sentence. Flexo answers exactly the + elements without an `owningRelatedElement`, so an element owned through its `owningRelationship` + is a root too; that fits neither reading: the known divergence `RootsIgnoreOwningRelationship` + (§8) accepts that exact set, and anything else fails. - `GetRelationshipsByProjectCommitRelatedElementAsync`, `Direction` `in` / `out` / `both`, for the step's relationship ends. - History is immutable: one element of an earlier commit is re-read at that commit and is unchanged. +- Every `Membership` read back has the `memberElement` and `memberName` that were sent, and no + non-derived reference read back is the empty GUID. The comparers do not cover these members, and + the JSON round trip loses them today (#424), so these checks stay red until #424 is fixed. +- No request body references the empty GUID. +- A negative case expects 404 for an unknown resource where the OpenAPI document declares 404, and + any 4xx where it does not; a 404 whose body conforms must reach the caller with its `Error`. A + call may tolerate one named known divergence (§8); any other answer fails. +- Every request and response of the step conforms to the OpenAPI document (§3.3). +- An element that differs from what was sent names the properties that differ. Comparisons over a list of elements run inside `Assert.EnterMultipleScope`, so one run reports every failing metaclass, not just the first. ## 5. The scenario -`FlexoModelScenarioTestFixture` — `[Category("Integration")]`, one `[Test]` per step ordered with -`[Order(n)]` (precedent: `SqlSchemaBenchmarkTestFixture`). `[SetUp]` ignores a step when an -earlier step failed (`Assert.Ignore("step N failed")`), so a failure is reported once, at its -origin. +`FlexoModelScenarioTestFixture` — `[Category("Integration")]`, one `[Test]` per step. Each step +declares `[DependsOnTest(previous step, AllowFailure = true)]` (NUnit 5 deprecates `[Order]`), so +the steps run in order and an assertion failure in one step does not hide the outcome of the next; +a step ignores itself only when the state it builds on is missing. The verdict always runs. | # | Step | Model content | Operations exercised (Appendix C #) | |---:|---|---|---| | 1 | **Empty server** | — | `GET /meta/datatypes` (34), by id (35); `GET /projects` is empty (1); unknown project → 404 `Error` (3) | -| 2 | **Project and root model** | `POST`/`GET`/`PUT` project (2, 3, 4, 1); commit on the default branch: root `Package`, nested `Package`s, `Namespace`, `LibraryPackage`, `AnnotatingElement`, `Comment`, `Documentation`, `TextualRepresentation`, `Annotation`, `OwningMembership`, `Membership`, `NamespaceImport`, `MembershipImport`, `Dependency`, `ElementFilterMembership` (Root, Packages — 14) | 15, 14, 16, 17, 18, 19, 20, 22, 23 | +| 2 | **Project and root model** | `POST`/`GET`/`PUT` project (2, 3, 4, 1); commit on the default branch: root `Package`, nested `Package`s, `Namespace`, `LibraryPackage`, `AnnotatingElement`, `Comment`, `Documentation`, `TextualRepresentation`, `Annotation`, `OwningMembership`, `Membership`, `NamespaceImport`, `MembershipImport`, `Dependency`, `ElementFilterMembership` (Root, Packages — 14); the filter condition is a `LiteralBoolean` with its `result` parameter (a `Feature` through a `ReturnParameterMembership`), which KerML requires of every `Expression` | 15, 14, 16, 17, 18, 19, 20, 22, 23 | | 3 | **KerML Core** | `Type`, `Classifier`, `Feature`, `Specialization`, `Subclassification`, `FeatureTyping`, `Subsetting`, `Redefinition`, `ReferenceSubsetting`, `CrossSubsetting`, `Conjugation`, `Disjoining`, `Differencing`, `Intersecting`, `Unioning`, `FeatureChaining`, `FeatureInverting`, `TypeFeaturing`, `FeatureMembership`, `EndFeatureMembership`, `Multiplicity` (21) — typing and specializing step-2 content | as step 2 | | 4 | **KerML Kernel** | data types, classes, structures, associations, connectors, behaviors, steps, functions, all expression and literal kinds, feature values, multiplicity ranges, interactions, flows, metaclasses and metadata (43); then **tag** `kernel` on this commit | as step 2; `POST`/`GET` tags (11, 10, 12) | | 5 | **Update the KerML model** | U1–U4 (§6.1) on step 2–4 content | 15, 17, 20; `DiffAsync` `kernel` → head shows `UPDATED` (24) | @@ -209,7 +270,9 @@ Computed from what the **server returned**, not from what was sent: DTO interfaces), some element read back carried a non-default value, and some update changed it. - **Literals**: every enumeration literal was read back at least once. - **Endpoints**: `EndpointRecorder` saw every `(method, path template)` of - `Resources/ptc-25-02-30.json` (35), each with at least one success and one failure status. + `Resources/ptc-25-02-30.json` (35) with a success status, and with a client error status where + the document declares a 4xx response for it. A 5xx counts as a divergence, not as coverage. Every + request must address an operation of the document. All four lists are self-calibrating: extending the metamodel or the OpenAPI document never needs a change to the verdict, only to the steps. @@ -218,20 +281,47 @@ change to the verdict, only to the steps. | Finding | Action | |---|---| -| Our client or serializer is wrong per the spec | fix here, with a unit test | -| Flexo diverges from the spec | not a failure of the client, so not a failure of this suite: upstream issue on `Open-MBEE/flexo-mms-sysmlv2`; the case goes in one `KnownServerDivergences` table and is reported through `Assert.Warn` quoting the issue, so later steps still run — the expectation stays spec-based | +| Our client or serializer is wrong per the spec | not fixed while the scenario is built: a GitHub issue is filed and the check stays red, so the scenario is the fixture the client is fixed against later | +| Flexo diverges from the spec | not a failure of the client, so not a failure of this suite: the case goes in one `KnownServerDivergences` table and is reported through `Assert.Warn` quoting its reference, so later steps still run — the expectation stays spec-based. The reference is the Flexo source location, or the route it was observed on, at the pinned commit until an upstream issue on `Open-MBEE/flexo-mms-sysmlv2` exists, which then replaces it. A divergence that a response violation shows (§3.3) carries a matcher as narrow as the violation, so it cannot hide another one. An entry is added with the step that first observes it | | The spec is ambiguous | pick a reading, cite the clause, note in one line that it admits more than one (CLAUDE.md) | -Known before starting: Flexo's `/meta/datatypes` serves a pre-final schema (`ItemFlow`, -`LifeClass`, …) — step 1 asserts shape only. +Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergences.cs`: + +- `RootsIgnoreOwningRelationship`: the roots are every element without an `owningRelatedElement`, + including the elements owned through their `owningRelationship` (step 2); +- `UnknownResourceNotFound`, `UnknownResourceAccepted`: an unknown project answers 403 instead of + 404, and the relationships of an unknown element answer 200 (step 2); +- `ErrorWithoutErrorBody`: an error answer carries an empty or `text/plain` body, never an + `application/json` `Error` (steps 1, 2); +- `CreatedAnsweredOk`: `POST /projects` and `POST …/commits` answer 200 instead of 201 (step 2); +- `RecordsWithoutRequiredProperties`: projects, branches, commits and data versions leave out the + required `alias`, `name`, `description` and `deleted`, and send `null` for an empty + `previousCommit` (step 2); +- `ElementsWithoutDerivedProperties`: elements come back without their derived properties + (`owner`, `qualifiedName`, …), which the response schemas require; it matches only when every + missing property is derived, so a missing non-derived property still fails (step 2); +- `DatatypeIdNotUri`: a datatype comes back with an `$id` that is not a URI (step 1). + +Expected from the Flexo source, added with the step that observes them: + +- diff and merge answer 501 Not Implemented (steps 5, 8); +- real values come back as single-precision floats (step 4); +- deleting an element leaves the elements it owns in place (no cascade, §6.2 D3, step 12). + +Client defects found so far, each red until fixed: + +- #424 — the JSON round trip loses non-derived members that a derived property redefines + (`memberElement`, `memberName`, `source`, `target`); +- #425 — the PSM JSON serializers write `null` for optional references that the OpenAPI document + does not make nullable (`ProjectRequest.defaultBranch`, …). ## 9. Open questions 1. **Query by `@type` and subtypes** — Flexo matches subtypes; check whether the spec requires it. 2. **ProjectUsage / ExternalData / ExternalRelationship on Flexo** — stored generically, untested. -3. **Flexo image** — `v0.2.1` (recommended) or `develop-SNAPSHOT`. +3. **Flexo image** — decided: the `develop` build pinned by digest (§3.1). 4. **CI** — local only (recommended for now), or a separate opt-in workflow. -5. **One `[Test]` per step vs `TESTING.md` §2** — In the scope of this integration test, going again rules defined in the TESTING.md file is accepted. One scenario can be split into multiple [Test] method. A TestOrder need to be correctly settle +5. **One `[Test]` per step vs `TESTING.md` §2** — decided: in the scope of this integration test, going against the rules of `TESTING.md` is accepted. One scenario is split into one `[Test]` per step, and the order is set with `[DependsOnTest(…, AllowFailure = true)]` (§5). ## 10. Work breakdown diff --git a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs new file mode 100644 index 000000000..fc8731b8a --- /dev/null +++ b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs @@ -0,0 +1,212 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.IntegrationTests +{ + using System; + using System.IO; + using System.Linq; + using System.Net; + using System.Runtime.CompilerServices; + using System.Threading; + using System.Threading.Tasks; + + using NUnit.Framework; + + using SySML2.NET.REST; + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + using SysML2.NET.PSM.DTO; + using SysML2.NET.REST.Exceptions; + using SysML2.NET.Serializer.Json; + + /// + /// The scenario of SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md: it builds a model step by step on a + /// Flexo server through the REST client, verifying the client by reading back everything it wrote + /// + /// + /// One [Test] per scenario step, each depending on the previous one with AllowFailure, so the + /// steps run in order and an assertion failure in one step does not hide the outcome of the next. + /// + [TestFixture] + [Category("Integration")] + [NonParallelizable] + public class FlexoModelScenarioTestFixture + { + private readonly ScenarioState state = new(); + + private FlexoTestHost host; + + private OpenApiDocument openApi; + + private IntegrationHttpClientFactory httpClientFactory; + + private Session session; + + private IPsmApiClient client; + + private ReadBackAssertions readBack; + + private int verifiedCalls; + + [OneTimeSetUp] + public async Task OneTimeSetUp() + { + this.host = new FlexoTestHost(); + + using var startTimeout = new CancellationTokenSource(TimeSpan.FromMinutes(15)); + await this.host.StartAsync(startTimeout.Token); + + this.openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + this.httpClientFactory = new IntegrationHttpClientFactory(this.host.Token, this.openApi); + this.session = new Session(this.httpClientFactory, new DeSerializer(), new Serializer()); + + await this.session.Open(this.host.BaseAddress, CancellationToken.None); + + this.client = this.session.Client; + this.readBack = new ReadBackAssertions(this.client, this.state); + } + + [OneTimeTearDown] + public async Task OneTimeTearDown() + { + this.session?.Close(); + this.httpClientFactory?.Dispose(); + + if (this.host != null) + { + await this.host.DisposeAsync(); + } + } + + [TearDown] + public void TearDown() + { + if (this.httpClientFactory == null) + { + return; + } + + var calls = this.httpClientFactory.Recorder.Calls.ToList(); + + OpenApiConformance.Verify(calls[this.verifiedCalls..], KnownServerDivergences.All); + this.verifiedCalls = calls.Count; + } + + [Test] + public async Task VerifyEmptyServer() + { + var datatypes = await this.client.GetDatatypesAsync(); + var projects = await this.client.GetProjectsAsync(); + + Assert.That(datatypes.Records, Is.Not.Empty); + + var datatypeId = datatypes.Records[0].RootElement.GetProperty("$defs").EnumerateObject().First().Name; + var datatype = await this.client.GetDatatypeByIdAsync(datatypeId); + + using (Assert.EnterMultipleScope()) + { + Assert.That(datatype.RootElement.ValueKind, Is.EqualTo(System.Text.Json.JsonValueKind.Object)); + Assert.That(projects.Records, Is.Empty); + } + + await this.ExpectNotFoundAsync(() => this.client.GetDatatypeByIdAsync("NoSuchDatatype")); + await this.ExpectNotFoundAsync(() => this.client.GetProjectByIdAsync(Guid.NewGuid())); + } + + [Test] + [DependsOnTest(nameof(VerifyEmptyServer), AllowFailure = true)] + public async Task VerifyProjectAndRootModel() + { + var created = await this.client.PostProjectAsync(new ProjectRequest { Name = "CoverageModel", Description = "The model of the REST client integration scenario" }); + + this.state.ProjectId = created.Id; + this.state.DefaultBranchId = created.DefaultBranch; + + var read = await this.client.GetProjectByIdAsync(created.Id); + var renamed = await this.client.PutProjectByIdAsync(created.Id, new ProjectRequest { Name = "Coverage model", Description = "Renamed by step 2", DefaultBranch = created.DefaultBranch }); + var (projects, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetProjectsAsync(parameters)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(read.Name, Is.EqualTo("CoverageModel")); + Assert.That(read.DefaultBranch, Is.EqualTo(created.DefaultBranch)); + Assert.That(renamed.Name, Is.EqualTo("Coverage model")); + Assert.That(renamed.Description, Is.EqualTo("Renamed by step 2")); + Assert.That(projects.Select(project => project.Id), Is.EqualTo([created.Id])); + } + + var model = new RootModel(); + var elements = model.Builder.ToDtos(); + + var commit = await this.client.PostCommitByProjectAsync(created.Id, ModelBuilder.ToCommitRequest(elements, "Root model"), created.DefaultBranch); + + this.state.HeadCommitId = commit.Id; + this.state.ExpectedModels[commit.Id] = elements; + + var unknown = Guid.NewGuid(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(this.httpClientFactory.Recorder.EmptyGuidRequests, Is.Empty, "a request referenced the empty GUID"); + + await this.ExpectNotFoundAsync(() => this.client.PutProjectByIdAsync(unknown, new ProjectRequest { Name = "Unknown" })); + await ExpectClientErrorAsync(() => this.client.PostCommitByProjectAsync(unknown, ModelBuilder.ToCommitRequest(elements, "Unknown project"))); + await this.ExpectNotFoundAsync(() => this.client.GetCommitsByProjectAsync(unknown), KnownServerDivergences.UnknownResourceNotFound); + await this.ExpectNotFoundAsync(() => this.client.GetCommitByProjectAndIdAsync(created.Id, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetChangesByProjectCommitAsync(created.Id, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetChangeByProjectCommitIdAsync(created.Id, commit.Id, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetElementsByProjectCommitAsync(created.Id, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetElementByProjectCommitIdAsync(created.Id, commit.Id, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetRootsByProjectCommitAsync(created.Id, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(created.Id, commit.Id, unknown), KnownServerDivergences.UnknownResourceAccepted); + await this.ExpectNotFoundAsync(() => this.client.GetBranchesByProjectAndIdAsync(created.Id, unknown)); + + await this.readBack.VerifyCommitAsync(commit, created.DefaultBranch, null, elements); + await this.readBack.VerifyModelAsync(commit.Id, elements, model.Nested.Id); + } + } + + [Test] + [DependsOnTest(nameof(VerifyProjectAndRootModel), AllowFailure = true)] + public async Task VerifyCoverage() + { + var verdict = new CoverageVerdict(this.state.ReadBack, this.httpClientFactory.Recorder.Calls, this.openApi); + + await TestContext.Out.WriteLineAsync($"Missing metaclasses ({verdict.MissingMetaclasses.Count}): {string.Join(", ", verdict.MissingMetaclasses)}"); + await TestContext.Out.WriteLineAsync($"Unset properties ({verdict.UnsetProperties.Count}): {string.Join(", ", verdict.UnsetProperties)}"); + await TestContext.Out.WriteLineAsync($"Unchanged properties ({verdict.UnchangedProperties.Count}): {string.Join(", ", verdict.UnchangedProperties)}"); + await TestContext.Out.WriteLineAsync($"Missing literals ({verdict.MissingLiterals.Count}): {string.Join(", ", verdict.MissingLiterals)}"); + await TestContext.Out.WriteLineAsync($"Uncovered operations ({verdict.UncoveredOperations.Count}): {string.Join(", ", verdict.UncoveredOperations)}"); + await TestContext.Out.WriteLineAsync($"Unmatched requests ({verdict.UnmatchedRequests.Count}): {string.Join(", ", verdict.UnmatchedRequests)}"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(verdict.MissingMetaclasses, Is.Empty, "metaclasses of which the server returned no instance"); + Assert.That(verdict.UnsetProperties, Is.Empty, "properties never returned with a non-default value"); + Assert.That(verdict.UnchangedProperties, Is.Empty, "properties never changed by an update"); + Assert.That(verdict.MissingLiterals, Is.Empty, "enumeration literals never returned"); + Assert.That(verdict.UncoveredOperations, Is.Empty, "operations not called with a success, or with a client error where the OpenAPI document declares one"); + Assert.That(verdict.UnmatchedRequests, Is.Empty, "requests that address no operation of the OpenAPI document"); + Assert.That(this.httpClientFactory.Recorder.EmptyGuidRequests, Is.Empty, "requests that referenced the empty GUID"); + } + } + + private static async Task ExpectClientErrorAsync(Func call, [CallerArgumentExpression(nameof(call))] string description = null) + { + await Assert.ThatAsync(() => call(), Throws.InstanceOf().With.Property(nameof(PsmApiException.StatusCode)).Matches(status => (int)status is >= 400 and < 500), description); + } + + private Task ExpectNotFoundAsync(Func call, ServerDivergence tolerated = null, [CallerArgumentExpression(nameof(call))] string description = null) + { + return KnownServerDivergences.ExpectNotFoundAsync(call, () => this.httpClientFactory.Recorder.LastCall, tolerated, description); + } + } +} diff --git a/SySML2.NET.REST.Tests/Resources/Flexo/cluster.trig b/SySML2.NET.REST.Tests/Resources/Flexo/cluster.trig new file mode 100644 index 000000000..2b0401d4a --- /dev/null +++ b/SySML2.NET.REST.Tests/Resources/Flexo/cluster.trig @@ -0,0 +1,1311 @@ +prefix rdf: +prefix rdfs: +prefix mms: +prefix mms-object: +prefix m: +prefix ma: +prefix m-graph: +prefix m-user: +prefix m-group: +prefix m-policy: +prefix sysml: +prefix sysx: +prefix xsd: + +# users and groups which are the subjects of access control policies +graph m-graph:AccessControl.Agents { + m-user:root a mms:User ; + mms:id "root" . + + m-user:admin a mms:User ; + mms:group m-group:SuperAdmins ; + mms:id "admin" . + + m-user:anon a mms:User ; + mms:id "anon" . + + a mms:User ; + mms:id "ldap/user/user01" . + + a mms:User ; + mms:id "ldap/user/user02" . + + a mms:Group ; + mms:id "ldap/group/group01" . + + m-group:SuperAdmins a mms:Group ; + mms:id "super_admins" ; + mms:etag "mms-init-etag-value-group-SuperAdmins" . +} + +# default policies +graph m-graph:AccessControl.Policies { + m-policy:DefaultSuperAdmins a mms:Policy ; + mms:subject m-user:root, m-group:SuperAdmins, , ; + mms:scope ; + mms:role mms-object:Role.AdminCluster, mms-object:Role.AdminOrg, mms-object:Role.AdminRepo, mms-object:Role.AdminMetadata, mms-object:Role.AdminModel, mms-object:Role.AdminAccessControlAny . +} + +# cluster-specific classes +graph m-graph:Cluster { + a mms:Cluster . + + a mms:AccessControlAny . +} + +# copy of static schema inherited from global MMS definitions +graph m-graph:Schema { + # ==================================== + # == Classes == + # ==================================== + mms:Project a rdfs:Class ; + rdfs:label "Project" . + + mms:Collection a rdfs:Class ; + rdfs:label "Collection" ; + rdfs:subClassOf mms:Project . + + mms:Repo a rdfs:Class ; + rdfs:label "Repo" ; + rdfs:subClassOf mms:Project . + + mms:Ref a rdfs:Class ; + rdfs:label "Ref" . + + mms:Branch a rdfs:Class ; + rdfs:label "Branch" ; + rdfs:subClassOf mms:Ref . + + mms:Lock a rdfs:Class ; + rdfs:label "Lock" ; + rdfs:subClassOf mms:Ref . + + mms:InterimLock a rdfs:Class ; + rdfs:label "InterimLock" ; + rdfs:subClassOf mms:Lock . + + mms:Artifact a rdfs:Class ; + rdfs:label "Artifact" . + + mms:Scratch a rdfs:Class ; + rdfs:label "Scratch" . + + mms:Snapshot a rdfs:Class ; + rdfs:label "Snapshot" . + + mms:Model a rdfs:Class ; + rdfs:label "Model" ; + rdfs:subClassOf mms:Snapshot . + + mms:Staging a rdfs:Class ; + rdfs:label "Staging" ; + rdfs:subClassOf mms:Snapshot . + + mms:Commit a rdfs:Class ; + rdfs:label "Commit" . + + mms:Agent a rdfs:Class ; + rdfs:label "Agent" . + + mms:User a rdfs:Class ; + rdfs:label "User" ; + rdfs:subClassOf mms:Agent . + + mms:Group a rdfs:Class ; + rdfs:label "Group" ; + rdfs:subClassOf mms:Agent . + + mms:Policy a rdfs:Class ; + rdfs:label "Policy" . + + # ==================================== + # == Properties == + # ==================================== + mms:ref a rdf:Property ; + rdfs:label "ref" ; + rdfs:range mms:Ref . + + mms:commit a rdf:Property ; + rdfs:label "commit" ; + rdfs:range mms:Commit . + + mms:snapshot a rdf:Property ; + rdfs:label "snapshot" ; + rdfs:range mms:Snapshot . +} + +graph m-graph:AccessControl.Definitions { + # ==================================== + # == Scopes == + # ==================================== + mms:Cluster a rdfs:Class ; + rdfs:label "Cluster level scope" ; + rdfs:subClassOf mms:Scope ; + mms:implies mms:Org, mms:AccessControlAny . + + mms:Org a rdfs:Class ; + rdfs:label "Org level scope" ; + rdfs:subClassOf mms:Scope ; + mms:implies mms:Project . + + mms:Project a rdfs:Class ; + rdfs:label "Project level scope" ; + rdfs:subClassOf mms:Scope ; + mms:implies mms:Repo, mms:Collection . + + mms:Repo a rdfs:Class ; + rdfs:label "Repo level scope" ; + rdfs:subClassOf mms:Scope ; + mms:implies mms:Ref, mms:Artifact, mms:Commit, mms:Scratch . + + mms:Collection a rdfs:Class ; + rdfs:label "Collection level scope" ; + rdfs:subClassOf mms:Scope . + + mms:Artifact a rdfs:Class ; + rdfs:label "Artifact level scope" ; + rdfs:subClassOf mms:Scope . + + mms:Ref a rdfs:Class ; + rdfs:label "Ref level scope" ; + rdfs:subClassOf mms:Scope ; + mms:implies mms:Branch, mms:Lock . + + mms:AccessControlAny a rdfs:Class ; + rdfs:label "AccessControlAny level scope" ; + rdfs:subClassOf mms:Scope ; + mms:implies mms:Agent, mms:Policy . + + mms:Agent a rdfs:Class ; + rdfs:label "Agent level scope" ; + rdfs:subClassOf mms:Scope ; + mms:implies mms:User, mms:Group . + + mms:User a rdfs:Class ; + rdfs:label "User level scope" ; + rdfs:subClassOf mms:Scope . + + mms:Group a rdfs:Class ; + rdfs:label "Group level scope" ; + rdfs:subClassOf mms:Scope . + + mms:Policy a rdfs:Class ; + rdfs:label "Policy level scope" ; + rdfs:subClassOf mms:Scope . + + mms:Scratch a rdfs:Class ; + rdfs:label "Scratch level scope" ; + rdfs:subClassOf mms:Scope . + + # ==================================== + # == Object-Centric Permissions == + # ==================================== + mms-object:Permission.CreateCluster a mms:Permission . + + mms-object:Permission.ReadCluster a mms:Permission . + + mms-object:Permission.UpdateCluster a mms:Permission ; + mms:implies mms-object:Permission.ReadCluster, mms-object:Permission.CreateOrg, mms-object:Permission.CreateAccessControlAny . + + mms-object:Permission.DeleteCluster a mms:Permission ; + mms:implies mms-object:Permission.UpdateCluster, mms-object:Permission.DeleteOrg, mms-object:Permission.DeleteAccessControlAny . + + mms-object:Permission.CreateOrg a mms:Permission . + + mms-object:Permission.ReadOrg a mms:Permission . + + mms-object:Permission.UpdateOrg a mms:Permission ; + mms:implies mms-object:Permission.ReadOrg, mms-object:Permission.CreateProject . + + mms-object:Permission.DeleteOrg a mms:Permission ; + mms:implies mms-object:Permission.UpdateOrg, mms-object:Permission.DeleteProject . + + mms-object:Permission.CreateProject a mms:Permission ; + mms:implies mms-object:Permission.CreateCollection, mms-object:Permission.CreateRepo . + + mms-object:Permission.ReadProject a mms:Permission ; + mms:implies mms-object:Permission.ReadCollection, mms-object:Permission.ReadRepo . + + mms-object:Permission.UpdateProject a mms:Permission ; + mms:implies mms-object:Permission.ReadProject, mms-object:Permission.UpdateCollection, mms-object:Permission.UpdateRepo . + + mms-object:Permission.DeleteProject a mms:Permission ; + mms:implies mms-object:Permission.UpdateProject, mms-object:Permission.DeleteCollection, mms-object:Permission.DeleteRepo . + + mms-object:Permission.CreateCollection a mms:Permission . + + mms-object:Permission.ReadCollection a mms:Permission . + + mms-object:Permission.UpdateCollection a mms:Permission ; + mms:implies mms-object:Permission.ReadCollection . + + mms-object:Permission.DeleteCollection a mms:Permission ; + mms:implies mms-object:Permission.UpdateCollection . + + mms-object:Permission.CreateRepo a mms:Permission . + + mms-object:Permission.ReadRepo a mms:Permission . + + mms-object:Permission.UpdateRepo a mms:Permission ; + mms:implies mms-object:Permission.ReadRepo, mms-object:Permission.ReadCommit, mms-object:Permission.ReadScratch, mms-object:Permission.UpdateBranch, mms-object:Permission.UpdateLock, mms-object:Permission.UpdateCommit, mms-object:Permission.UpdateRef, mms-object:Permission.UpdateArtifact, mms-object:Permission.UpdateScratch . + + mms-object:Permission.DeleteRepo a mms:Permission ; + mms:implies mms-object:Permission.UpdateRepo, mms-object:Permission.CreateRef, mms-object:Permission.DeleteRef, mms-object:Permission.CreateArtifact, mms-object:Permission.DeleteArtifact, mms-object:Permission.CreateDiff, mms-object:Permission.DeleteDiff, mms-object:Permission.CreateScratch, mms-object:Permission.DeleteScratch . + + mms-object:Permission.CreateRef a mms:Permission . + + mms-object:Permission.ReadRef a mms:Permission . + + mms-object:Permission.UpdateRef a mms:Permission ; + mms:implies mms-object:Permission.ReadRef, mms-object:Permission.UpdateBranch, mms-object:Permission.UpdateLock . + + mms-object:Permission.DeleteRef a mms:Permission ; + mms:implies mms-object:Permission.CreateBranch, mms-object:Permission.DeleteBranch, mms-object:Permission.CreateLock, mms-object:Permission.DeleteLock . + + mms-object:Permission.CreateBranch a mms:Permission . + + mms-object:Permission.ReadBranch a mms:Permission . + + mms-object:Permission.UpdateBranch a mms:Permission ; + mms:implies mms-object:Permission.ReadBranch . + + mms-object:Permission.DeleteBranch a mms:Permission ; + mms:implies mms-object:Permission.UpdateBranch . + + mms-object:Permission.CreateLock a mms:Permission . + + mms-object:Permission.ReadLock a mms:Permission . + + mms-object:Permission.UpdateLock a mms:Permission ; + mms:implies mms-object:Permission.ReadLock . + + mms-object:Permission.DeleteLock a mms:Permission ; + mms:implies mms-object:Permission.UpdateLock . + + mms-object:Permission.CreateArtifact a mms:Permission . + + mms-object:Permission.ReadArtifact a mms:Permission . + + mms-object:Permission.UpdateArtifact a mms:Permission ; + mms:implies mms-object:Permission.ReadArtifact . + + mms-object:Permission.DeleteArtifact a mms:Permission ; + mms:implies mms-object:Permission.UpdateArtifact . + + mms-object:Permission.CreateScratch a mms:Permission . + + mms-object:Permission.ReadScratch a mms:Permission . + + mms-object:Permission.UpdateScratch a mms:Permission ; + mms:implies mms-object:Permission.ReadScratch . + + mms-object:Permission.DeleteScratch a mms:Permission ; + mms:implies mms-object:Permission.UpdateScratch . + + mms-object:Permission.CreateCommit a mms:Permission . + + mms-object:Permission.ReadCommit a mms:Permission . + + mms-object:Permission.UpdateCommit a mms:Permission ; + mms:implies mms-object:Permission.ReadCommit . + + mms-object:Permission.DeleteCommit a mms:Permission ; + mms:implies mms-object:Permission.UpdateCommit . + + mms-object:Permission.CreateAccessControlAny a mms:Permission . + + mms-object:Permission.ReadAccessControlAny a mms:Permission . + + mms-object:Permission.UpdateAccessControlAny a mms:Permission ; + mms:implies mms-object:Permission.ReadAccessControlAny, mms-object:Permission.CreateAgent, mms-object:Permission.CreatePolicy . + + mms-object:Permission.DeleteAccessControlAny a mms:Permission ; + mms:implies mms-object:Permission.UpdateAccessControlAny, mms-object:Permission.DeleteAgent, mms-object:Permission.DeletePolicy . + + mms-object:Permission.CreateAgent a mms:Permission . + + mms-object:Permission.ReadAgent a mms:Permission . + + mms-object:Permission.UpdateAgent a mms:Permission ; + mms:implies mms-object:Permission.ReadAgent, mms-object:Permission.CreateUser, mms-object:Permission.CreateGroup . + + mms-object:Permission.DeleteAgent a mms:Permission ; + mms:implies mms-object:Permission.UpdateAgent, mms-object:Permission.DeleteUser, mms-object:Permission.DeleteGroup . + + mms-object:Permission.CreateUser a mms:Permission . + + mms-object:Permission.ReadUser a mms:Permission . + + mms-object:Permission.UpdateUser a mms:Permission ; + mms:implies mms-object:Permission.ReadUser . + + mms-object:Permission.DeleteUser a mms:Permission ; + mms:implies mms-object:Permission.UpdateUser . + + mms-object:Permission.CreateGroup a mms:Permission . + + mms-object:Permission.ReadGroup a mms:Permission . + + mms-object:Permission.UpdateGroup a mms:Permission ; + mms:implies mms-object:Permission.ReadGroup . + + mms-object:Permission.DeleteGroup a mms:Permission ; + mms:implies mms-object:Permission.UpdateGroup . + + mms-object:Permission.CreatePolicy a mms:Permission . + + mms-object:Permission.ReadPolicy a mms:Permission . + + mms-object:Permission.UpdatePolicy a mms:Permission ; + mms:implies mms-object:Permission.ReadPolicy . + + mms-object:Permission.DeletePolicy a mms:Permission ; + mms:implies mms-object:Permission.UpdatePolicy . + + # ==================================== + # == Roles == + # ==================================== + mms-object:Role.AdminOrg a mms:Role ; + mms:permits mms-object:Permission.DeleteOrg . + + mms-object:Role.WriteOrg a mms:Role ; + mms:permits mms-object:Permission.UpdateOrg . + + mms-object:Role.ReadOrg a mms:Role ; + mms:permits mms-object:Permission.ReadOrg . + + mms-object:Role.AdminRepo a mms:Role ; + mms:permits mms-object:Permission.DeleteRepo . + + mms-object:Role.WriteRepo a mms:Role ; + mms:permits mms-object:Permission.UpdateRepo . + + mms-object:Role.ReadRepo a mms:Role ; + mms:permits mms-object:Permission.ReadRepo . + + mms-object:Role.AdminModel a mms:Role ; + mms:permits mms-object:Permission.DeleteModel . + + mms-object:Role.WriteModel a mms:Role ; + mms:permits mms-object:Permission.UpdateModel . + + mms-object:Role.ReadModel a mms:Role ; + mms:permits mms-object:Permission.ReadModel . + + mms-object:Role.AdminMetadata a mms:Role ; + mms:permits mms-object:Permission.DeleteMetadata . + + mms-object:Role.WriteMetadata a mms:Role ; + mms:permits mms-object:Permission.UpdateMetadata . + + mms-object:Role.ReadMetadata a mms:Role ; + mms:permits mms-object:Permission.ReadMetadata . + + mms-object:Role.AdminCluster a mms:Role ; + mms:permits mms-object:Permission.DeleteCluster . + + mms-object:Role.WriteCluster a mms:Role ; + mms:permits mms-object:Permission.UpdateCluster . + + mms-object:Role.ReadCluster a mms:Role ; + mms:permits mms-object:Permission.ReadCluster . + + mms-object:Role.AdminAccessControlAny a mms:Role ; + mms:permits mms-object:Permission.DeleteAccessControlAny . + + mms-object:Role.WriteAccessControlAny a mms:Role ; + mms:permits mms-object:Permission.UpdateAccessControlAny . + + mms-object:Role.ReadAccessControlAny a mms:Role ; + mms:permits mms-object:Permission.ReadAccessControlAny . +} + + +# SysML metaclass hierarchy, copied verbatim from Open-MBEE/OpenSysML +# internal/translate/rdf/ontology/sysml-metaclasses.ttl (written by `sysml -metaclass-graph`, +# OpenSysML commit d4e050400; pilot metamodel 2026-08 / 0.62.0); also bundled as +# src/main/resources/sysml-metaclasses.ttl. Lets a SPARQL consumer resolve metaclass +# specializations with rdf:type/rdfs:subClassOf* against this named graph. +graph { + sysml:AcceptActionUsage + a rdfs:Class ; + rdfs:label "AcceptActionUsage" ; + rdfs:subClassOf sysml:ActionUsage . + + sysml:ActionDefinition + a rdfs:Class ; + rdfs:label "ActionDefinition" ; + rdfs:subClassOf sysml:Behavior, sysml:OccurrenceDefinition . + + sysml:ActionUsage + a rdfs:Class ; + rdfs:label "ActionUsage" ; + rdfs:subClassOf sysml:OccurrenceUsage, sysml:Step . + + sysml:ActorMembership + a rdfs:Class ; + rdfs:label "ActorMembership" ; + rdfs:subClassOf sysml:ParameterMembership . + + sysml:AllocationDefinition + a rdfs:Class ; + rdfs:label "AllocationDefinition" ; + rdfs:subClassOf sysml:ConnectionDefinition . + + sysml:AllocationUsage + a rdfs:Class ; + rdfs:label "AllocationUsage" ; + rdfs:subClassOf sysml:ConnectionUsage . + + sysml:AnalysisCaseDefinition + a rdfs:Class ; + rdfs:label "AnalysisCaseDefinition" ; + rdfs:subClassOf sysml:CaseDefinition . + + sysml:AnalysisCaseUsage + a rdfs:Class ; + rdfs:label "AnalysisCaseUsage" ; + rdfs:subClassOf sysml:CaseUsage . + + sysml:AnnotatingElement + a rdfs:Class ; + rdfs:label "AnnotatingElement" ; + rdfs:subClassOf sysml:Element . + + sysml:Annotation + a rdfs:Class ; + rdfs:label "Annotation" ; + rdfs:subClassOf sysml:Relationship . + + sysml:AssertConstraintUsage + a rdfs:Class ; + rdfs:label "AssertConstraintUsage" ; + rdfs:subClassOf sysml:ConstraintUsage, sysml:Invariant . + + sysml:AssignmentActionUsage + a rdfs:Class ; + rdfs:label "AssignmentActionUsage" ; + rdfs:subClassOf sysml:ActionUsage . + + sysml:Association + a rdfs:Class ; + rdfs:label "Association" ; + rdfs:subClassOf sysml:Classifier, sysml:Relationship . + + sysml:AssociationStructure + a rdfs:Class ; + rdfs:label "AssociationStructure" ; + rdfs:subClassOf sysml:Association, sysml:Structure . + + sysml:AttributeDefinition + a rdfs:Class ; + rdfs:label "AttributeDefinition" ; + rdfs:subClassOf sysml:DataType, sysml:Definition . + + sysml:AttributeUsage + a rdfs:Class ; + rdfs:label "AttributeUsage" ; + rdfs:subClassOf sysml:Usage . + + sysml:Behavior + a rdfs:Class ; + rdfs:label "Behavior" ; + rdfs:subClassOf sysml:Class . + + sysml:BindingConnector + a rdfs:Class ; + rdfs:label "BindingConnector" ; + rdfs:subClassOf sysml:Connector . + + sysml:BindingConnectorAsUsage + a rdfs:Class ; + rdfs:label "BindingConnectorAsUsage" ; + rdfs:subClassOf sysml:BindingConnector, sysml:ConnectorAsUsage . + + sysml:BooleanExpression + a rdfs:Class ; + rdfs:label "BooleanExpression" ; + rdfs:subClassOf sysml:Expression . + + sysml:CalculationDefinition + a rdfs:Class ; + rdfs:label "CalculationDefinition" ; + rdfs:subClassOf sysml:ActionDefinition, sysml:Function . + + sysml:CalculationUsage + a rdfs:Class ; + rdfs:label "CalculationUsage" ; + rdfs:subClassOf sysml:ActionUsage, sysml:Expression . + + sysml:CaseDefinition + a rdfs:Class ; + rdfs:label "CaseDefinition" ; + rdfs:subClassOf sysml:CalculationDefinition . + + sysml:CaseUsage + a rdfs:Class ; + rdfs:label "CaseUsage" ; + rdfs:subClassOf sysml:CalculationUsage . + + sysml:Class + a rdfs:Class ; + rdfs:label "Class" ; + rdfs:subClassOf sysml:Classifier . + + sysml:Classifier + a rdfs:Class ; + rdfs:label "Classifier" ; + rdfs:subClassOf sysml:Type . + + sysml:CollectExpression + a rdfs:Class ; + rdfs:label "CollectExpression" ; + rdfs:subClassOf sysml:OperatorExpression . + + sysml:Comment + a rdfs:Class ; + rdfs:label "Comment" ; + rdfs:subClassOf sysml:AnnotatingElement . + + sysml:ConcernDefinition + a rdfs:Class ; + rdfs:label "ConcernDefinition" ; + rdfs:subClassOf sysml:RequirementDefinition . + + sysml:ConcernUsage + a rdfs:Class ; + rdfs:label "ConcernUsage" ; + rdfs:subClassOf sysml:RequirementUsage . + + sysml:ConjugatedPortDefinition + a rdfs:Class ; + rdfs:label "ConjugatedPortDefinition" ; + rdfs:subClassOf sysml:PortDefinition . + + sysml:ConjugatedPortTyping + a rdfs:Class ; + rdfs:label "ConjugatedPortTyping" ; + rdfs:subClassOf sysml:FeatureTyping . + + sysml:Conjugation + a rdfs:Class ; + rdfs:label "Conjugation" ; + rdfs:subClassOf sysml:Relationship . + + sysml:ConnectionDefinition + a rdfs:Class ; + rdfs:label "ConnectionDefinition" ; + rdfs:subClassOf sysml:AssociationStructure, sysml:PartDefinition . + + sysml:ConnectionUsage + a rdfs:Class ; + rdfs:label "ConnectionUsage" ; + rdfs:subClassOf sysml:ConnectorAsUsage, sysml:PartUsage . + + sysml:Connector + a rdfs:Class ; + rdfs:label "Connector" ; + rdfs:subClassOf sysml:Feature, sysml:Relationship . + + sysml:ConnectorAsUsage + a rdfs:Class ; + rdfs:label "ConnectorAsUsage" ; + rdfs:subClassOf sysml:Connector, sysml:Usage ; + sysx:abstract "true"^^xsd:boolean . + + sysml:ConstraintDefinition + a rdfs:Class ; + rdfs:label "ConstraintDefinition" ; + rdfs:subClassOf sysml:OccurrenceDefinition, sysml:Predicate . + + sysml:ConstraintUsage + a rdfs:Class ; + rdfs:label "ConstraintUsage" ; + rdfs:subClassOf sysml:BooleanExpression, sysml:OccurrenceUsage . + + sysml:ConstructorExpression + a rdfs:Class ; + rdfs:label "ConstructorExpression" ; + rdfs:subClassOf sysml:InstantiationExpression . + + sysml:ControlNode + a rdfs:Class ; + rdfs:label "ControlNode" ; + rdfs:subClassOf sysml:ActionUsage ; + sysx:abstract "true"^^xsd:boolean . + + sysml:CrossSubsetting + a rdfs:Class ; + rdfs:label "CrossSubsetting" ; + rdfs:subClassOf sysml:Subsetting . + + sysml:DataType + a rdfs:Class ; + rdfs:label "DataType" ; + rdfs:subClassOf sysml:Classifier . + + sysml:DecisionNode + a rdfs:Class ; + rdfs:label "DecisionNode" ; + rdfs:subClassOf sysml:ControlNode . + + sysml:Definition + a rdfs:Class ; + rdfs:label "Definition" ; + rdfs:subClassOf sysml:Classifier . + + sysml:Dependency + a rdfs:Class ; + rdfs:label "Dependency" ; + rdfs:subClassOf sysml:Relationship . + + sysml:Differencing + a rdfs:Class ; + rdfs:label "Differencing" ; + rdfs:subClassOf sysml:Relationship . + + sysml:Disjoining + a rdfs:Class ; + rdfs:label "Disjoining" ; + rdfs:subClassOf sysml:Relationship . + + sysml:Documentation + a rdfs:Class ; + rdfs:label "Documentation" ; + rdfs:subClassOf sysml:Comment . + + sysml:Element + a rdfs:Class ; + rdfs:label "Element" ; + sysx:abstract "true"^^xsd:boolean . + + sysml:ElementFilterMembership + a rdfs:Class ; + rdfs:label "ElementFilterMembership" ; + rdfs:subClassOf sysml:OwningMembership . + + sysml:EndFeatureMembership + a rdfs:Class ; + rdfs:label "EndFeatureMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:EnumerationDefinition + a rdfs:Class ; + rdfs:label "EnumerationDefinition" ; + rdfs:subClassOf sysml:AttributeDefinition . + + sysml:EnumerationUsage + a rdfs:Class ; + rdfs:label "EnumerationUsage" ; + rdfs:subClassOf sysml:AttributeUsage . + + sysml:EventOccurrenceUsage + a rdfs:Class ; + rdfs:label "EventOccurrenceUsage" ; + rdfs:subClassOf sysml:OccurrenceUsage . + + sysml:ExhibitStateUsage + a rdfs:Class ; + rdfs:label "ExhibitStateUsage" ; + rdfs:subClassOf sysml:PerformActionUsage, sysml:StateUsage . + + sysml:Expose + a rdfs:Class ; + rdfs:label "Expose" ; + rdfs:subClassOf sysml:Import ; + sysx:abstract "true"^^xsd:boolean . + + sysml:Expression + a rdfs:Class ; + rdfs:label "Expression" ; + rdfs:subClassOf sysml:Step . + + sysml:Feature + a rdfs:Class ; + rdfs:label "Feature" ; + rdfs:subClassOf sysml:Type . + + sysml:FeatureChainExpression + a rdfs:Class ; + rdfs:label "FeatureChainExpression" ; + rdfs:subClassOf sysml:OperatorExpression . + + sysml:FeatureChaining + a rdfs:Class ; + rdfs:label "FeatureChaining" ; + rdfs:subClassOf sysml:Relationship . + + sysml:FeatureInverting + a rdfs:Class ; + rdfs:label "FeatureInverting" ; + rdfs:subClassOf sysml:Relationship . + + sysml:FeatureMembership + a rdfs:Class ; + rdfs:label "FeatureMembership" ; + rdfs:subClassOf sysml:OwningMembership . + + sysml:FeatureReferenceExpression + a rdfs:Class ; + rdfs:label "FeatureReferenceExpression" ; + rdfs:subClassOf sysml:Expression . + + sysml:FeatureTyping + a rdfs:Class ; + rdfs:label "FeatureTyping" ; + rdfs:subClassOf sysml:Specialization . + + sysml:FeatureValue + a rdfs:Class ; + rdfs:label "FeatureValue" ; + rdfs:subClassOf sysml:OwningMembership . + + sysml:Flow + a rdfs:Class ; + rdfs:label "Flow" ; + rdfs:subClassOf sysml:Connector, sysml:Step . + + sysml:FlowDefinition + a rdfs:Class ; + rdfs:label "FlowDefinition" ; + rdfs:subClassOf sysml:ActionDefinition, sysml:Interaction . + + sysml:FlowEnd + a rdfs:Class ; + rdfs:label "FlowEnd" ; + rdfs:subClassOf sysml:Feature . + + sysml:FlowUsage + a rdfs:Class ; + rdfs:label "FlowUsage" ; + rdfs:subClassOf sysml:ActionUsage, sysml:ConnectorAsUsage, sysml:Flow . + + sysml:ForLoopActionUsage + a rdfs:Class ; + rdfs:label "ForLoopActionUsage" ; + rdfs:subClassOf sysml:LoopActionUsage . + + sysml:ForkNode + a rdfs:Class ; + rdfs:label "ForkNode" ; + rdfs:subClassOf sysml:ControlNode . + + sysml:FramedConcernMembership + a rdfs:Class ; + rdfs:label "FramedConcernMembership" ; + rdfs:subClassOf sysml:RequirementConstraintMembership . + + sysml:Function + a rdfs:Class ; + rdfs:label "Function" ; + rdfs:subClassOf sysml:Behavior . + + sysml:IfActionUsage + a rdfs:Class ; + rdfs:label "IfActionUsage" ; + rdfs:subClassOf sysml:ActionUsage . + + sysml:Import + a rdfs:Class ; + rdfs:label "Import" ; + rdfs:subClassOf sysml:Relationship ; + sysx:abstract "true"^^xsd:boolean . + + sysml:IncludeUseCaseUsage + a rdfs:Class ; + rdfs:label "IncludeUseCaseUsage" ; + rdfs:subClassOf sysml:PerformActionUsage, sysml:UseCaseUsage . + + sysml:IndexExpression + a rdfs:Class ; + rdfs:label "IndexExpression" ; + rdfs:subClassOf sysml:OperatorExpression . + + sysml:InstantiationExpression + a rdfs:Class ; + rdfs:label "InstantiationExpression" ; + rdfs:subClassOf sysml:Expression ; + sysx:abstract "true"^^xsd:boolean . + + sysml:Interaction + a rdfs:Class ; + rdfs:label "Interaction" ; + rdfs:subClassOf sysml:Association, sysml:Behavior . + + sysml:InterfaceDefinition + a rdfs:Class ; + rdfs:label "InterfaceDefinition" ; + rdfs:subClassOf sysml:ConnectionDefinition . + + sysml:InterfaceUsage + a rdfs:Class ; + rdfs:label "InterfaceUsage" ; + rdfs:subClassOf sysml:ConnectionUsage . + + sysml:Intersecting + a rdfs:Class ; + rdfs:label "Intersecting" ; + rdfs:subClassOf sysml:Relationship . + + sysml:Invariant + a rdfs:Class ; + rdfs:label "Invariant" ; + rdfs:subClassOf sysml:BooleanExpression . + + sysml:InvocationExpression + a rdfs:Class ; + rdfs:label "InvocationExpression" ; + rdfs:subClassOf sysml:InstantiationExpression . + + sysml:ItemDefinition + a rdfs:Class ; + rdfs:label "ItemDefinition" ; + rdfs:subClassOf sysml:OccurrenceDefinition, sysml:Structure . + + sysml:ItemUsage + a rdfs:Class ; + rdfs:label "ItemUsage" ; + rdfs:subClassOf sysml:OccurrenceUsage . + + sysml:JoinNode + a rdfs:Class ; + rdfs:label "JoinNode" ; + rdfs:subClassOf sysml:ControlNode . + + sysml:LibraryPackage + a rdfs:Class ; + rdfs:label "LibraryPackage" ; + rdfs:subClassOf sysml:Package . + + sysml:LiteralBoolean + a rdfs:Class ; + rdfs:label "LiteralBoolean" ; + rdfs:subClassOf sysml:LiteralExpression . + + sysml:LiteralExpression + a rdfs:Class ; + rdfs:label "LiteralExpression" ; + rdfs:subClassOf sysml:Expression . + + sysml:LiteralInfinity + a rdfs:Class ; + rdfs:label "LiteralInfinity" ; + rdfs:subClassOf sysml:LiteralExpression . + + sysml:LiteralInteger + a rdfs:Class ; + rdfs:label "LiteralInteger" ; + rdfs:subClassOf sysml:LiteralExpression . + + sysml:LiteralRational + a rdfs:Class ; + rdfs:label "LiteralRational" ; + rdfs:subClassOf sysml:LiteralExpression . + + sysml:LiteralString + a rdfs:Class ; + rdfs:label "LiteralString" ; + rdfs:subClassOf sysml:LiteralExpression . + + sysml:LoopActionUsage + a rdfs:Class ; + rdfs:label "LoopActionUsage" ; + rdfs:subClassOf sysml:ActionUsage ; + sysx:abstract "true"^^xsd:boolean . + + sysml:Membership + a rdfs:Class ; + rdfs:label "Membership" ; + rdfs:subClassOf sysml:Relationship . + + sysml:MembershipExpose + a rdfs:Class ; + rdfs:label "MembershipExpose" ; + rdfs:subClassOf sysml:Expose, sysml:MembershipImport . + + sysml:MembershipImport + a rdfs:Class ; + rdfs:label "MembershipImport" ; + rdfs:subClassOf sysml:Import . + + sysml:MergeNode + a rdfs:Class ; + rdfs:label "MergeNode" ; + rdfs:subClassOf sysml:ControlNode . + + sysml:Metaclass + a rdfs:Class ; + rdfs:label "Metaclass" ; + rdfs:subClassOf sysml:Structure . + + sysml:MetadataAccessExpression + a rdfs:Class ; + rdfs:label "MetadataAccessExpression" ; + rdfs:subClassOf sysml:Expression . + + sysml:MetadataDefinition + a rdfs:Class ; + rdfs:label "MetadataDefinition" ; + rdfs:subClassOf sysml:ItemDefinition, sysml:Metaclass . + + sysml:MetadataFeature + a rdfs:Class ; + rdfs:label "MetadataFeature" ; + rdfs:subClassOf sysml:AnnotatingElement, sysml:Feature . + + sysml:MetadataUsage + a rdfs:Class ; + rdfs:label "MetadataUsage" ; + rdfs:subClassOf sysml:ItemUsage, sysml:MetadataFeature . + + sysml:Multiplicity + a rdfs:Class ; + rdfs:label "Multiplicity" ; + rdfs:subClassOf sysml:Feature . + + sysml:MultiplicityRange + a rdfs:Class ; + rdfs:label "MultiplicityRange" ; + rdfs:subClassOf sysml:Multiplicity . + + sysml:Namespace + a rdfs:Class ; + rdfs:label "Namespace" ; + rdfs:subClassOf sysml:Element . + + sysml:NamespaceExpose + a rdfs:Class ; + rdfs:label "NamespaceExpose" ; + rdfs:subClassOf sysml:Expose, sysml:NamespaceImport . + + sysml:NamespaceImport + a rdfs:Class ; + rdfs:label "NamespaceImport" ; + rdfs:subClassOf sysml:Import . + + sysml:NullExpression + a rdfs:Class ; + rdfs:label "NullExpression" ; + rdfs:subClassOf sysml:Expression . + + sysml:ObjectiveMembership + a rdfs:Class ; + rdfs:label "ObjectiveMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:OccurrenceDefinition + a rdfs:Class ; + rdfs:label "OccurrenceDefinition" ; + rdfs:subClassOf sysml:Class, sysml:Definition . + + sysml:OccurrenceUsage + a rdfs:Class ; + rdfs:label "OccurrenceUsage" ; + rdfs:subClassOf sysml:Usage . + + sysml:OperatorExpression + a rdfs:Class ; + rdfs:label "OperatorExpression" ; + rdfs:subClassOf sysml:InvocationExpression . + + sysml:OwningMembership + a rdfs:Class ; + rdfs:label "OwningMembership" ; + rdfs:subClassOf sysml:Membership . + + sysml:Package + a rdfs:Class ; + rdfs:label "Package" ; + rdfs:subClassOf sysml:Namespace . + + sysml:ParameterMembership + a rdfs:Class ; + rdfs:label "ParameterMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:PartDefinition + a rdfs:Class ; + rdfs:label "PartDefinition" ; + rdfs:subClassOf sysml:ItemDefinition . + + sysml:PartUsage + a rdfs:Class ; + rdfs:label "PartUsage" ; + rdfs:subClassOf sysml:ItemUsage . + + sysml:PayloadFeature + a rdfs:Class ; + rdfs:label "PayloadFeature" ; + rdfs:subClassOf sysml:Feature . + + sysml:PerformActionUsage + a rdfs:Class ; + rdfs:label "PerformActionUsage" ; + rdfs:subClassOf sysml:ActionUsage, sysml:EventOccurrenceUsage . + + sysml:PortConjugation + a rdfs:Class ; + rdfs:label "PortConjugation" ; + rdfs:subClassOf sysml:Conjugation . + + sysml:PortDefinition + a rdfs:Class ; + rdfs:label "PortDefinition" ; + rdfs:subClassOf sysml:OccurrenceDefinition, sysml:Structure . + + sysml:PortUsage + a rdfs:Class ; + rdfs:label "PortUsage" ; + rdfs:subClassOf sysml:OccurrenceUsage . + + sysml:Predicate + a rdfs:Class ; + rdfs:label "Predicate" ; + rdfs:subClassOf sysml:Function . + + sysml:Redefinition + a rdfs:Class ; + rdfs:label "Redefinition" ; + rdfs:subClassOf sysml:Subsetting . + + sysml:ReferenceSubsetting + a rdfs:Class ; + rdfs:label "ReferenceSubsetting" ; + rdfs:subClassOf sysml:Subsetting . + + sysml:ReferenceUsage + a rdfs:Class ; + rdfs:label "ReferenceUsage" ; + rdfs:subClassOf sysml:Usage . + + sysml:Relationship + a rdfs:Class ; + rdfs:label "Relationship" ; + rdfs:subClassOf sysml:Element ; + sysx:abstract "true"^^xsd:boolean . + + sysml:RenderingDefinition + a rdfs:Class ; + rdfs:label "RenderingDefinition" ; + rdfs:subClassOf sysml:PartDefinition . + + sysml:RenderingUsage + a rdfs:Class ; + rdfs:label "RenderingUsage" ; + rdfs:subClassOf sysml:PartUsage . + + sysml:RequirementConstraintMembership + a rdfs:Class ; + rdfs:label "RequirementConstraintMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:RequirementDefinition + a rdfs:Class ; + rdfs:label "RequirementDefinition" ; + rdfs:subClassOf sysml:ConstraintDefinition . + + sysml:RequirementUsage + a rdfs:Class ; + rdfs:label "RequirementUsage" ; + rdfs:subClassOf sysml:ConstraintUsage . + + sysml:RequirementVerificationMembership + a rdfs:Class ; + rdfs:label "RequirementVerificationMembership" ; + rdfs:subClassOf sysml:RequirementConstraintMembership . + + sysml:ResultExpressionMembership + a rdfs:Class ; + rdfs:label "ResultExpressionMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:ReturnParameterMembership + a rdfs:Class ; + rdfs:label "ReturnParameterMembership" ; + rdfs:subClassOf sysml:ParameterMembership . + + sysml:SatisfyRequirementUsage + a rdfs:Class ; + rdfs:label "SatisfyRequirementUsage" ; + rdfs:subClassOf sysml:AssertConstraintUsage, sysml:RequirementUsage . + + sysml:SelectExpression + a rdfs:Class ; + rdfs:label "SelectExpression" ; + rdfs:subClassOf sysml:OperatorExpression . + + sysml:SendActionUsage + a rdfs:Class ; + rdfs:label "SendActionUsage" ; + rdfs:subClassOf sysml:ActionUsage . + + sysml:Specialization + a rdfs:Class ; + rdfs:label "Specialization" ; + rdfs:subClassOf sysml:Relationship . + + sysml:StakeholderMembership + a rdfs:Class ; + rdfs:label "StakeholderMembership" ; + rdfs:subClassOf sysml:ParameterMembership . + + sysml:StateDefinition + a rdfs:Class ; + rdfs:label "StateDefinition" ; + rdfs:subClassOf sysml:ActionDefinition . + + sysml:StateSubactionMembership + a rdfs:Class ; + rdfs:label "StateSubactionMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:StateUsage + a rdfs:Class ; + rdfs:label "StateUsage" ; + rdfs:subClassOf sysml:ActionUsage . + + sysml:Step + a rdfs:Class ; + rdfs:label "Step" ; + rdfs:subClassOf sysml:Feature . + + sysml:Structure + a rdfs:Class ; + rdfs:label "Structure" ; + rdfs:subClassOf sysml:Class . + + sysml:Subclassification + a rdfs:Class ; + rdfs:label "Subclassification" ; + rdfs:subClassOf sysml:Specialization . + + sysml:SubjectMembership + a rdfs:Class ; + rdfs:label "SubjectMembership" ; + rdfs:subClassOf sysml:ParameterMembership . + + sysml:Subsetting + a rdfs:Class ; + rdfs:label "Subsetting" ; + rdfs:subClassOf sysml:Specialization . + + sysml:Succession + a rdfs:Class ; + rdfs:label "Succession" ; + rdfs:subClassOf sysml:Connector . + + sysml:SuccessionAsUsage + a rdfs:Class ; + rdfs:label "SuccessionAsUsage" ; + rdfs:subClassOf sysml:ConnectorAsUsage, sysml:Succession . + + sysml:SuccessionFlow + a rdfs:Class ; + rdfs:label "SuccessionFlow" ; + rdfs:subClassOf sysml:Flow, sysml:Succession . + + sysml:SuccessionFlowUsage + a rdfs:Class ; + rdfs:label "SuccessionFlowUsage" ; + rdfs:subClassOf sysml:FlowUsage, sysml:SuccessionFlow . + + sysml:TerminateActionUsage + a rdfs:Class ; + rdfs:label "TerminateActionUsage" ; + rdfs:subClassOf sysml:ActionUsage . + + sysml:TextualRepresentation + a rdfs:Class ; + rdfs:label "TextualRepresentation" ; + rdfs:subClassOf sysml:AnnotatingElement . + + sysml:TransitionFeatureMembership + a rdfs:Class ; + rdfs:label "TransitionFeatureMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:TransitionUsage + a rdfs:Class ; + rdfs:label "TransitionUsage" ; + rdfs:subClassOf sysml:ActionUsage . + + sysml:TriggerInvocationExpression + a rdfs:Class ; + rdfs:label "TriggerInvocationExpression" ; + rdfs:subClassOf sysml:InvocationExpression . + + sysml:Type + a rdfs:Class ; + rdfs:label "Type" ; + rdfs:subClassOf sysml:Namespace . + + sysml:TypeFeaturing + a rdfs:Class ; + rdfs:label "TypeFeaturing" ; + rdfs:subClassOf sysml:Relationship . + + sysml:Unioning + a rdfs:Class ; + rdfs:label "Unioning" ; + rdfs:subClassOf sysml:Relationship . + + sysml:Usage + a rdfs:Class ; + rdfs:label "Usage" ; + rdfs:subClassOf sysml:Feature . + + sysml:UseCaseDefinition + a rdfs:Class ; + rdfs:label "UseCaseDefinition" ; + rdfs:subClassOf sysml:CaseDefinition . + + sysml:UseCaseUsage + a rdfs:Class ; + rdfs:label "UseCaseUsage" ; + rdfs:subClassOf sysml:CaseUsage . + + sysml:VariantMembership + a rdfs:Class ; + rdfs:label "VariantMembership" ; + rdfs:subClassOf sysml:OwningMembership . + + sysml:VerificationCaseDefinition + a rdfs:Class ; + rdfs:label "VerificationCaseDefinition" ; + rdfs:subClassOf sysml:CaseDefinition . + + sysml:VerificationCaseUsage + a rdfs:Class ; + rdfs:label "VerificationCaseUsage" ; + rdfs:subClassOf sysml:CaseUsage . + + sysml:ViewDefinition + a rdfs:Class ; + rdfs:label "ViewDefinition" ; + rdfs:subClassOf sysml:PartDefinition . + + sysml:ViewRenderingMembership + a rdfs:Class ; + rdfs:label "ViewRenderingMembership" ; + rdfs:subClassOf sysml:FeatureMembership . + + sysml:ViewUsage + a rdfs:Class ; + rdfs:label "ViewUsage" ; + rdfs:subClassOf sysml:PartUsage . + + sysml:ViewpointDefinition + a rdfs:Class ; + rdfs:label "ViewpointDefinition" ; + rdfs:subClassOf sysml:RequirementDefinition . + + sysml:ViewpointUsage + a rdfs:Class ; + rdfs:label "ViewpointUsage" ; + rdfs:subClassOf sysml:RequirementUsage . + + sysml:WhileLoopActionUsage + a rdfs:Class ; + rdfs:label "WhileLoopActionUsage" ; + rdfs:subClassOf sysml:LoopActionUsage . +} diff --git a/SySML2.NET.REST.Tests/SySML2.NET.REST.Tests.csproj b/SySML2.NET.REST.Tests/SySML2.NET.REST.Tests.csproj index 3ae9fbe84..a3e6186a6 100644 --- a/SySML2.NET.REST.Tests/SySML2.NET.REST.Tests.csproj +++ b/SySML2.NET.REST.Tests/SySML2.NET.REST.Tests.csproj @@ -18,6 +18,7 @@ + @@ -25,6 +26,7 @@ + @@ -36,10 +38,14 @@ + + + + diff --git a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md new file mode 100644 index 000000000..b7571881c --- /dev/null +++ b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md @@ -0,0 +1,167 @@ +# SySML2.NET.REST.Tests — project structure + +This page describes how the test project of the REST client `SySML2.NET.REST` is organised. It is written to be moved to the project wiki. + +The project holds two kinds of tests: + +| Kind | Needs | Runs in CI | What it verifies | +|---|---|---|---| +| **Offline tests** | nothing | yes | The client, the session and the test infrastructure itself, against mocked HTTP answers and recorded JSON. | +| **Integration scenario** (`[Category("Integration")]`) | Docker | no | The client against a live Flexo MMS SysML v2 server. A complete model is built step by step and every write is read back. | + +The integration scenario verifies **our client**, not Flexo. Its measure is the OpenAPI document of the Systems Modeling API and Services specification (`Resources/ptc-25-02-30.json`): every request and response is checked against it. Where Flexo answers differently, the scenario reports a named warning instead of failing. Client defects are not fixed while the scenario is built: each gets a GitHub issue and its check stays red, so the scenario is the fixture the client is fixed against later. The plan behind the scenario is `SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md`. + +## Layout + +``` +SySML2.NET.REST.Tests/ +├── PsmApiClientTestFixture.cs offline: every client operation against MockHttp +├── SessionTestFixture.cs offline: Session against recorded JSON +├── QueryStringBuilderTestFixture.cs offline: query string building +├── Exceptions/ offline: PsmApiException, MergeConflictException +├── Helpers/ the scenario's infrastructure (no tests) +│ ├── FlexoTestHost.cs, FlexoJwt.cs, ModelBuilder.cs, … see below +│ └── Models/ the model each step commits +│ └── RootModel.cs step 2 +├── HelpersTests/ offline: one fixture per helper, mirroring Helpers/ +│ ├── FlexoJwtTestFixture.cs, ModelBuilderTestFixture.cs, … +│ └── Models/RootModelTestFixture.cs +├── IntegrationTests/ needs Docker +│ └── FlexoModelScenarioTestFixture.cs the scenario: one [Test] per step +├── Resources/Flexo/cluster.trig Flexo's initial quad-store content (Apache-2.0, see NOTICE) +├── INTEGRATION_TEST_PLAN.md the scenario plan +└── TEST_PROJECT_STRUCTURE.md this page +``` + +| Folder | Namespace | Contains | +|---|---|---| +| `Helpers/` | `SySML2.NET.REST.Tests.Helpers` | Helper types only. No `[TestFixture]`. | +| `Helpers/Models/` | `SySML2.NET.REST.Tests.Helpers.Models` | One model class per scenario step. | +| `HelpersTests/` | `SySML2.NET.REST.Tests.HelpersTests` (and `.Models`) | The offline fixtures of the helpers, one per helper type. They run in CI. | +| `IntegrationTests/` | `SySML2.NET.REST.Tests.IntegrationTests` | The fixtures marked `[Category("Integration")]`, which need a live server. | + +Files linked from elsewhere in the repository and copied to the output folder: + +| Output path | Source | Used by | +|---|---|---| +| `Data/*.json` | `SysML2.NET.Serializer.Json.Tests/Data/` | `SessionTestFixture` | +| `Resources/ptc-25-02-30.json` | `Resources/ptc-25-02-30.json` (the normative OpenAPI document) | `OpenApiPathTemplates`, `CoverageVerdict` | + +Every helper type with behaviour has its own offline fixture in `HelpersTests/`. A bug in a helper therefore shows up in CI, not as a confusing result in a Docker run. The exceptions are `FlexoTestHost`, which needs Docker and is exercised by the scenario itself, and the plain data types `ContractViolation`, `ContractViolationKind`, `MetamodelProperty`, `ScenarioState` and `ServerDivergence`, which the fixtures of their users cover. + +## Helpers + +The types fall into six groups. + +### 1. Server host + +| Type | Responsibility | +|---|---| +| `FlexoTestHost` | Starts Flexo in Docker with Testcontainers. On one network it starts, in order: Fuseki (the quad store, seeded with `cluster.trig`), the Flexo layer1 service, then the Flexo SysML v2 service, each image pinned by digest. Before that last start, it creates the `sysmlv2` organisation on layer1. If Docker is unreachable, the fixture is **ignored**. Any later start-up failure **fails** the run, with the container logs attached. | +| `FlexoJwt` | Creates the HS256 tokens layer1 accepts. The signing secret is random per run, so no secret is stored in source. | + +### 2. HTTP wiring + +The `Session` under test gets its `HttpClient` from `IntegrationHttpClientFactory`. All clients share one handler chain: + +``` +Session → PsmApiClient → HttpClient + └─ BearerTokenHandler adds "Authorization: Bearer " + └─ EndpointRecorder records (operation, status), checks request and response + against the OpenAPI document, flags empty GUIDs in bodies + └─ HttpClientHandler → Flexo +``` + +| Type | Responsibility | +|---|---| +| `IntegrationHttpClientFactory` | `IHttpClientFactory` that hands out clients over the shared chain. The chain is disposed once, at the end of the fixture. | +| `BearerTokenHandler` | Adds the bearer token, because `Session` has no authentication option of its own. | +| `EndpointRecorder` | Records every request as an `EndpointCall`: the OpenAPI operation it matched, the request line, the status, and how the request and the response break the document. It buffers the response body, so the client still reads it. It also collects request bodies that reference `00000000-0000-0000-0000-000000000000`. | +| `EndpointCall` | One recorded request, with its `RequestViolations` (client defects) and `ResponseViolations` (server divergences). | + +### 3. The OpenAPI contract + +| Type | Responsibility | +|---|---| +| `OpenApiDocument` | Reads the OpenAPI 3.1 document as JSON Schema 2020-12, with JsonSchema.Net, and matches a request path to its operation. When templates overlap, the one with the most literal segments wins. It removes the `$id`s of the component schemas and makes every reference absolute, because the document references its schemas both by JSON pointer and by those `$id`s. | +| `OpenApiOperation` | One operation: its parameters, request body and responses. `CheckRequest` checks the query and the body a client sends; `CheckResponse` checks the status and the body a server answers. | +| `OpenApiParameter`, `OpenApiContent` | A declared parameter, and a declared body (a schema per media type). They check one value or one body; schema errors are summarized to the branch whose `@type` matched. | +| `ContractViolation`, `ContractViolationKind` | One way a request or a response breaks the document, by kind, so a known divergence can match it. | +| `OpenApiConformance` | After each step: fails on any request violation; reports a response violation as the known divergence that explains it, or fails. | + +### 4. Building the model + +| Type | Responsibility | +|---|---| +| `ModelBuilder` | Creates POCOs with deterministic ids; the step wires them with `AssignOwnership`. Once the step is complete, they are converted with the Dal's `ToDto(includeDerivedProperties: true)` and turned into a `CommitRequest`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | +| `DeterministicGuid` | Name-based UUID v5 of `"/"`, so the elements have the same ids in every run. | +| `Models/*` | One class per step, describing the model that step commits (for example `RootModel` for step 2). | + +### 5. Checking what came back + +| Type | Responsibility | +|---|---| +| `ScenarioState` | What the steps hand on to each other: the ids the server assigned (project, branch, commits), the expected model at each commit, and everything the server returned. | +| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, every element by id, paged element reads, roots (the elements without an `owner`), relationships, the member element and name of every membership, and that no returned DTO holds an empty GUID. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. | +| `KnownServerDivergences`, `ServerDivergence` | The named ways Flexo diverges from the specification, each with a reference: an upstream issue, or a Flexo source location at the pinned commit. A divergence can explain response violations. `Report` raises an `Assert.Warn`. `ExpectNotFoundAsync` expects a 404, tolerates one named divergence, and fails when a conforming 404 reaches the caller without its `Error`. | +| `IsolatedAssertions` | Runs a check in an isolated NUnit context and returns its failures and warnings, without failing the calling test. The offline fixtures use it to prove that a check fails when it should. | + +### 6. Coverage verdict + +| Type | Responsibility | +|---|---| +| `CoverageVerdict` | Lists what the scenario has not yet exercised: concrete metaclasses never sent; non-derived properties never set to a non-default value, or never changed; enumeration literals never used; OpenAPI operations never answered with a 2xx and with a 4xx. A 5xx answer does not count as coverage. | +| `DtoMetadata`, `MetamodelProperty` | Read the metaclasses and properties from the `[Class]`/`[Property]` decorators on the generated DTOs, so the lists keep up with the generator. | + +## The scenario + +`FlexoModelScenarioTestFixture` is one ordered scenario: + +- `[OneTimeSetUp]` starts `FlexoTestHost` and opens a `Session` over the factory. +- `[TearDown]` runs `OpenApiConformance` over the calls of the step that just ran. +- Each step is its own `[Test]`. The steps are ordered with `[DependsOnTest(previous, AllowFailure = true)]`: a failed step does not stop the next one. A step is skipped only when state it needs is missing (for example, no project was created). +- The last test, `VerifyCoverage`, always runs and prints the coverage verdict. It stays red until the scenario covers everything. +- `[OneTimeTearDown]` closes the session and disposes the handler chain and the containers. +- Starting the host has a 15-minute timeout. + +Having one `[Test]` per step goes against the one-test-per-method rule in `TESTING.md`. This is accepted for this scenario only (see plan §9). + +| Step | Test | Status | +|---|---|---| +| 1 | `VerifyEmptyServer` | implemented | +| 2 | `VerifyProjectAndRootModel` | implemented | +| 3–13 | see plan §5 | planned | +| 14 | `VerifyCoverage` | implemented, red by design | + +### Reading the outcome + +| Outcome | Meaning | +|---|---| +| Passed | Every check held. | +| Warning (the VSTest console shows it as **Skipped**) | Every check held, but Flexo showed one or more known divergences. The message names each divergence and its reference. | +| Failed | A check failed. Either the client is at fault, or Flexo diverges in a way not yet in `KnownServerDivergences`. | +| Ignored | Docker was not reachable. | + +## Running the tests + +```bash +# offline tests only (what CI runs) +dotnet test SySML2.NET.REST.Tests/SySML2.NET.REST.Tests.csproj --filter "TestCategory!=Integration" + +# the Flexo scenario (Docker must be running) +dotnet test SySML2.NET.REST.Tests/SySML2.NET.REST.Tests.csproj --filter "TestCategory=Integration" --logger "console;verbosity=detailed" +``` + +The Docker endpoint is taken from `DOCKER_HOST`, and otherwise, on Windows, from the Docker Desktop Linux engine pipe (`npipe://./pipe/dockerDesktopLinuxEngine`). + +## Extending the scenario + +To add a step: + +1. Add a model class under `Helpers/Models/` that builds the step's elements with `ModelBuilder`, and its offline fixture under `HelpersTests/Models/`. +2. Add a `[Test]` to `IntegrationTests/FlexoModelScenarioTestFixture.cs` that depends on the previous step with `AllowFailure = true`, commits the model, and calls `ReadBackAssertions`. +3. Make `VerifyCoverage` depend on the new last step. +4. When Flexo diverges, add an entry to `KnownServerDivergences` with its reference, and list it under "Observed" in plan §8. +5. Check the coverage verdict output: the step should remove items from it. + +Fixture rules (`TESTING.md`, `DEVELOPMENT_STANDARDS.md`) apply to every file here, with the one exception noted above. From 2cd1694fe9ccd2938647da3a35c6c3aa9d11fb99 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Sat, 7 Nov 2026 23:26:18 +0100 Subject: [PATCH 04/11] =?UTF-8?q?[Add]=20Flexo=20integration=20scenario=20?= =?UTF-8?q?stage=202:=20KerML=20Core,=20Kernel=20and=20update=20steps=203?= =?UTF-8?q?=E2=80=935=20(#407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Helpers/EndpointRecorder.cs | 25 + .../Helpers/KnownServerDivergences.cs | 22 +- SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs | 159 +++- .../Helpers/Models/CoreModel.cs | 216 ++++++ .../Helpers/Models/KerMLUpdateModel.cs | 285 +++++++ .../Helpers/Models/KernelModel.cs | 716 ++++++++++++++++++ .../Helpers/Models/RootModel.cs | 59 +- .../Helpers/Models/StepModel.cs | 117 +++ .../Helpers/OpenApiContent.cs | 94 ++- .../Helpers/OpenApiDocument.cs | 128 +++- .../Helpers/ReadBackAssertions.cs | 323 ++++++-- .../Helpers/ScenarioState.cs | 5 + .../Helpers/ServerDivergence.cs | 6 +- .../EndpointRecorderTestFixture.cs | 4 + .../KnownServerDivergencesTestFixture.cs | 18 +- .../HelpersTests/ModelBuilderTestFixture.cs | 94 +++ .../Models/CoreModelTestFixture.cs | 65 ++ .../Models/KerMLUpdateModelTestFixture.cs | 155 ++++ .../Models/KernelModelTestFixture.cs | 78 ++ .../Models/RootModelTestFixture.cs | 1 + .../HelpersTests/OpenApiContentTestFixture.cs | 29 + .../OpenApiDocumentTestFixture.cs | 65 ++ .../ReadBackAssertionsTestFixture.cs | 191 ++++- .../INTEGRATION_TEST_PLAN.md | 50 +- .../FlexoModelScenarioTestFixture.cs | 142 +++- .../TEST_PROJECT_STRUCTURE.md | 32 +- 26 files changed, 2911 insertions(+), 168 deletions(-) create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/KernelModelTestFixture.cs diff --git a/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs b/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs index fdc971b4b..7e3314187 100644 --- a/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs +++ b/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs @@ -12,6 +12,7 @@ namespace SySML2.NET.REST.Tests.Helpers using System; using System.Collections.Concurrent; using System.Collections.Generic; + using System.Diagnostics; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -43,6 +44,16 @@ public sealed class EndpointRecorder : DelegatingHandler /// private readonly ConcurrentQueue emptyGuidRequests = new(); + /// + /// The time spent waiting for the server, in ticks + /// + private long serverTicks; + + /// + /// The time spent checking requests and responses against the OpenAPI document, in ticks + /// + private long checkTicks; + /// /// Initializes a new instance of the class /// @@ -72,6 +83,16 @@ public EndpointRecorder(OpenApiDocument openApi, HttpMessageHandler innerHandler /// public EndpointCall LastCall { get; private set; } + /// + /// Gets the time spent waiting for the server + /// + public TimeSpan ServerTime => TimeSpan.FromTicks(Interlocked.Read(ref this.serverTicks)); + + /// + /// Gets the time spent checking requests and responses against the OpenAPI document + /// + public TimeSpan CheckTime => TimeSpan.FromTicks(Interlocked.Read(ref this.checkTicks)); + /// /// Sends the request on, and records the operation it addressed, the status it was answered with, and how the /// request and the response break the OpenAPI document @@ -101,11 +122,14 @@ protected override async Task SendAsync(HttpRequestMessage } } + var server = Stopwatch.StartNew(); var response = await base.SendAsync(request, cancellationToken); await response.Content.LoadIntoBufferAsync(cancellationToken); var responseBody = await response.Content.ReadAsStringAsync(cancellationToken); + Interlocked.Add(ref this.serverTicks, server.Elapsed.Ticks); + var check = Stopwatch.StartNew(); var operation = this.openApi.Match(request.Method, request.RequestUri?.AbsolutePath ?? string.Empty); var call = new EndpointCall(operation, requestLine, response.StatusCode) @@ -114,6 +138,7 @@ protected override async Task SendAsync(HttpRequestMessage ResponseViolations = operation?.CheckResponse(response.StatusCode, response.Content.Headers.ContentType?.MediaType, responseBody) ?? [] }; + Interlocked.Add(ref this.checkTicks, check.Elapsed.Ticks); this.calls.Enqueue(call); this.LastCall = call; diff --git a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs index ae4845364..65a03756f 100644 --- a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs +++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs @@ -51,6 +51,11 @@ public static class KnownServerDivergences /// private static readonly Regex NullList = new(@"^\S* type: Value is ""null"" but should be ""array""$", RegexOptions.Compiled); + /// + /// Matches a schema error on a previousCommit sent as one object + /// + private static readonly Regex PreviousCommitObject = new(@"^\S*/previousCommit type: Value is ""object"" but should be ""array""$", RegexOptions.Compiled); + /// /// Gets the divergence that the roots are the elements without an owningRelatedElement, owned through /// an owningRelationship or not, where Clause 7.2.2 makes them the elements without an owner @@ -78,6 +83,11 @@ public static class KnownServerDivergences $"{FlexoRevision}, layer1 Http404Exception and the meta datatypes route", (call, violation) => (int)call.StatusCode >= 400 && violation.Kind is ContractViolationKind.UnexpectedBody or ContractViolationKind.UndeclaredMediaType); + /// + /// Gets the divergence that the diff of two commits is not implemented + /// + public static ServerDivergence DiffNotImplemented { get; } = new("GET /projects/{projectId}/commits/{compareCommitId}/diff answers 501 Not Implemented", $"{FlexoRevision}, observed on GET /projects/{{projectId}}/commits/{{compareCommitId}}/diff"); + /// /// Gets the divergence that a create answers 200 OK, where the OpenAPI document declares 201 Created and no 200 /// @@ -95,6 +105,16 @@ public static class KnownServerDivergences $"{FlexoRevision}, observed on every project, branch, commit and change read", (_, violation) => violation.Kind == ContractViolationKind.SchemaMismatch && (NullList.IsMatch(violation.Message) || MissingNames(violation) is { Count: > 0 } names && names.All(OmittedRecordProperties.Contains))); + /// + /// Gets the divergence that a commit with one previous commit sends previousCommit as that one object, + /// where the OpenAPI document declares an array + /// + public static ServerDivergence PreviousCommitAsObject { get; } = new( + "a commit with one previous commit sends previousCommit as an object instead of an array", + $"{FlexoRevision}, observed on GET /projects/{{projectId}}/commits/{{commitId}} and GET /projects/{{projectId}}/commits", + (_, violation) => violation.Kind == ContractViolationKind.SchemaMismatch && PreviousCommitObject.IsMatch(violation.Message), + BreaksDeserialization: true); + /// /// Gets the divergence that elements are returned without their derived properties, which the response schemas /// of the OpenAPI document require @@ -115,7 +135,7 @@ public static class KnownServerDivergences /// /// Gets every known divergence /// - public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, ElementsWithoutDerivedProperties, DatatypeIdNotUri]; + public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri]; /// /// Asserts that a call for an unknown resource fails with 404 Not Found, or reports the one tolerated divergence diff --git a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs index 5e54c1553..2074a00d6 100644 --- a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs +++ b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs @@ -10,45 +10,92 @@ namespace SySML2.NET.REST.Tests.Helpers { using System; + using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; + using System.Reflection; + using SysML2.NET.Extensions.Core.DTO.Comparers; using SysML2.NET.PSM.DTO; using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; /// - /// Builds the part of the model that one scenario step commits: POCOs with deterministic ids, wired by the - /// caller with AssignOwnership, then converted to DTOs, including derived values, once the step is complete + /// Builds the model of the scenario step by step: POCOs with deterministic ids, wired by the caller with + /// AssignOwnership, then converted to DTOs, including derived values, once a step is complete /// /// /// The DTOs are produced from POCOs because a DTO cannot hold the values of members that a derived property - /// redefines, such as OwningMembership.memberElement, which the payload must still carry. + /// redefines, such as OwningMembership.memberElement, which the payload must still carry. One builder holds + /// the whole model, so a later step can wire into the elements of an earlier one. /// public sealed class ModelBuilder { /// - /// The prefix of the names that the ids are derived from + /// The settable string list properties per DTO class, which the Dal conversion shares with the POCO (#428) /// - private readonly string scope; + private static readonly ConcurrentDictionary StringListsByClass = new(); + + /// + /// The prefix of the names that the ids of the current step are derived from + /// + private string scope; /// /// The created elements with their conversion, in creation order /// - private readonly List<(string Name, PocoElement Poco, Func Convert)> entries = []; + private readonly List<(string Name, PocoElement Poco, Func Convert)> entries = []; + + /// + /// The names of the elements that the last converted without their derived values + /// + private List withoutDerivedValues = []; /// /// Initializes a new instance of the class /// /// - /// The prefix of the names that the ids are derived from, e.g. the step name + /// The prefix of the names that the ids of the first step are derived from, e.g. the step name /// public ModelBuilder(string scope) { this.scope = scope; } + /// + /// Gets the names of the elements that the last converted without their derived values, + /// because computing them failed; derived values are not sent, so the payload is unaffected + /// + public IReadOnlyList WithoutDerivedValues => this.withoutDerivedValues; + + /// + /// Gets every created element, in creation order, with the scoped name its id is derived from + /// + public IReadOnlyList<(string Name, PocoElement Element)> Elements => [.. this.entries.Select(entry => (entry.Name, entry.Poco))]; + + /// + /// Selects the elements that a commit must send: those that are new, or whose DTO differs from the one of the + /// previous commit under ComparerProvider + /// + /// + /// The model at the previous commit + /// + /// + /// The model as it must be after the commit + /// + /// + /// The new and changed elements of , in its order + /// + public static IReadOnlyList Changed(IReadOnlyList previous, IReadOnlyList current) + { + var previousById = previous.ToDictionary(element => element.Id); + + return current + .Where(element => !previousById.TryGetValue(element.Id, out var before) || before.GetType() != element.GetType() || !ComparerProvider.Resolve(element).Equals(before, element)) + .ToList(); + } + /// /// Creates the commit request that creates or replaces the given elements /// @@ -74,6 +121,18 @@ public static CommitRequest ToCommitRequest(IEnumerable elements, st }; } + /// + /// Starts the next step: the ids of the elements created from now on are derived from names in + /// + /// + /// + /// The prefix of the names of the step, e.g. core + /// + public void BeginStep(string stepScope) + { + this.scope = stepScope; + } + /// /// Creates a POCO with a deterministic Id and ElementId, and records its conversion to a DTO /// @@ -94,26 +153,56 @@ public static CommitRequest ToCommitRequest(IEnumerable elements, st /// public TPoco Create(string name, Func toDto) where TPoco : PocoElement, new() { - if (this.entries.Exists(entry => entry.Name == name)) + var scopedName = $"{this.scope}/{name}"; + + if (this.entries.Exists(entry => entry.Name == scopedName)) { throw new ArgumentException($"The name {name} is already used in scope {this.scope}", nameof(name)); } var poco = new TPoco { - Id = DeterministicGuid.Create($"{this.scope}/{name}") + Id = DeterministicGuid.Create(scopedName) }; poco.ElementId = poco.Id.ToString(); - this.entries.Add((name, poco, () => toDto(poco, true))); + this.entries.Add((scopedName, poco, includeDerivedProperties => toDto(poco, includeDerivedProperties))); return poco; } /// - /// Converts every created POCO to its DTO, including derived values + /// Finds a created element by the scoped name its id is derived from, e.g. core/f + /// + /// + /// The POCO type of the element + /// + /// + /// The scope and name of the element + /// + /// + /// The element + /// + /// + /// Thrown when no element of was created under + /// + public TPoco Find(string scopedName) where TPoco : PocoElement + { + return this.entries.Find(entry => entry.Name == scopedName).Poco is TPoco element + ? element + : throw new ArgumentException($"No {typeof(TPoco).Name} was created as {scopedName}", nameof(scopedName)); + } + + /// + /// Converts every created POCO to its DTO, including derived values; an element whose derived values cannot be + /// computed, such as an operator expression without the model library, is converted without them and listed + /// in /// + /// + /// Every DTO gets its own copy of the string lists that the Dal conversion shares with the POCO (#428), so that + /// a DTO stays the snapshot of the model at its commit when a later step changes the POCO. + /// /// /// The DTOs, in creation order /// @@ -122,17 +211,59 @@ public static CommitRequest ToCommitRequest(IEnumerable elements, st /// public IReadOnlyList ToDtos() { - return this.entries.Select(entry => + var withoutDerived = new List(); + + var dtos = this.entries.Select(entry => { try { - return entry.Convert(); + return Detach(entry.Convert(true)); + } + catch (Exception) + { + withoutDerived.Add(entry.Name); + } + + try + { + return Detach(entry.Convert(false)); } catch (Exception exception) { - throw new InvalidOperationException($"{this.scope}/{entry.Name} ({entry.Poco.GetType().Name}) cannot be converted to a DTO: {exception.Message}", exception); + throw new InvalidOperationException($"{entry.Name} ({entry.Poco.GetType().Name}) cannot be converted to a DTO: {exception.Message}", exception); } }).ToList(); + + this.withoutDerivedValues = withoutDerived; + + return dtos; + } + + /// + /// Gives a DTO its own copy of every string list it holds + /// + /// + /// The DTO + /// + /// + /// The same DTO + /// + private static DtoElement Detach(DtoElement dto) + { + var stringLists = StringListsByClass.GetOrAdd(dto.GetType(), type => type + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(property => property.PropertyType == typeof(List) && property.CanWrite && property.SetMethod is { IsPublic: true } or { IsAssembly: true }) + .ToArray()); + + foreach (var property in stringLists) + { + if (property.GetValue(dto) is List list) + { + property.SetValue(dto, new List(list)); + } + } + + return dto; } } } diff --git a/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs new file mode 100644 index 000000000..5fc6e1f25 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs @@ -0,0 +1,216 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + using System.Linq; + + using SysML2.NET.Core.Core.Types; + using SysML2.NET.Core.POCO.Core.Classifiers; + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using Type = SysML2.NET.Core.POCO.Core.Types.Type; + + /// + /// The model of scenario step 3: the KerML Core metaclasses, in a package Core of the root package + /// + /// + /// + /// package Core { + /// abstract classifier A { feature f : B :> g [m]; feature g { in feature h; } inout feature k ::> g inverse of f; } + /// classifier B specializes A { feature r :>> g; } + /// type T ~ A; + /// type U specializes A unions A, B intersects A, B differences A, B; + /// classifier C disjoint from A { end feature e1 crosses cf; end feature e2 { feature x; } } + /// } + /// + /// where cf is the feature chain e2.x, a member of Core because the SDK lets only an owning + /// membership or an annotation own a related element, and every owned feature is also featured by its owning type. The end features e1 and e2 get the multiplicity [1] that + /// KerML requires of an end feature (validateFeatureEndMultiplicity) in step 4, because + /// MultiplicityRange is a Kernel metaclass. Rules that need the model library (checkTypeSpecialization + /// and the like) cannot hold without one. + /// + public sealed class CoreModel : StepModel + { + /// + /// Initializes a new instance of the class and builds the model on that of step 2 + /// + /// + /// The model of step 2 + /// + public CoreModel(RootModel root) : base((root ?? throw new ArgumentNullException(nameof(root))).Builder, "core") + { + this.Package = this.CreateNamed("Core", "core", PackageExtensions.ToDto); + this.OwnMember(root.Root, this.Package); + + this.A = this.CreateNamed("A", "a", ClassifierExtensions.ToDto); + this.A.IsAbstract = true; + this.OwnMember(this.Package, this.A); + + var b = this.CreateNamed("B", "b", ClassifierExtensions.ToDto); + this.OwnMember(this.Package, b); + + var f = this.CreateNamed("f", "f", FeatureExtensions.ToDto); + this.G = this.CreateNamed("g", "g", FeatureExtensions.ToDto); + this.G.IsDerived = true; + var k = this.CreateNamed("k", "k", FeatureExtensions.ToDto); + k.Direction = FeatureDirectionKind.Inout; + this.OwnFeature(this.A, f); + this.OwnFeature(this.A, this.G); + this.OwnFeature(this.A, k); + + var h = this.CreateNamed("h", "h", FeatureExtensions.ToDto); + h.Direction = FeatureDirectionKind.In; + h.IsUnique = false; + h.IsOrdered = true; + h.IsComposite = true; + h.IsPortion = true; + this.OwnFeature(this.G, h); + + var typing = this.Builder.Create("f/typing", FeatureTypingExtensions.ToDto); + typing.TypedFeature = f; + typing.Type = b; + f.AssignOwnership(typing); + + var subsetting = this.Builder.Create("f/subsetting", SubsettingExtensions.ToDto); + subsetting.SubsettingFeature = f; + subsetting.SubsettedFeature = this.G; + f.AssignOwnership(subsetting); + + var multiplicity = this.CreateNamed("m", "m", MultiplicityExtensions.ToDto); + this.OwnMember(f, multiplicity); + + var multiplicityFeaturing = this.Builder.Create("m/featuring", TypeFeaturingExtensions.ToDto); + multiplicityFeaturing.FeatureOfType = multiplicity; + multiplicityFeaturing.FeaturingType = this.A; + multiplicity.AssignOwnership(multiplicityFeaturing); + + var referenceSubsetting = this.Builder.Create("k/reference", ReferenceSubsettingExtensions.ToDto); + referenceSubsetting.ReferencedFeature = this.G; + k.AssignOwnership(referenceSubsetting); + + var inverting = this.Builder.Create("k/inverting", FeatureInvertingExtensions.ToDto); + inverting.FeatureInverted = k; + inverting.InvertingFeature = f; + k.AssignOwnership(inverting); + + var subclassification = this.Builder.Create("B/subclassification", SubclassificationExtensions.ToDto); + subclassification.Subclassifier = b; + subclassification.Superclassifier = this.A; + b.AssignOwnership(subclassification); + + var r = this.CreateNamed("r", "r", FeatureExtensions.ToDto); + this.OwnFeature(b, r); + + var redefinition = this.Builder.Create("r/redefinition", RedefinitionExtensions.ToDto); + redefinition.RedefiningFeature = r; + redefinition.RedefinedFeature = this.G; + r.AssignOwnership(redefinition); + + var t = this.CreateNamed("T", "t", TypeExtensions.ToDto); + t.IsSufficient = true; + this.OwnMember(this.Package, t); + + var conjugation = this.Builder.Create("T/conjugation", ConjugationExtensions.ToDto); + conjugation.ConjugatedType = t; + conjugation.OriginalType = this.A; + t.AssignOwnership(conjugation); + + var u = this.CreateNamed("U", "u", TypeExtensions.ToDto); + this.OwnMember(this.Package, u); + + var specialization = this.Builder.Create("U/specialization", SpecializationExtensions.ToDto); + specialization.Specific = u; + specialization.General = this.A; + u.AssignOwnership(specialization); + + foreach (var (operand, index) in new[] { (IType)this.A, b }.Select((operand, index) => (operand, index))) + { + var unioning = this.Builder.Create($"U/unioning {index}", UnioningExtensions.ToDto); + unioning.UnioningType = operand; + u.AssignOwnership(unioning); + + var intersecting = this.Builder.Create($"U/intersecting {index}", IntersectingExtensions.ToDto); + intersecting.IntersectingType = operand; + u.AssignOwnership(intersecting); + + var differencing = this.Builder.Create($"U/differencing {index}", DifferencingExtensions.ToDto); + differencing.DifferencingType = operand; + u.AssignOwnership(differencing); + } + + this.C = this.CreateNamed("C", "c", ClassifierExtensions.ToDto); + this.OwnMember(this.Package, this.C); + + var disjoining = this.Builder.Create("C/disjoining", DisjoiningExtensions.ToDto); + disjoining.TypeDisjoined = this.C; + disjoining.DisjoiningType = this.A; + this.C.AssignOwnership(disjoining); + + this.FirstEnd = this.CreateNamed("e1", "e1", FeatureExtensions.ToDto); + this.FirstEnd.IsEnd = true; + this.SecondEnd = this.CreateNamed("e2", "e2", FeatureExtensions.ToDto); + this.SecondEnd.IsEnd = true; + this.OwnFeature(this.C, this.FirstEnd); + this.OwnFeature(this.C, this.SecondEnd); + + var x = this.CreateNamed("x", "x", FeatureExtensions.ToDto); + this.OwnFeature(this.SecondEnd, x); + + var chain = this.CreateNamed("cf", "cf", FeatureExtensions.ToDto); + this.OwnMember(this.Package, chain); + + var crossSubsetting = this.Builder.Create("e1/cross", CrossSubsettingExtensions.ToDto); + crossSubsetting.CrossedFeature = chain; + this.FirstEnd.AssignOwnership(crossSubsetting); + + foreach (var (link, index) in new[] { this.SecondEnd, x }.Select((link, index) => (link, index))) + { + var chaining = this.Builder.Create($"cf/chaining {index}", FeatureChainingExtensions.ToDto); + chaining.ChainingFeature = link; + chain.AssignOwnership(chaining); + } + } + + /// + /// Gets the package that holds the step + /// + public Package Package { get; } + + /// + /// Gets the abstract classifier A, which most relationships of the step target + /// + public Classifier A { get; } + + /// + /// Gets the classifier C, which owns the end features + /// + public Classifier C { get; } + + /// + /// Gets the feature g of A, which is subsetted and redefined + /// + public Feature G { get; } + + /// + /// Gets the end feature e1 of C + /// + public Feature FirstEnd { get; } + + /// + /// Gets the end feature e2 of C + /// + public Feature SecondEnd { get; } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs new file mode 100644 index 000000000..41815d13a --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs @@ -0,0 +1,285 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using SysML2.NET.Core.Core.Types; + using SysML2.NET.Core.POCO.Core.Classifiers; + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Kernel.Behaviors; + using SysML2.NET.Core.POCO.Kernel.DataTypes; + using SysML2.NET.Core.POCO.Kernel.Expressions; + using SysML2.NET.Core.POCO.Kernel.FeatureValues; + using SysML2.NET.Core.POCO.Kernel.Functions; + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Core.POCO.Root.Annotations; + using SysML2.NET.Core.POCO.Root.Dependencies; + using SysML2.NET.Core.POCO.Root.Namespaces; + using SysML2.NET.Core.Root.Namespaces; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using Type = SysML2.NET.Core.POCO.Core.Types.Type; + + /// + /// The changes of scenario step 5 to the KerML model of steps 2 to 4, after plan §6.1: U1 renames one instance of + /// every metaclass, U2 changes the non-derived attributes, U3 retargets relationship ends, and U4 extends owned + /// relationships, so that every metaclass gets U1 and at least one of U2 to U4 + /// + /// + /// Retargeting an owning membership moves its member, and U4 also asks for an owned relationship list reordered and + /// shrunk; the public SDK can express none of these (#427), so an owning membership gets U2 (its visibility). A + /// TypeFeaturing keeps its ends, because its featuring type is the type that owns its feature. + /// + public sealed class KerMLUpdateModel : StepModel + { + /// + /// Initializes a new instance of the class and changes the model of steps 2 to 4 + /// + /// + /// The model of step 2 + /// + /// + /// The model of step 3 + /// + /// + /// The model of step 4 + /// + public KerMLUpdateModel(RootModel root, CoreModel core, KernelModel kernel) : base((kernel ?? throw new ArgumentNullException(nameof(kernel))).Builder, "kerml update") + { + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(core); + + var firstInstances = this.Builder.Elements.GroupBy(entry => entry.Element.GetType()).Select(group => group.First().Element).ToList(); + + this.Rename(firstInstances); + this.ChangeAttributes(root); + this.Retarget(core, kernel); + this.Complete(firstInstances); + this.Extend(core); + } + + /// + /// Gets the classifier that step 5 adds to the package Core + /// + public Classifier Added { get; private set; } + + /// + /// U2: changes every non-derived attribute that steps 2 to 4 set, to another legal value + /// + /// + /// The model of step 2 + /// + private void ChangeAttributes(RootModel root) + { + root.Root.AliasIds.Add("urn:coverage-model:CoverageModel:2"); + + var comment = this.Builder.Find("root/Note"); + comment.Body = "A comment about the library."; + comment.Locale = "nl-NL"; + + this.Builder.Find("root/doc").Body = "The coverage model, updated."; + + var representation = this.Builder.Find("root/Representation"); + representation.Language = "plain"; + representation.Body = "The updated coverage model, in words."; + + this.Builder.Find("root/Library").IsStandard = false; + + var namespaceImport = this.Builder.Find("root/Nested/import Library"); + namespaceImport.IsRecursive = false; + namespaceImport.IsImportAll = false; + namespaceImport.Visibility = VisibilityKind.Public; + + var membershipImport = this.Builder.Find("root/Nested/import LibAlias"); + membershipImport.IsRecursive = true; + membershipImport.Visibility = VisibilityKind.Private; + + var alias = this.Builder.Find("root/Space/LibAlias"); + alias.MemberName = "LibraryAlias"; + alias.MemberShortName = "lia"; + alias.Visibility = VisibilityKind.Private; + + this.Builder.Find("root/Library/filter/condition").Value = false; + + this.Builder.Find("core/A").IsAbstract = false; + this.Builder.Find("core/T").IsSufficient = false; + this.Builder.Find("core/g").IsDerived = false; + + var h = this.Builder.Find("core/h"); + h.IsUnique = true; + h.IsOrdered = false; + h.IsComposite = false; + h.IsPortion = false; + h.Direction = FeatureDirectionKind.Out; + + this.Builder.Find("core/k").Direction = FeatureDirectionKind.In; + + this.Builder.Find("kernel/D").IsSufficient = false; + + var c = this.Builder.Find("kernel/c"); + c.IsOrdered = false; + c.IsUnique = true; + + this.Builder.Find("kernel/a/value").IsDefault = false; + this.Builder.Find("kernel/a/value/42").Value = 43; + this.Builder.Find("kernel/rational").Value = 3.5; + this.Builder.Find("kernel/text").Value = "t"; + this.Builder.Find("kernel/inv").IsNegated = false; + this.Builder.Find("kernel/P/body").Value = false; + } + + /// + /// U4: extends the owned relationships of the package Core with a new classifier + /// + /// + /// The model of step 3 + /// + private void Extend(CoreModel core) + { + this.Added = this.CreateNamed("Added", "add", ClassifierExtensions.ToDto); + this.OwnMember(core.Package, this.Added); + } + + /// + /// Gives the first instance of every metaclass that has no attribute or end of its own to change a change of + /// U2 or U4: a membership changes its visibility, a namespace gets an owned comment, and an annotating element + /// annotates one more element + /// + /// + /// The first instance of every metaclass that steps 2 to 4 created + /// + private void Complete(IReadOnlyList firstInstances) + { + var space = this.Builder.Find("root/Space"); + + foreach (var element in firstInstances) + { + switch (element) + { + case IMembership membership: + membership.Visibility = membership.Visibility == VisibilityKind.Private ? VisibilityKind.Public : VisibilityKind.Private; + break; + case INamespace owner: + var comment = this.Builder.Create($"{element.ElementId}/update comment", CommentExtensions.ToDto); + comment.Body = $"Updated in step 5: {element.GetType().Name}."; + this.OwnMember(owner, comment); + break; + case AnnotatingElement annotating: + var annotation = this.Builder.Create($"{element.ElementId}/update annotation", AnnotationExtensions.ToDto); + annotation.AnnotatedElement = space; + annotating.AssignOwnership(annotation); + break; + } + } + } + + /// + /// U1: renames the first instance of every metaclass that steps 2 to 4 created + /// + /// + /// The first instance of every metaclass that steps 2 to 4 created + /// + private void Rename(IReadOnlyList firstInstances) + { + foreach (var element in firstInstances) + { + element.DeclaredName = $"{element.DeclaredName ?? element.GetType().Name} renamed"; + element.DeclaredShortName = $"{element.DeclaredShortName ?? element.GetType().Name.ToLowerInvariant()}2"; + } + } + + /// + /// U3: retargets an end of every kind of KerML relationship that steps 2 to 4 created, keeping the model + /// well-formed; a connector, flow or association is retargeted through the reference or typing of an end + /// + /// + /// The model of step 3 + /// + /// + /// The model of step 4 + /// + private void Retarget(CoreModel core, KernelModel kernel) + { + var library = this.Builder.Find("root/Library"); + var space = this.Builder.Find("root/Space"); + var b = this.Builder.Find("core/B"); + var f = this.Builder.Find("core/f"); + var k = this.Builder.Find("core/k"); + + this.Builder.Find("root/Note/about Nested").AnnotatedElement = library; + + var dependency = this.Builder.Find("root/Uses"); + dependency.Supplier.Clear(); + dependency.Supplier.Add(space); + + this.Builder.Find("root/Nested/import Library").ImportedNamespace = space; + this.Builder.Find("root/Space/LibAlias").MemberElement = this.Builder.Find("root/Nested"); + + this.Builder.Find("core/f/typing").Type = core.A; + this.Builder.Find("core/f/subsetting").SubsettedFeature = k; + this.Builder.Find("core/r/redefinition").RedefinedFeature = f; + this.Builder.Find("core/k/reference").ReferencedFeature = f; + this.Builder.Find("core/U/specialization").General = b; + this.Builder.Find("core/T/conjugation").OriginalType = b; + this.Builder.Find("core/C/disjoining").DisjoiningType = b; + this.Builder.Find("core/U/unioning 0").UnioningType = core.C; + this.Builder.Find("core/U/intersecting 0").IntersectingType = core.C; + this.Builder.Find("core/U/differencing 0").DifferencingType = core.C; + this.Builder.Find("core/k/inverting").InvertingFeature = core.G; + + this.Builder.Find("root/Nested/import LibAlias").ImportedMembership = (IMembership)core.A.OwningRelationship; + this.Builder.Find("kernel/M/subclassification").Superclassifier = kernel.Class; + + var x2 = this.CreateNamed("x2", "x2", FeatureExtensions.ToDto); + this.OwnFeature(core.SecondEnd, x2); + this.Builder.Find("core/cf/chaining 1").ChainingFeature = x2; + + var chain = this.CreateNamed("cf2", "cf2", FeatureExtensions.ToDto); + this.OwnMember(core.Package, chain); + + foreach (var (link, index) in new[] { core.SecondEnd, x2 }.Select((link, index) => (link, index))) + { + var chaining = this.Builder.Create($"cf2/chaining {index}", FeatureChainingExtensions.ToDto); + chaining.ChainingFeature = link; + chain.AssignOwnership(chaining); + } + + this.Builder.Find("core/e1/cross").CrossedFeature = chain; + + var dataType = this.Builder.Find("kernel/D"); + var first = this.Builder.Find("kernel/s1"); + var second = this.Builder.Find("kernel/s2"); + + this.Builder.Find("kernel/k/target/reference").ReferencedFeature = this.Builder.Find("kernel/c"); + this.Builder.Find("kernel/bc/target/reference").ReferencedFeature = this.Builder.Find("kernel/c"); + this.Builder.Find("kernel/su/first/reference").ReferencedFeature = second; + this.Builder.Find("kernel/su/then/reference").ReferencedFeature = first; + + foreach (var flow in new[] { "fl", "sf" }) + { + this.Builder.Find($"kernel/{flow}/source/reference").ReferencedFeature = second; + this.Builder.Find($"kernel/{flow}/target/reference").ReferencedFeature = first; + } + + foreach (var (association, endType) in new[] { ("As", (IType)dataType), ("AsS", this.Builder.Find("kernel/S")), ("I", dataType) }) + { + this.Builder.Find($"kernel/{association}/e2").OwnedRelationship.OfType().Single().Type = endType; + } + + this.Builder.Find("kernel/md/about Cl").AnnotatedElement = dataType; + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs new file mode 100644 index 000000000..9f688d675 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs @@ -0,0 +1,716 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + + using SysML2.NET.Core.Core.Types; + using SysML2.NET.Core.POCO.Core.Classifiers; + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Kernel.Associations; + using SysML2.NET.Core.POCO.Kernel.Behaviors; + using SysML2.NET.Core.POCO.Kernel.Classes; + using SysML2.NET.Core.POCO.Kernel.Connectors; + using SysML2.NET.Core.POCO.Kernel.DataTypes; + using SysML2.NET.Core.POCO.Kernel.Expressions; + using SysML2.NET.Core.POCO.Kernel.FeatureValues; + using SysML2.NET.Core.POCO.Kernel.Functions; + using SysML2.NET.Core.POCO.Kernel.Interactions; + using SysML2.NET.Core.POCO.Kernel.Metadata; + using SysML2.NET.Core.POCO.Kernel.Multiplicities; + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Core.POCO.Kernel.Structures; + using SysML2.NET.Core.POCO.Root.Annotations; + using SysML2.NET.Core.POCO.Root.Namespaces; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using PocoRelationship = SysML2.NET.Core.POCO.Root.Elements.IRelationship; + + /// + /// The model of scenario step 4: the KerML Kernel metaclasses, in a package Kernel of the root package, and + /// the multiplicity [1] that the end features of step 3 require + /// + /// + /// + /// package Kernel { + /// datatype D; class Cl { feature a : D [1] = 42 default; feature b : D [1]; feature c : D [0..*]; + /// connector k from a to b; binding bc of a = b; } + /// struct S; metaclass M specializes S; + /// behavior B2 { in x : D; out y : D; } + /// behavior B { step s1 : B2 [1]; step s2 : B2 [1]; succession su first s1 then s2; + /// flow fl of payload : D from s1.y to s2.x; succession flow sf of payload : D from s1.y to s2.x; + /// expressions: e, be, inv, literals, invocation, constructor, operators, metadata access } + /// assoc As { end e1 : Cl [1]; end e2 : S [1]; } assoc struct AsS { … } interaction I { … } + /// function F { in p : D; return r; p } predicate P { true } + /// metadata md : M about Cl; + /// } + /// + /// Every expression owns its result parameter. Without the model library, the operator expressions have no + /// instantiated type and the multiplicity bounds no library result types; those rules cannot hold. + /// + public sealed class KernelModel : StepModel + { + /// + /// Initializes a new instance of the class and builds the model on that of step 3 + /// + /// + /// The model of step 2 + /// + /// + /// The model of step 3 + /// + public KernelModel(RootModel root, CoreModel core) : base((core ?? throw new ArgumentNullException(nameof(core))).Builder, "kernel") + { + ArgumentNullException.ThrowIfNull(root); + + this.MultiplicityOne(core.FirstEnd, core.C); + this.MultiplicityOne(core.SecondEnd, core.C); + + this.Package = this.CreateNamed("Kernel", "kernel", PackageExtensions.ToDto); + this.OwnMember(root.Root, this.Package); + + var dataType = this.CreateNamed("D", "d", DataTypeExtensions.ToDto); + dataType.IsSufficient = true; + this.OwnMember(this.Package, dataType); + + this.Class = this.CreateNamed("Cl", "cl", ClassExtensions.ToDto); + this.OwnMember(this.Package, this.Class); + + var a = this.TypedFeature(this.Class, "a", dataType); + this.MultiplicityOne(a, this.Class); + var b = this.TypedFeature(this.Class, "b", dataType); + this.MultiplicityOne(b, this.Class); + var c = this.TypedFeature(this.Class, "c", dataType); + c.IsOrdered = true; + c.IsUnique = false; + this.MultiplicityRange(c, this.Class, this.Literal("c/lower", LiteralIntegerExtensions.ToDto, literal => literal.Value = 0), this.Literal("c/upper", LiteralInfinityExtensions.ToDto, _ => { })); + + var defaultValue = this.Builder.Create("a/value", FeatureValueExtensions.ToDto); + defaultValue.IsDefault = true; + a.AssignOwnership(defaultValue, this.Literal("a/value/42", LiteralIntegerExtensions.ToDto, literal => literal.Value = 42)); + + var connector = this.CreateNamed("k", "k", ConnectorExtensions.ToDto); + this.OwnFeature(this.Class, connector); + this.ConnectorEnd(connector, "k/source", a); + this.ConnectorEnd(connector, "k/target", b); + + var binding = this.CreateNamed("bc", "bc", BindingConnectorExtensions.ToDto); + this.OwnFeature(this.Class, binding); + this.ConnectorEnd(binding, "bc/source", a); + this.ConnectorEnd(binding, "bc/target", b); + + var structure = this.CreateNamed("S", "s", StructureExtensions.ToDto); + this.OwnMember(this.Package, structure); + + this.Metaclass = this.CreateNamed("M", "m", MetaclassExtensions.ToDto); + this.OwnMember(this.Package, this.Metaclass); + + var metaclassGeneral = this.Builder.Create("M/subclassification", SubclassificationExtensions.ToDto); + metaclassGeneral.Subclassifier = this.Metaclass; + metaclassGeneral.Superclassifier = structure; + this.Metaclass.AssignOwnership(metaclassGeneral); + + var called = this.CreateNamed("B2", "b2", BehaviorExtensions.ToDto); + this.OwnMember(this.Package, called); + + var input = this.Parameter(called, "x", FeatureDirectionKind.In, ParameterMembershipExtensions.ToDto); + this.Typed(input, dataType); + var output = this.CreateNamed("y", "y", FeatureExtensions.ToDto); + output.Direction = FeatureDirectionKind.Out; + this.OwnFeature(called, output); + this.Typed(output, dataType); + + this.Behavior = this.CreateNamed("B", "bh", BehaviorExtensions.ToDto); + this.OwnMember(this.Package, this.Behavior); + + var first = this.TypedFeature(this.Behavior, "s1", called, StepExtensions.ToDto); + this.MultiplicityOne(first, this.Behavior); + var second = this.TypedFeature(this.Behavior, "s2", called, StepExtensions.ToDto); + this.MultiplicityOne(second, this.Behavior); + + var succession = this.CreateNamed("su", "su", SuccessionExtensions.ToDto); + this.OwnFeature(this.Behavior, succession); + this.ConnectorEnd(succession, "su/first", first); + this.ConnectorEnd(succession, "su/then", second); + + this.Flow("fl", FlowExtensions.ToDto, first, second, output, input, dataType); + this.Flow("sf", SuccessionFlowExtensions.ToDto, first, second, output, input, dataType); + + this.Association("As", AssociationExtensions.ToDto, structure); + this.Association("AsS", AssociationStructureExtensions.ToDto, dataType); + this.Association("I", InteractionExtensions.ToDto, structure); + + this.Function = this.CreateNamed("F", "f", FunctionExtensions.ToDto); + this.OwnMember(this.Package, this.Function); + this.FunctionParameter = this.Parameter(this.Function, "p", FeatureDirectionKind.In, ParameterMembershipExtensions.ToDto); + this.Typed(this.FunctionParameter, dataType); + this.Result(this.Function, "F"); + this.Body(this.Function, "F", this.FeatureReference("F/body", this.FunctionParameter)); + + var predicate = this.CreateNamed("P", "p", PredicateExtensions.ToDto); + this.OwnMember(this.Package, predicate); + this.Result(predicate, "P"); + this.Body(predicate, "P", this.Literal("P/body", LiteralBooleanExtensions.ToDto, literal => literal.Value = true)); + + this.Expressions(dataType, a, b, c, predicate); + + var metadata = this.CreateNamed("md", "md", MetadataFeatureExtensions.ToDto); + this.OwnMember(this.Package, metadata); + this.Typed(metadata, this.Metaclass); + + var about = this.Builder.Create("md/about Cl", AnnotationExtensions.ToDto); + about.AnnotatedElement = this.Class; + metadata.AssignOwnership(about); + } + + /// + /// Gets the package that holds the step + /// + public Package Package { get; } + + /// + /// Gets the class Cl, which owns the connectors and which the associations, the constructor expression + /// and the metadata relate to + /// + public Class Class { get; } + + /// + /// Gets the behavior B, which owns the steps, flows and expressions + /// + public Behavior Behavior { get; } + + /// + /// Gets the function F + /// + public Function Function { get; } + + /// + /// Gets the in parameter p of + /// + public Feature FunctionParameter { get; } + + /// + /// Gets the metaclass M + /// + public Metaclass Metaclass { get; } + + /// + /// Adds an in parameter to an invocation-like expression, whose value is an expression + /// + /// + /// The expression that takes the argument + /// + /// + /// The name of the argument + /// + /// + /// The value of the argument + /// + /// + /// The argument feature + /// + private IFeature Argument(IExpression expression, string name, IExpression value) + { + var argument = this.Parameter(expression, name, FeatureDirectionKind.In, ParameterMembershipExtensions.ToDto); + var argumentValue = this.Builder.Create($"{argument.ElementId}/value", FeatureValueExtensions.ToDto); + argument.AssignOwnership(argumentValue, value); + + return argument; + } + + /// + /// Creates an association-like classifier with two end features, typed by and by + /// , each with the multiplicity [1] + /// + /// + /// The association POCO type + /// + /// + /// The name of the association + /// + /// + /// The generated ToDto extension of + /// + /// + /// The type of the second end + /// + private void Association(string name, Func toDto, IType other) where TAssociation : IAssociation, new() + { + var association = this.CreateNamed(name, name.ToLowerInvariant(), toDto); + this.OwnMember(this.Package, association); + + foreach (var (endName, endType) in new[] { ($"{name}/e1", (IType)this.Class), ($"{name}/e2", other) }) + { + var end = this.CreateNamed(endName, endName.Replace('/', '_'), FeatureExtensions.ToDto); + end.IsEnd = true; + this.OwnFeature(association, end); + this.Typed(end, endType); + this.MultiplicityOne(end, association); + } + } + + /// + /// Makes an expression the result expression of a function or predicate + /// + /// + /// The function or predicate + /// + /// + /// The name the membership is derived from + /// + /// + /// The result expression + /// + private void Body(IFunction function, string name, IExpression body) + { + var membership = this.Builder.Create($"{name}/result expression", ResultExpressionMembershipExtensions.ToDto); + function.AssignOwnership(membership, body); + } + + /// + /// Creates a feature reference expression whose referent is an expression owned through a + /// , as the body of a select or collect expression + /// + /// + /// The name the elements are derived from + /// + /// + /// The feature reference expression + /// + private FeatureReferenceExpression BodyReference(string name) + { + var reference = this.Builder.Create(name, FeatureReferenceExpressionExtensions.ToDto); + var body = this.Literal($"{name}/true", LiteralBooleanExtensions.ToDto, literal => literal.Value = true); + var membership = this.Builder.Create($"{name}/membership", FeatureMembershipExtensions.ToDto); + reference.AssignOwnership(membership, body); + this.Result(reference, name); + + return reference; + } + + /// + /// Adds an end feature to a connector, referencing a related feature + /// + /// + /// The connector + /// + /// + /// The name the end is derived from + /// + /// + /// The related feature + /// + /// + /// The end feature + /// + private Feature ConnectorEnd(IConnector connector, string name, IFeature related) + { + var end = this.Builder.Create(name, FeatureExtensions.ToDto); + end.IsEnd = true; + this.OwnFeature(connector, end); + + var reference = this.Builder.Create($"{name}/reference", ReferenceSubsettingExtensions.ToDto); + reference.ReferencedFeature = related; + end.AssignOwnership(reference); + + return end; + } + + /// + /// Adds one instance of every expression metaclass to + /// + /// + /// The data type D + /// + /// + /// The feature Cl::a + /// + /// + /// The feature Cl::b + /// + /// + /// The feature Cl::c + /// + /// + /// The predicate P + /// + private void Expressions(IType dataType, IFeature a, IFeature b, IFeature c, IFunction predicate) + { + var expression = this.OwnExpression("e", ExpressionExtensions.ToDto); + this.Typed(expression, this.Function); + + var booleanExpression = this.OwnExpression("be", BooleanExpressionExtensions.ToDto); + this.Typed(booleanExpression, predicate); + + var invariant = this.OwnExpression("inv", InvariantExtensions.ToDto); + invariant.IsNegated = true; + this.Typed(invariant, predicate); + + var rational = this.OwnExpression("rational", LiteralRationalExtensions.ToDto); + rational.Value = 2.5; + + var text = this.OwnExpression("text", LiteralStringExtensions.ToDto); + text.Value = "s"; + + this.OwnExpression("literal", LiteralExpressionExtensions.ToDto); + this.OwnExpression("null", NullExpressionExtensions.ToDto); + + var metadataAccess = this.OwnExpression("metadata access", MetadataAccessExpressionExtensions.ToDto); + this.Reference(metadataAccess, this.Class); + + var invocation = this.OwnExpression("invocation", InvocationExpressionExtensions.ToDto); + this.Reference(invocation, this.Function); + var invocationArgument = this.Argument(invocation, "invocation/p", this.Literal("invocation/p/7", LiteralIntegerExtensions.ToDto, literal => literal.Value = 7)); + var redefinition = this.Builder.Create("invocation/p/redefinition", RedefinitionExtensions.ToDto); + redefinition.RedefiningFeature = invocationArgument; + redefinition.RedefinedFeature = this.FunctionParameter; + invocationArgument.AssignOwnership(redefinition); + + var constructor = this.OwnExpression("constructor", ConstructorExpressionExtensions.ToDto); + this.Reference(constructor, this.Class); + + var sum = this.OwnExpression("sum", OperatorExpressionExtensions.ToDto); + sum.Operator = "+"; + this.Argument(sum, "sum/left", this.Literal("sum/left/1", LiteralIntegerExtensions.ToDto, literal => literal.Value = 1)); + this.Argument(sum, "sum/right", this.Literal("sum/right/2", LiteralIntegerExtensions.ToDto, literal => literal.Value = 2)); + + var index = this.OwnExpression("index", IndexExpressionExtensions.ToDto); + index.Operator = "#"; + this.Argument(index, "index/sequence", this.FeatureReference("index/sequence/c", c)); + this.Argument(index, "index/position", this.Literal("index/position/1", LiteralIntegerExtensions.ToDto, literal => literal.Value = 1)); + + var select = this.OwnExpression("select", SelectExpressionExtensions.ToDto); + select.Operator = "select"; + this.Argument(select, "select/sequence", this.FeatureReference("select/sequence/c", c)); + this.Argument(select, "select/body", this.BodyReference("select/body/reference")); + + var collect = this.OwnExpression("collect", CollectExpressionExtensions.ToDto); + collect.Operator = "collect"; + this.Argument(collect, "collect/sequence", this.FeatureReference("collect/sequence/c", c)); + this.Argument(collect, "collect/body", this.BodyReference("collect/body/reference")); + + var chain = this.OwnExpression("chain", FeatureChainExpressionExtensions.ToDto); + chain.Operator = "."; + this.Argument(chain, "chain/source", this.FeatureReference("chain/source/a", a)); + this.Reference(chain, b); + + var typed = this.Builder.Create("rational/typing", FeatureTypingExtensions.ToDto); + typed.TypedFeature = rational; + typed.Type = dataType; + rational.AssignOwnership(typed); + } + + /// + /// Creates a feature reference expression that refers to a feature + /// + /// + /// The name the elements are derived from + /// + /// + /// The referenced feature + /// + /// + /// The feature reference expression + /// + private FeatureReferenceExpression FeatureReference(string name, IFeature referent) + { + var reference = this.Builder.Create(name, FeatureReferenceExpressionExtensions.ToDto); + this.Reference(reference, referent); + this.Result(reference, name); + + return reference; + } + + /// + /// Creates a flow-like connector in from an output of one step to an input of another, + /// with its payload feature + /// + /// + /// The flow POCO type + /// + /// + /// The name of the flow + /// + /// + /// The generated ToDto extension of + /// + /// + /// The source step + /// + /// + /// The target step + /// + /// + /// The output parameter that the source end redefines + /// + /// + /// The input parameter that the target end redefines + /// + /// + /// The type of the payload + /// + private void Flow(string name, Func toDto, IFeature source, IFeature target, IFeature output, IFeature input, IType payloadType) where TFlow : IFlow, new() + { + var flow = this.CreateNamed(name, name, toDto); + this.OwnFeature(this.Behavior, flow); + + var payload = this.Builder.Create($"{name}/payload", PayloadFeatureExtensions.ToDto); + this.OwnFeature(flow, payload); + this.Typed(payload, payloadType); + + foreach (var (endName, related, redefined, direction) in new[] { ($"{name}/source", source, output, FeatureDirectionKind.Out), ($"{name}/target", target, input, FeatureDirectionKind.In) }) + { + var end = this.Builder.Create(endName, FlowEndExtensions.ToDto); + end.IsEnd = true; + this.OwnFeature(flow, end); + + var reference = this.Builder.Create($"{endName}/reference", ReferenceSubsettingExtensions.ToDto); + reference.ReferencedFeature = related; + end.AssignOwnership(reference); + + var flowFeature = this.Builder.Create($"{endName}/feature", FeatureExtensions.ToDto); + flowFeature.Direction = direction; + this.OwnFeature(end, flowFeature); + + var redefinition = this.Builder.Create($"{endName}/feature/redefinition", RedefinitionExtensions.ToDto); + redefinition.RedefiningFeature = flowFeature; + redefinition.RedefinedFeature = redefined; + flowFeature.AssignOwnership(redefinition); + } + } + + /// + /// Creates a literal expression with its result parameter + /// + /// + /// The literal POCO type + /// + /// + /// The name the elements are derived from + /// + /// + /// The generated ToDto extension of + /// + /// + /// Sets the value of the literal + /// + /// + /// The literal expression + /// + private TLiteral Literal(string name, Func toDto, Action setValue) where TLiteral : IExpression, new() + { + var literal = this.Builder.Create(name, toDto); + setValue(literal); + this.Result(literal, name); + + return literal; + } + + /// + /// Gives a feature the multiplicity [1], featured like the feature + /// + /// + /// The feature + /// + /// + /// The type that features + /// + private void MultiplicityOne(IFeature feature, IType featuringType) + { + this.MultiplicityRange(feature, featuringType, this.Literal($"{feature.ElementId}/multiplicity/1", LiteralIntegerExtensions.ToDto, literal => literal.Value = 1)); + } + + /// + /// Gives a feature a multiplicity range with the given bounds, featured like the feature as KerML requires + /// (validateFeatureMultiplicityDomain) + /// + /// + /// The feature + /// + /// + /// The type that features + /// + /// + /// The bounds: the upper bound alone, or the lower and the upper bound + /// + private void MultiplicityRange(IFeature feature, IType featuringType, params IExpression[] bounds) + { + var range = this.Builder.Create($"{feature.ElementId}/multiplicity", MultiplicityRangeExtensions.ToDto); + + foreach (var bound in bounds) + { + this.OwnMember(range, bound); + } + + this.OwnMember(feature, range); + + var featuring = this.Builder.Create($"{feature.ElementId}/multiplicity/featuring", TypeFeaturingExtensions.ToDto); + featuring.FeatureOfType = range; + featuring.FeaturingType = featuringType; + range.AssignOwnership(featuring); + } + + /// + /// Creates an expression with its result parameter as a feature of + /// + /// + /// The expression POCO type + /// + /// + /// The declared name of the expression + /// + /// + /// The generated ToDto extension of + /// + /// + /// The expression + /// + private TExpression OwnExpression(string name, Func toDto) where TExpression : IExpression, new() + { + var expression = this.CreateNamed(name, name.Replace(' ', '_'), toDto); + this.OwnFeature(this.Behavior, expression); + this.Result(expression, name); + + return expression; + } + + /// + /// Adds a parameter to a behavior or expression through a parameter membership + /// + /// + /// The parameter membership POCO type + /// + /// + /// The behavior or expression + /// + /// + /// The name of the parameter + /// + /// + /// The direction of the parameter + /// + /// + /// The generated ToDto extension of + /// + /// + /// The parameter + /// + private Feature Parameter(IType owner, string name, FeatureDirectionKind direction, Func toDto) where TMembership : PocoRelationship, new() + { + var parameter = this.Builder.Create(name, FeatureExtensions.ToDto); + parameter.DeclaredName = name[(name.LastIndexOf('/') + 1)..]; + parameter.Direction = direction; + + var membership = this.Builder.Create($"{name}/membership", toDto); + owner.AssignOwnership(membership, parameter); + + return parameter; + } + + /// + /// Refers an expression to an element through a plain, non-owning + /// + /// + /// The expression + /// + /// + /// The referenced element + /// + private void Reference(IExpression expression, PocoElement element) + { + var membership = this.Builder.Create($"{expression.ElementId}/reference {element.ElementId}", MembershipExtensions.ToDto); + membership.MemberElement = element; + membership.MemberName = element.DeclaredName; + expression.AssignOwnership(membership); + } + + /// + /// Adds the result parameter to an expression or function, through a + /// + /// + /// The expression or function + /// + /// + /// The name the elements are derived from + /// + private void Result(IType owner, string name) + { + this.Parameter(owner, $"{name}/result", FeatureDirectionKind.Out, ReturnParameterMembershipExtensions.ToDto); + } + + /// + /// Types a feature with a + /// + /// + /// The feature + /// + /// + /// The type + /// + private void Typed(IFeature feature, IType type) + { + var typing = this.Builder.Create($"{feature.ElementId}/typing", FeatureTypingExtensions.ToDto); + typing.TypedFeature = feature; + typing.Type = type; + feature.AssignOwnership(typing); + } + + /// + /// Creates a feature of a type, typed by another type + /// + /// + /// The owning type + /// + /// + /// The name of the feature + /// + /// + /// The type of the feature + /// + /// + /// The feature + /// + private IFeature TypedFeature(IType owner, string name, IType type) => this.TypedFeature(owner, name, type, FeatureExtensions.ToDto); + + /// + /// Creates a feature of a given metaclass that a type owns, typed by another type + /// + /// + /// The feature POCO type + /// + /// + /// The owning type + /// + /// + /// The name of the feature + /// + /// + /// The type of the feature + /// + /// + /// The generated ToDto extension of + /// + /// + /// The feature + /// + private TFeature TypedFeature(IType owner, string name, IType type, Func toDto) where TFeature : IFeature, new() + { + var feature = this.CreateNamed(name, name, toDto); + this.OwnFeature(owner, feature); + this.Typed(feature, type); + + return feature; + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs index 825b14b13..a6fbca8ac 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/RootModel.cs @@ -9,8 +9,6 @@ namespace SySML2.NET.REST.Tests.Helpers.Models { - using System; - using SysML2.NET.Core.Core.Types; using SysML2.NET.Core.POCO.Core.Features; using SysML2.NET.Core.POCO.Kernel.Expressions; @@ -23,9 +21,6 @@ namespace SySML2.NET.REST.Tests.Helpers.Models using SysML2.NET.Dal; using SysML2.NET.Extensions; - using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; - using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; - /// /// The model of scenario step 2: the root package and the KerML Root and Packages metaclasses /// @@ -51,15 +46,13 @@ namespace SySML2.NET.REST.Tests.Helpers.Models /// plus an about Library, which has no textual notation of its own, and the /// result parameter of the filter condition, which KerML requires of every Expression (result [1..1]). /// - public sealed class RootModel + public sealed class RootModel : StepModel { /// /// Initializes a new instance of the class and builds the model /// - public RootModel() + public RootModel() : base(new ModelBuilder("root"), "root") { - this.Builder = new ModelBuilder("root"); - this.Root = this.CreateNamed("CoverageModel", "cvm", PackageExtensions.ToDto); this.Nested = this.CreateNamed("Nested", "nst", PackageExtensions.ToDto); @@ -133,11 +126,6 @@ public RootModel() this.OwnMember(this.Root, dependency); } - /// - /// Gets the holding every element of the model - /// - public ModelBuilder Builder { get; } - /// /// Gets the root package /// @@ -147,48 +135,5 @@ public RootModel() /// Gets the nested package, which owns the imports and is annotated by the comment /// public Package Nested { get; } - - /// - /// Creates an element with a declared name, short name and alias id - /// - /// - /// The POCO type - /// - /// - /// The declared name, also the name its id is derived from - /// - /// - /// The declared short name - /// - /// - /// The generated ToDto extension of - /// - /// - /// The created POCO - /// - private TPoco CreateNamed(string name, string shortName, Func toDto) where TPoco : PocoElement, new() - { - var element = this.Builder.Create(name, toDto); - element.DeclaredName = name; - element.DeclaredShortName = shortName; - element.AliasIds = [$"urn:coverage-model:{name}"]; - - return element; - } - - /// - /// Makes an element an owned member of a namespace through a new - /// - /// - /// The owning namespace - /// - /// - /// The owned member - /// - private void OwnMember(PocoElement owner, PocoElement member) - { - var membership = this.Builder.Create($"{member.ElementId}/membership", OwningMembershipExtensions.ToDto); - owner.AssignOwnership(membership, member); - } } } diff --git a/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs new file mode 100644 index 000000000..ba5a45ee1 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs @@ -0,0 +1,117 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Root.Namespaces; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using PocoRelationship = SysML2.NET.Core.POCO.Root.Elements.IRelationship; + + /// + /// The base of the model of one scenario step: the elements it adds to the one that + /// holds the whole model, built with the same naming and ownership conventions in every step + /// + public abstract class StepModel + { + /// + /// Initializes a new instance of the class, starting the step on the builder + /// + /// + /// The builder holding the whole model + /// + /// + /// The name of the step, which scopes the ids of its elements + /// + protected StepModel(ModelBuilder builder, string scope) + { + this.Builder = builder ?? throw new ArgumentNullException(nameof(builder)); + this.Builder.BeginStep(scope); + } + + /// + /// Gets the holding every element of the model + /// + public ModelBuilder Builder { get; } + + /// + /// Creates an element with a declared name, short name and alias id + /// + /// + /// The POCO type + /// + /// + /// The declared name, also the name its id is derived from + /// + /// + /// The declared short name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The created POCO + /// + protected TPoco CreateNamed(string name, string shortName, Func toDto) where TPoco : PocoElement, new() + { + var element = this.Builder.Create(name, toDto); + element.DeclaredName = name; + element.DeclaredShortName = shortName; + element.AliasIds = [$"urn:coverage-model:{name}"]; + + return element; + } + + /// + /// Makes a feature an owned feature of a type, through a or, for an end + /// feature, an , and features it by that type with a + /// + /// + /// The owning type + /// + /// + /// The owned feature + /// + protected void OwnFeature(IType owner, IFeature feature) + { + PocoRelationship membership = feature.IsEnd + ? this.Builder.Create($"{feature.ElementId}/membership", EndFeatureMembershipExtensions.ToDto) + : this.Builder.Create($"{feature.ElementId}/membership", FeatureMembershipExtensions.ToDto); + + owner.AssignOwnership(membership, feature); + + var featuring = this.Builder.Create($"{feature.ElementId}/featuring", TypeFeaturingExtensions.ToDto); + featuring.FeatureOfType = feature; + featuring.FeaturingType = owner; + feature.AssignOwnership(featuring); + } + + /// + /// Makes an element an owned member of a namespace through a new + /// + /// + /// The owning namespace + /// + /// + /// The owned member + /// + protected void OwnMember(PocoElement owner, PocoElement member) + { + var membership = this.Builder.Create($"{member.ElementId}/membership", OwningMembershipExtensions.ToDto); + owner.AssignOwnership(membership, member); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs index 1e6cfb5ec..660545109 100644 --- a/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs @@ -19,6 +19,12 @@ namespace SySML2.NET.REST.Tests.Helpers /// /// The body that an OpenAPI request body or response declares: a schema per media type, or no body at all /// + /// + /// Where the declared schema is a union of object schemas that each fix their @type with a const, as + /// the element schemas are, an object is validated against the member of its @type alone: every other + /// member rejects that @type, so the verdict is the same, its errors are those of that member, and the + /// evaluation skips the other members. + /// public sealed class OpenApiContent { /// @@ -37,9 +43,27 @@ public sealed class OpenApiContent /// /// The schema of the body per declared media type; empty when no body is declared /// - public OpenApiContent(IReadOnlyDictionary schemasByMediaType) + public OpenApiContent(IReadOnlyDictionary schemasByMediaType) : this(schemasByMediaType, new Dictionary(), false) + { + } + + /// + /// Initializes a new instance of the class, with the member schemas of a union + /// + /// + /// The schema of the body per declared media type; empty when no body is declared + /// + /// + /// The member of the declared union for each @type it admits; empty when the schema is no such union + /// + /// + /// Whether the body is an array whose items are of the union, rather than an object of it + /// + public OpenApiContent(IReadOnlyDictionary schemasByMediaType, IReadOnlyDictionary schemasByType, bool isArrayOfTypes) { this.SchemasByMediaType = schemasByMediaType ?? throw new ArgumentNullException(nameof(schemasByMediaType)); + this.SchemasByType = schemasByType ?? throw new ArgumentNullException(nameof(schemasByType)); + this.IsArrayOfTypes = isArrayOfTypes; } /// @@ -47,6 +71,16 @@ public OpenApiContent(IReadOnlyDictionary schemasByMediaType /// public IReadOnlyDictionary SchemasByMediaType { get; } + /// + /// Gets the member of the declared union for each @type it admits; empty when the schema is no such union + /// + public IReadOnlyDictionary SchemasByType { get; } + + /// + /// Gets a value indicating whether the body is an array whose items are of the union + /// + public bool IsArrayOfTypes { get; } + /// /// Checks a body against the declared media types and their schemas /// @@ -96,9 +130,14 @@ public IReadOnlyList Check(string mediaType, string body) using (instance) { + if (this.CheckByType(instance.RootElement) is { } byType) + { + return byType; + } + var results = this.SchemasByMediaType[declared].Evaluate(instance.RootElement, Evaluation); - return results.IsValid ? [] : [.. Summarize(results).Select(error => new ContractViolation(ContractViolationKind.SchemaMismatch, error))]; + return results.IsValid ? [] : [.. Summarize(results, string.Empty).Select(error => new ContractViolation(ContractViolationKind.SchemaMismatch, error))]; } } @@ -224,10 +263,13 @@ private static bool IsWithin(string location, string instance) /// /// The results, in the hierarchical output format /// + /// + /// The location of the evaluated instance in the body, empty for the body itself + /// /// /// At most lines of the form location keyword: message /// - private static IReadOnlyList Summarize(EvaluationResults results) + private static IReadOnlyList Summarize(EvaluationResults results, string location) { var errors = ErrorsOf(results) .Where(error => error.Keyword is not ("anyOf" or "oneOf" or "allOf" or "properties" or "items" or "$ref" or "")) @@ -252,7 +294,51 @@ private static IReadOnlyList Summarize(EvaluationResults results) return errors.Count == 0 ? ["the body does not validate"] - : [.. reported.Take(ReportedErrors).Select(error => $"{(error.Location.Length == 0 ? "/" : error.Location)} {error.Keyword}: {error.Message}")]; + : [.. reported.Take(ReportedErrors).Select(error => $"{(location.Length + error.Location.Length == 0 ? "/" : location + error.Location)} {error.Keyword}: {error.Message}")]; + } + + /// + /// Checks the body against the member of the union for its @type, or for the @type of each of its + /// items + /// + /// + /// The body + /// + /// + /// The violations found, or null when the body cannot be checked by type and the declared schema decides + /// + private IReadOnlyList CheckByType(JsonElement body) + { + if (this.SchemasByType.Count == 0 || (this.IsArrayOfTypes && body.ValueKind != JsonValueKind.Array)) + { + return null; + } + + var instances = this.IsArrayOfTypes + ? body.EnumerateArray().Select((item, index) => (Location: $"/{index}", Instance: item)).ToList() + : [(Location: string.Empty, Instance: body)]; + + var members = new List<(string Location, JsonElement Instance, JsonSchema Schema)>(); + + foreach (var (location, instance) in instances) + { + if (instance.ValueKind != JsonValueKind.Object + || !instance.TryGetProperty("@type", out var type) + || type.ValueKind != JsonValueKind.String + || !this.SchemasByType.TryGetValue(type.GetString()!, out var member)) + { + return null; + } + + members.Add((location, instance, member)); + } + + return [.. members + .Select(entry => (entry.Location, Results: entry.Schema.Evaluate(entry.Instance, Evaluation))) + .Where(entry => !entry.Results.IsValid) + .SelectMany(entry => Summarize(entry.Results, entry.Location)) + .Take(ReportedErrors) + .Select(error => new ContractViolation(ContractViolationKind.SchemaMismatch, error))]; } } } diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs index a6b83d534..8c9184007 100644 --- a/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs @@ -85,7 +85,7 @@ public static OpenApiDocument Load(string path) RemoveIds(schemas); RewriteSchemaReferences(root, keysById); - var reader = new SchemaReader(); + var reader = new SchemaReader(schemas); reader.Build(new JsonObject { @@ -141,11 +141,13 @@ public OpenApiOperation Match(HttpMethod method, string relativePath) private static OpenApiContent ReadContent(JsonObject declaration, SchemaReader reader) { var content = declaration?["content"]?.AsObject() ?? []; + var schema = content.Select(mediaType => mediaType.Value?["schema"]).FirstOrDefault(node => node != null); + var isArray = schema?["type"]?.GetValueKind() == JsonValueKind.String && (string)schema["type"] == "array"; - return new OpenApiContent(content.ToDictionary( - mediaType => mediaType.Key, - mediaType => reader.Build(mediaType.Value?["schema"] ?? new JsonObject()), - StringComparer.OrdinalIgnoreCase)); + return new OpenApiContent( + content.ToDictionary(mediaType => mediaType.Key, mediaType => reader.Build(mediaType.Value?["schema"] ?? new JsonObject()), StringComparer.OrdinalIgnoreCase), + reader.UnionMembers(isArray ? schema["items"] : schema), + isArray); } /// @@ -302,6 +304,26 @@ private static void RewriteSchemaReferences(JsonNode node, IReadOnlyDictionary private sealed class SchemaReader { + /// + /// The prefix of an absolute reference to a component schema + /// + private const string DefinitionReferencePrefix = $"{DefinitionsUri}#/$defs/"; + + /// + /// The keywords that a node of a union may carry besides its alternatives, none of which validates + /// + private static readonly HashSet AnnotationKeywords = ["$ref", "anyOf", "oneOf", "title", "description", "$comment", "examples", "$schema"]; + + /// + /// The component schemas, by name, with their references made absolute + /// + private readonly JsonObject definitions; + + /// + /// The built members of unions, by the schema object they were built from + /// + private readonly Dictionary members = new(ReferenceEqualityComparer.Instance); + /// /// The options that every schema of the document is built with /// @@ -312,6 +334,17 @@ private sealed class SchemaReader /// private int count; + /// + /// Initializes a new instance of the class + /// + /// + /// The component schemas, by name, with their references made absolute + /// + public SchemaReader(JsonObject definitions) + { + this.definitions = definitions; + } + /// /// Builds a schema /// @@ -328,6 +361,91 @@ public JsonSchema Build(JsonNode schema, Uri baseUri = null) { return JsonSchema.Build(JsonSerializer.SerializeToElement(schema), this.options, baseUri ?? new Uri($"{DefinitionsUri}:{++this.count}")); } + + /// + /// Finds the members of the union that a schema is, through its $refs, anyOfs and oneOfs: + /// the object schemas that fix their @type with a const; a @type fixed by two different + /// objects is left out, so that the member of a @type is always the only one that admits it + /// + /// + /// The schema, or null + /// + /// + /// The built member for each @type + /// + public IReadOnlyDictionary UnionMembers(JsonNode schema) + { + var byType = new Dictionary(StringComparer.Ordinal); + var ambiguous = new HashSet(StringComparer.Ordinal); + var visited = new HashSet(StringComparer.Ordinal); + var pending = new Stack(); + + if (schema != null) + { + pending.Push(schema); + } + + while (pending.Count > 0) + { + if (pending.Pop() is not JsonObject node) + { + continue; + } + + if (node["properties"]?["@type"]?["const"] is JsonValue constant && constant.GetValueKind() == JsonValueKind.String) + { + var type = constant.GetValue(); + + if (byType.TryGetValue(type, out var known) && !ReferenceEquals(known, node)) + { + ambiguous.Add(type); + } + + byType.TryAdd(type, node); + continue; + } + + if (node.Any(keyword => !AnnotationKeywords.Contains(keyword.Key))) + { + return new Dictionary(); + } + + if (node["$ref"] is JsonValue reference && reference.GetValue() is { } target && target.StartsWith(DefinitionReferencePrefix, StringComparison.Ordinal) + && visited.Add(target) && this.definitions[target[DefinitionReferencePrefix.Length..]] is { } definition) + { + pending.Push(definition); + } + + foreach (var alternative in new[] { node["anyOf"], node["oneOf"] }.OfType().SelectMany(alternatives => alternatives)) + { + pending.Push(alternative); + } + } + + return byType + .Where(member => !ambiguous.Contains(member.Key)) + .ToDictionary(member => member.Key, member => this.BuildMember(member.Value), StringComparer.Ordinal); + } + + /// + /// Builds the member of a union once, however many unions it belongs to + /// + /// + /// The schema object of the member + /// + /// + /// The built + /// + private JsonSchema BuildMember(JsonObject member) + { + if (!this.members.TryGetValue(member, out var built)) + { + built = this.Build(member); + this.members[member] = built; + } + + return built; + } } } } diff --git a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs index f940bb9f5..96210c851 100644 --- a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs +++ b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs @@ -12,6 +12,7 @@ namespace SySML2.NET.REST.Tests.Helpers using System; using System.Collections.Generic; using System.Linq; + using System.Net; using System.Threading.Tasks; using NUnit.Framework; @@ -24,6 +25,7 @@ namespace SySML2.NET.REST.Tests.Helpers using SysML2.NET.Extensions.Core.DTO.Comparers; using SysML2.NET.PSM; using SysML2.NET.PSM.DTO; + using SysML2.NET.REST.Exceptions; using Direction = SysML2.NET.PSM.Enumerations.Direction; @@ -53,6 +55,16 @@ public sealed class ReadBackAssertions /// private readonly ScenarioState state; + /// + /// Gets the calls that the recorded so far, in order, or null + /// + private readonly Func> recordedCalls; + + /// + /// The known divergences, of which those that break deserialization excuse a failed read + /// + private readonly IReadOnlyList divergences; + /// /// Initializes a new instance of the class /// @@ -62,10 +74,19 @@ public sealed class ReadBackAssertions /// /// The scenario state that read-back data is recorded in /// - public ReadBackAssertions(IPsmApiClient client, ScenarioState state) + /// + /// Gets the calls that the recorded so far, so that a read failing on a response + /// the client cannot be expected to read is told apart from a client defect; null when nothing is recorded + /// + /// + /// The known divergences, when null + /// + public ReadBackAssertions(IPsmApiClient client, ScenarioState state, Func> recordedCalls = null, IReadOnlyList divergences = null) { this.client = client; this.state = state; + this.recordedCalls = recordedCalls; + this.divergences = divergences ?? KnownServerDivergences.All; } /// @@ -134,18 +155,38 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous Guid[] expectedPrevious = previousCommitId.HasValue ? [previousCommitId.Value] : []; - var commitById = await this.client.GetCommitByProjectAndIdAsync(projectId, commit.Id); - var (commits, _) = await ReadAllPagesAsync(parameters => this.client.GetCommitsByProjectAsync(projectId, parameters)); - var branch = await this.client.GetBranchesByProjectAndIdAsync(projectId, branchId); - var (changes, changePages) = await ReadAllPagesAsync(parameters => this.client.GetChangesByProjectCommitAsync(projectId, commit.Id, parameters)); - using (Assert.EnterMultipleScope()) { - Assert.That(commitById.Id, Is.EqualTo(commit.Id)); - Assert.That(commitById.OwningProject, Is.EqualTo(projectId)); - Assert.That(commitById.PreviousCommit, Is.EqualTo(expectedPrevious)); - Assert.That(commits.Select(record => record.Id), Does.Contain(commit.Id)); - Assert.That(branch.Head, Is.EqualTo(commit.Id)); + var commitById = await this.ReadAsync(() => this.client.GetCommitByProjectAndIdAsync(projectId, commit.Id), "GetCommitByProjectAndIdAsync"); + + if (commitById != null) + { + Assert.That(commitById.Id, Is.EqualTo(commit.Id)); + Assert.That(commitById.OwningProject, Is.EqualTo(projectId)); + Assert.That(commitById.PreviousCommit, Is.EqualTo(expectedPrevious)); + } + + var (commits, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetCommitsByProjectAsync(projectId, parameters)), "GetCommitsByProjectAsync"); + + if (commits != null) + { + Assert.That(commits.Select(record => record.Id), Does.Contain(commit.Id)); + } + + var branch = await this.ReadAsync(() => this.client.GetBranchesByProjectAndIdAsync(projectId, branchId), "GetBranchesByProjectAndIdAsync"); + + if (branch != null) + { + Assert.That(branch.Head, Is.EqualTo(commit.Id)); + } + + var (changes, changePages) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetChangesByProjectCommitAsync(projectId, commit.Id, parameters)), "GetChangesByProjectCommitAsync"); + + if (changes == null) + { + return; + } + Assert.That(changes.Select(change => change.Identity.Id), Is.EquivalentTo(changed.Select(element => element.Id))); Assert.That(changePages, Is.GreaterThan(1), "the changes did not span several pages, so paging is untested"); @@ -155,18 +196,20 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous { VerifySame(sentById[change.Identity.Id], change.Payload as IElement, $"the payload of change {change.Id}"); } - } - if (changes.Count == 0) - { - return; - } + if (changes.Count == 0) + { + return; + } - var firstChange = changes[0]; - var changeById = await this.client.GetChangeByProjectCommitIdAsync(projectId, commit.Id, firstChange.Id); + var firstChange = changes[0]; + var changeById = await this.ReadAsync(() => this.client.GetChangeByProjectCommitIdAsync(projectId, commit.Id, firstChange.Id), "GetChangeByProjectCommitIdAsync"); + + if (changeById == null) + { + return; + } - using (Assert.EnterMultipleScope()) - { Assert.That(changeById.Id, Is.EqualTo(firstChange.Id)); Assert.That(changeById.Identity.Id, Is.EqualTo(firstChange.Identity.Id)); @@ -178,51 +221,162 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous } /// - /// Verifies the model at a commit through every element read operation, recording what the server returned + /// Verifies the diff of two commits: one difference per element created, changed or deleted between them, an + /// element of the base commit as updated, and an element added since as created + /// + /// + /// The base commit, whose expected model is known + /// + /// + /// The compare commit + /// + /// + /// The elements created or changed between the two commits + /// + /// + /// An awaitable + /// + public async Task VerifyDiffAsync(Guid baseCommitId, Guid compareCommitId, IReadOnlyList changed) + { + var projectId = this.state.ProjectId!.Value; + var notImplemented = false; + + using (Assert.EnterMultipleScope()) + { + var (differences, _) = await this.ReadAsync(async () => + { + try + { + return await ReadAllPagesAsync(parameters => this.client.DiffAsync(projectId, baseCommitId, compareCommitId, parameters)); + } + catch (PsmApiException exception) when (exception.StatusCode == HttpStatusCode.NotImplemented) + { + notImplemented = true; + return (null, 0); + } + }, "DiffAsync"); + + if (notImplemented) + { + KnownServerDivergences.Report(KnownServerDivergences.DiffNotImplemented, $"DiffAsync from {baseCommitId} to {compareCommitId} answered 501"); + return; + } + + if (differences == null) + { + return; + } + + var atBase = this.state.ExpectedModels[baseCommitId].Select(element => element.Id).ToHashSet(); + var compared = differences.Where(difference => difference.CompareData?.Identity != null).ToList(); + + Assert.That(differences, Has.None.Matches(difference => (difference.CompareData ?? difference.BaseData)?.Identity == null), "a difference names the data it is about"); + Assert.That(differences.Select(difference => (difference.CompareData ?? difference.BaseData)?.Identity?.Id), Is.EquivalentTo(changed.Select(element => (Guid?)element.Id))); + Assert.That(compared.Where(difference => atBase.Contains(difference.CompareData.Identity.Id)), Has.All.Matches(difference => difference.BaseData != null), "an element of the base commit is UPDATED"); + Assert.That(compared.Where(difference => !atBase.Contains(difference.CompareData.Identity.Id)), Has.All.Matches(difference => difference.BaseData == null), "an element added since is CREATED"); + } + } + + /// + /// Verifies that the history is immutable: an element read at an earlier commit is still the version of that + /// commit + /// + /// + /// The earlier commit + /// + /// + /// The element as it was at + /// + /// + /// An awaitable + /// + public async Task VerifyHistoryAsync(Guid earlierCommitId, IElement expected) + { + var description = $"{expected.GetType().Name} {expected.Id} at the earlier commit {earlierCommitId}"; + var (succeeded, actual) = await this.TryReadAsync(() => this.client.GetElementByProjectCommitIdAsync(this.state.ProjectId!.Value, earlierCommitId, expected.Id), $"GetElementByProjectCommitIdAsync of {description}"); + + if (succeeded) + { + VerifySame(expected, actual, description); + } + } + + /// + /// Verifies the model at a commit through every element read operation, recording what the server returned: + /// the elements the commit changed are read by id, and every element is compared as listed /// + /// + /// An element that the commit did not change was read by id at the commit that last changed it; reading it + /// by id again would repeat that check against a growing model, so its content is compared in the list. + /// /// /// The commit to read the model at /// /// /// The complete model expected at /// + /// + /// The elements that the commit created or changed + /// /// /// The element whose relationships are read in each direction /// /// /// An awaitable /// - public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expected, Guid relationshipSubjectId) + public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expected, IReadOnlyList changed, Guid relationshipSubjectId) { var projectId = this.state.ProjectId!.Value; var readById = new Dictionary(); - foreach (var element in expected) + using (Assert.EnterMultipleScope()) { - readById[element.Id] = await this.client.GetElementByProjectCommitIdAsync(projectId, commitId, element.Id); - } + foreach (var element in changed) + { + var (succeeded, actual) = await this.TryReadAsync(() => this.client.GetElementByProjectCommitIdAsync(projectId, commitId, element.Id), $"GetElementByProjectCommitIdAsync of {element.GetType().Name} {element.Id}"); - this.state.ReadBack.AddRange(readById.Values.Select(element => (commitId, (IData)element))); + if (succeeded) + { + readById[element.Id] = actual; + } + } - var (listed, listPages) = await ReadAllPagesAsync(parameters => this.client.GetElementsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)); - var (roots, _) = await ReadAllPagesAsync(parameters => this.client.GetRootsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)); + var read = changed.Where(element => readById.ContainsKey(element.Id)).ToList(); - using (Assert.EnterMultipleScope()) - { - foreach (var element in expected) + foreach (var element in read) { VerifySame(element, readById[element.Id], $"{element.GetType().Name} {element.Id}"); } - Assert.That(listed.Select(element => element.Id), Is.EquivalentTo(expected.Select(element => element.Id))); - Assert.That(listPages, Is.GreaterThan(1), "the elements did not span several pages, so paging is untested"); - VerifyRoots(roots, expected); + var (listed, listPages) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetElementsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)), "GetElementsByProjectCommitAsync"); + + this.state.ReadBack.AddRange((listed ?? [.. readById.Values]).Select(element => (commitId, (IData)element))); + + if (listed != null) + { + Assert.That(listed.Select(element => element.Id), Is.EquivalentTo(expected.Select(element => element.Id))); + Assert.That(listPages, Is.GreaterThan(1), "the elements did not span several pages, so paging is untested"); + + var listedById = listed.GroupBy(element => element.Id).ToDictionary(group => group.Key, group => group.First()); + + foreach (var element in expected.Where(element => !readById.ContainsKey(element.Id) && listedById.ContainsKey(element.Id))) + { + VerifySame(element, listedById[element.Id], $"{element.GetType().Name} {element.Id} as listed"); + } + } + + var (roots, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetRootsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)), "GetRootsByProjectCommitAsync"); + + if (roots != null) + { + VerifyRoots(roots, expected); + } - VerifyMemberships(expected, readById); + VerifyMemberships(read, readById); VerifyNoEmptyReferences(readById.Values); - } - await this.VerifyRelationshipsAsync(commitId, expected, relationshipSubjectId); + await this.VerifyRelationshipsAsync(commitId, expected, relationshipSubjectId); + } } /// @@ -275,6 +429,10 @@ private static void VerifyNoEmptyReferences(IEnumerable elements) /// , exactly the elements without an /// owningRelatedElement /// + /// + /// KerML derives owner as owningRelationship.owningRelatedElement, so an element has no owner exactly + /// when it has no owningRelationship, which is not derived and is known for every element sent. + /// /// /// The roots read back /// @@ -284,7 +442,7 @@ private static void VerifyNoEmptyReferences(IEnumerable elements) private static void VerifyRoots(IReadOnlyList roots, IReadOnlyList model) { var rootIds = roots.Select(element => element.Id).ToHashSet(); - var unowned = model.Where(element => element.owner == null).Select(element => element.Id).ToList(); + var unowned = model.Where(element => element.OwningRelationship == null).Select(element => element.Id).ToList(); var notOwnedRelated = model.Where(element => element is not IRelationship { OwningRelatedElement: not null }).Select(element => element.Id).ToList(); if (!rootIds.SetEquals(unowned) && roots.Count == notOwnedRelated.Count && rootIds.SetEquals(notOwnedRelated)) @@ -326,6 +484,78 @@ private static void VerifySame(IElement sent, IElement actual, string descriptio Assert.Fail($"{description} differs from what was sent: {(differing.Count == 0 ? "a member that only its comparer compares" : string.Join(", ", differing))}"); } + /// + /// Reads from the server, reporting a read that throws as a failure, so that the checks that do not depend on + /// it still run + /// + /// + /// The type of what is read + /// + /// + /// The read + /// + /// + /// The description of the read in the failure message + /// + /// + /// What was read, or the default of when the read threw + /// + private async Task ReadAsync(Func> read, string description) + { + var (_, value) = await this.TryReadAsync(read, description); + + return value; + } + + /// + /// Reads from the server, reporting a read that throws as a failure, or as a warning when a response of that + /// read shows a known divergence that breaks deserialization, which reports + /// + /// + /// Only the calls recorded while the read ran count, and only divergences that break deserialization: every + /// Flexo response breaks the document in some tolerated way, and a client defect must still fail. + /// + /// + /// The type of what is read + /// + /// + /// The read + /// + /// + /// The description of the read in the failure message + /// + /// + /// Whether the read succeeded, and what was read + /// + private async Task<(bool Succeeded, T Value)> TryReadAsync(Func> read, string description) + { + var callsBefore = this.recordedCalls?.Invoke().Count ?? 0; + + try + { + return (true, await read()); + } + catch (Exception exception) when (exception is not ResultStateException) + { + var failure = $"{description} threw {exception.GetType().Name}: {exception.Message}"; + + var excused = (this.recordedCalls?.Invoke() ?? []).Skip(callsBefore) + .SelectMany(call => call.ResponseViolations.Select(violation => (Call: call, Divergence: this.divergences.FirstOrDefault(divergence => divergence.BreaksDeserialization && divergence.Explains?.Invoke(call, violation) == true)))) + .FirstOrDefault(entry => entry.Divergence != null); + + if (excused.Divergence != null) + { + Assert.Warn($"{failure}, on a response that shows the known divergence that {excused.Divergence.Summary} ({excused.Call.RequestLine}); the OpenAPI conformance check reports the response"); + } + else + { + Assert.Fail(failure); + } + + return (false, default); + } + } + /// /// Verifies the relationships of an element in each direction against the sources and targets that were sent /// @@ -349,17 +579,22 @@ private async Task VerifyRelationshipsAsync(Guid commitId, IReadOnlyList relationship.Source.Contains(subjectId)).Select(relationship => relationship.Id).ToList(); var incoming = relationships.Where(relationship => relationship.Target.Contains(subjectId)).Select(relationship => relationship.Id).ToList(); - var (readOut, _) = await ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, Direction.@out, queryParameters: parameters)); - var (readIn, _) = await ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, Direction.@in, queryParameters: parameters)); - var (readBoth, _) = await ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, Direction.both, queryParameters: parameters)); + (Direction Direction, List Expected)[] directions = [(Direction.@out, outgoing), (Direction.@in, incoming), (Direction.both, [.. outgoing.Union(incoming)])]; using (Assert.EnterMultipleScope()) { Assert.That(outgoing, Is.Not.Empty, "the subject is the source of no relationship, so the out direction is untested"); Assert.That(incoming, Is.Not.Empty, "the subject is the target of no relationship, so the in direction is untested"); - Assert.That(readOut.Select(relationship => relationship.Id), Is.EquivalentTo(outgoing)); - Assert.That(readIn.Select(relationship => relationship.Id), Is.EquivalentTo(incoming)); - Assert.That(readBoth.Select(relationship => relationship.Id), Is.EquivalentTo(outgoing.Union(incoming))); + + foreach (var (direction, expectedIds) in directions) + { + var (read, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, direction, queryParameters: parameters)), $"GetRelationshipsByProjectCommitRelatedElementAsync {direction}"); + + if (read != null) + { + Assert.That(read.Select(relationship => relationship.Id), Is.EquivalentTo(expectedIds), $"the {direction} relationships"); + } + } } } } diff --git a/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs index fc7e88770..0c9469f09 100644 --- a/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs +++ b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs @@ -46,5 +46,10 @@ public sealed class ScenarioState /// Gets every data item the server returned, with the commit it was read at /// public List<(Guid CommitId, IData Data)> ReadBack { get; } = []; + + /// + /// Gets the ids of the tags the scenario created, by name + /// + public Dictionary TagIds { get; } = []; } } diff --git a/SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs b/SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs index ad6f512a5..dd2adb65f 100644 --- a/SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs +++ b/SySML2.NET.REST.Tests/Helpers/ServerDivergence.cs @@ -23,5 +23,9 @@ namespace SySML2.NET.REST.Tests.Helpers /// /// Whether the divergence explains a contract violation of a response, or null when it explains none /// - public sealed record ServerDivergence(string Summary, string Reference, Func Explains = null); + /// + /// Whether a response showing the divergence cannot be read by a client that follows the OpenAPI document, so that + /// a read failing on it is no client defect + /// + public sealed record ServerDivergence(string Summary, string Reference, Func Explains = null, bool BreaksDeserialization = false); } diff --git a/SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs index 4729dc0f4..0f891d4ca 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/EndpointRecorderTestFixture.cs @@ -61,6 +61,8 @@ public void VerifyEndpointRecorder() Assert.That(this.recorder.Calls, Is.Empty); Assert.That(this.recorder.EmptyGuidRequests, Is.Empty); Assert.That(this.recorder.LastCall, Is.Null); + Assert.That(this.recorder.ServerTime, Is.EqualTo(TimeSpan.Zero)); + Assert.That(this.recorder.CheckTime, Is.EqualTo(TimeSpan.Zero)); } } @@ -100,6 +102,8 @@ public async Task VerifySendAsync() Assert.That(calls[4].Operation, Is.Null); Assert.That(calls[4].ResponseViolations, Is.Empty); Assert.That(this.recorder.EmptyGuidRequests, Is.EqualTo((string[])["POST /projects"])); + Assert.That(this.recorder.ServerTime, Is.GreaterThan(TimeSpan.Zero)); + Assert.That(this.recorder.CheckTime, Is.GreaterThan(TimeSpan.Zero)); } } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs index 8b78af677..443956b74 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs @@ -36,7 +36,7 @@ public void VerifyAll() { using (Assert.EnterMultipleScope()) { - Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri])); + Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.DiffNotImplemented, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri])); Assert.That(KnownServerDivergences.All.Select(divergence => divergence.Reference), Has.All.Contains("Open-MBEE/flexo-mms-sysmlv2@836d904d")); } } @@ -149,6 +149,22 @@ public async Task VerifyExpectNotFoundAsync() await Assert.ThatAsync(() => KnownServerDivergences.ExpectNotFoundAsync(() => throw new InvalidOperationException("a client defect"), () => Conforming, notFound), Throws.InvalidOperationException); } + [Test] + public void VerifyPreviousCommitAsObject() + { + var explains = KnownServerDivergences.PreviousCommitAsObject.Explains; + var call = Conforming with { StatusCode = HttpStatusCode.OK }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/previousCommit type: Value is \"object\" but should be \"array\"")), Is.True); + Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/0/previousCommit type: Value is \"object\" but should be \"array\"")), Is.True); + Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/change type: Value is \"object\" but should be \"array\"")), Is.False); + Assert.That(explains(call, new ContractViolation(ContractViolationKind.InvalidJson, "/previousCommit type: Value is \"object\" but should be \"array\"")), Is.False); + Assert.That(KnownServerDivergences.All.Where(divergence => divergence.BreaksDeserialization), Is.EqualTo((ServerDivergence[])[KnownServerDivergences.PreviousCommitAsObject])); + } + } + [Test] public void VerifyRecordsWithoutRequiredProperties() { diff --git a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs index 88dc9cc89..f66fb6dce 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs @@ -24,6 +24,52 @@ namespace SySML2.NET.REST.Tests.HelpersTests [TestFixture] public class ModelBuilderTestFixture { + [Test] + public void VerifyBeginStep() + { + var builder = new ModelBuilder("first"); + var first = builder.Create("Package", PackageExtensions.ToDto); + + builder.BeginStep("second"); + + var second = builder.Create("Package", PackageExtensions.ToDto); + + using (Assert.EnterMultipleScope()) + { + Assert.That(second.Id, Is.EqualTo(DeterministicGuid.Create("second/Package"))); + Assert.That(second.Id, Is.Not.EqualTo(first.Id)); + Assert.That(builder.ToDtos().Select(dto => dto.Id), Is.EqualTo((Guid[])[first.Id, second.Id])); + Assert.That(() => builder.Create("Package", PackageExtensions.ToDto), Throws.ArgumentException.With.Message.Contains("second")); + } + } + + [Test] + public void VerifyChanged() + { + var builder = new ModelBuilder("scope"); + var owner = builder.Create("Owner", PackageExtensions.ToDto); + var untouched = builder.Create("Untouched", PackageExtensions.ToDto); + owner.DeclaredName = "Owner"; + + var before = builder.ToDtos(); + + Assert.That(ModelBuilder.Changed([], before), Is.EqualTo(before)); + Assert.That(ModelBuilder.Changed(before, builder.ToDtos()), Is.Empty); + + owner.DeclaredName = "Renamed"; + var added = builder.Create("Added", PackageExtensions.ToDto); + + var after = builder.ToDtos(); + var changed = ModelBuilder.Changed(before, after); + + using (Assert.EnterMultipleScope()) + { + Assert.That(changed.Select(dto => dto.Id), Is.EqualTo((Guid[])[owner.Id, added.Id])); + Assert.That(changed[0], Is.SameAs(after[0])); + Assert.That(changed.Select(dto => dto.Id), Does.Not.Contain(untouched.Id)); + } + } + [Test] public void VerifyCreate() { @@ -47,10 +93,15 @@ public void VerifyToDtos() var package = builder.Create("Package", PackageExtensions.ToDto); package.DeclaredName = "Package"; + package.AliasIds = ["first"]; + var dtos = builder.ToDtos(); + package.AliasIds.Add("second"); + using (Assert.EnterMultipleScope()) { + Assert.That(dtos[0].AliasIds, Is.EqualTo((string[])["first"]), "a DTO keeps the aliases it was converted with"); Assert.That(dtos, Has.Count.EqualTo(1)); Assert.That(dtos[0], Is.TypeOf()); Assert.That(dtos[0].Id, Is.EqualTo(package.Id)); @@ -60,11 +111,54 @@ public void VerifyToDtos() var failing = new ModelBuilder("scope"); failing.Create("Broken", (_, _) => throw new NotSupportedException("no conversion")); + var partial = new ModelBuilder("scope"); + var withoutDerived = partial.Create("WithoutDerived", (poco, includeDerived) => includeDerived ? throw new NullReferenceException("no library") : PackageExtensions.ToDto(poco, false)); + partial.Create("Complete", PackageExtensions.ToDto); + + var partialDtos = partial.ToDtos(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(builder.WithoutDerivedValues, Is.Empty); + Assert.That(partialDtos.Select(dto => dto.Id), Does.Contain(withoutDerived.Id)); + Assert.That(partial.WithoutDerivedValues, Is.EqualTo((string[])["scope/WithoutDerived"])); + } + Assert.That(failing.ToDtos, Throws.InvalidOperationException .With.Message.Contains("scope/Broken").And.Message.Contains(nameof(Package)) .And.InnerException.TypeOf()); } + [Test] + public void VerifyElements() + { + var builder = new ModelBuilder("scope"); + var first = builder.Create("First", PackageExtensions.ToDto); + var second = builder.Create("Second", PackageExtensions.ToDto); + + using (Assert.EnterMultipleScope()) + { + Assert.That(builder.Elements.Select(entry => entry.Name), Is.EqualTo((string[])["scope/First", "scope/Second"])); + Assert.That(builder.Elements[0].Element, Is.SameAs(first)); + Assert.That(builder.Elements[1].Element, Is.SameAs(second)); + Assert.That(new ModelBuilder("empty").Elements, Is.Empty); + } + } + + [Test] + public void VerifyFind() + { + var builder = new ModelBuilder("scope"); + var package = builder.Create("Package", PackageExtensions.ToDto); + + using (Assert.EnterMultipleScope()) + { + Assert.That(builder.Find("scope/Package"), Is.SameAs(package)); + Assert.That(() => builder.Find("scope/Missing"), Throws.ArgumentException.With.Message.Contains("scope/Missing")); + Assert.That(() => builder.Find("scope/Package"), Throws.ArgumentException); + } + } + [Test] public void VerifyToCommitRequest() { diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs new file mode 100644 index 000000000..e12b3a22e --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs @@ -0,0 +1,65 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System.IO; + using System.Linq; + using System.Text; + using System.Text.Json; + + using NUnit.Framework; + + using SysML2.NET.Serializer.Json; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + [TestFixture] + public class CoreModelTestFixture + { + private static readonly string[] CoreMetaclasses = + [ + "Type", "Classifier", "Feature", "Specialization", "Subclassification", "FeatureTyping", "Subsetting", "Redefinition", + "ReferenceSubsetting", "CrossSubsetting", "Conjugation", "Disjoining", "Differencing", "Intersecting", "Unioning", + "FeatureChaining", "FeatureInverting", "TypeFeaturing", "FeatureMembership", "EndFeatureMembership", "Multiplicity" + ]; + + [Test] + public void VerifyCoreModel() + { + Assert.That(() => new CoreModel(null), Throws.ArgumentNullException); + + var root = new RootModel(); + var atStep2 = root.Builder.ToDtos(); + var model = new CoreModel(root); + + var dtos = model.Builder.ToDtos(); + var changed = ModelBuilder.Changed(atStep2, dtos); + + using var stream = new MemoryStream(); + new Serializer().SerializeRequest(ModelBuilder.ToCommitRequest(changed, "core model"), SerializationModeKind.JSON, false, stream, new JsonWriterOptions()); + var json = Encoding.UTF8.GetString(stream.ToArray()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(dtos.Select(dto => dto.GetType().Name).Distinct(), Is.SupersetOf(CoreMetaclasses)); + Assert.That(changed.Select(dto => dto.Id), Does.Contain(root.Root.Id), "the root package owns the new package"); + Assert.That(changed.Select(dto => dto.Id), Does.Not.Contain(root.Nested.Id)); + Assert.That(changed, Has.Count.EqualTo(dtos.Count - atStep2.Count + 1)); + Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); + Assert.That(model.Builder.WithoutDerivedValues, Is.Empty); + Assert.That(model.FirstEnd.IsEnd && model.SecondEnd.IsEnd, Is.True); + } + + Assert.That(new CoreModel(new RootModel()).Builder.ToDtos().Select(dto => dto.Id), Is.EqualTo(dtos.Select(dto => dto.Id))); + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs new file mode 100644 index 000000000..5aa26dc15 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs @@ -0,0 +1,155 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using NUnit.Framework; + + using SysML2.NET.Core.DTO.Kernel.Packages; + using SysML2.NET.Core.DTO.Root.Elements; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using PocoFeature = SysML2.NET.Core.POCO.Core.Features.Feature; + using PocoFeatureTyping = SysML2.NET.Core.POCO.Core.Features.FeatureTyping; + + [TestFixture] + public class KerMLUpdateModelTestFixture + { + private static readonly string[] OwningMemberships = ["OwningMembership", "FeatureMembership", "EndFeatureMembership", "ParameterMembership", "ReturnParameterMembership", "ResultExpressionMembership", "FeatureValue", "ElementFilterMembership"]; + + private static readonly (string Metaclass, string Element, string Property)[] Retargets = + [ + ("Annotation", "root/Note/about Nested", "Annotation.AnnotatedElement"), + ("Dependency", "root/Uses", "Dependency.Supplier"), + ("NamespaceImport", "root/Nested/import Library", "NamespaceImport.ImportedNamespace"), + ("MembershipImport", "root/Nested/import LibAlias", "MembershipImport.ImportedMembership"), + ("Membership", "root/Space/LibAlias", "Membership.MemberElement"), + ("FeatureTyping", "core/f/typing", "FeatureTyping.Type"), + ("Subsetting", "core/f/subsetting", "Subsetting.SubsettedFeature"), + ("Redefinition", "core/r/redefinition", "Redefinition.RedefinedFeature"), + ("ReferenceSubsetting", "core/k/reference", "ReferenceSubsetting.ReferencedFeature"), + ("CrossSubsetting", "core/e1/cross", "CrossSubsetting.CrossedFeature"), + ("Specialization", "core/U/specialization", "Specialization.General"), + ("Subclassification", "kernel/M/subclassification", "Subclassification.Superclassifier"), + ("Conjugation", "core/T/conjugation", "Conjugation.OriginalType"), + ("Disjoining", "core/C/disjoining", "Disjoining.DisjoiningType"), + ("Unioning", "core/U/unioning 0", "Unioning.UnioningType"), + ("Intersecting", "core/U/intersecting 0", "Intersecting.IntersectingType"), + ("Differencing", "core/U/differencing 0", "Differencing.DifferencingType"), + ("FeatureChaining", "core/cf/chaining 1", "FeatureChaining.ChainingFeature"), + ("FeatureInverting", "core/k/inverting", "FeatureInverting.InvertingFeature"), + ("Connector", "kernel/k/target/reference", "ReferenceSubsetting.ReferencedFeature"), + ("BindingConnector", "kernel/bc/target/reference", "ReferenceSubsetting.ReferencedFeature"), + ("Succession", "kernel/su/first/reference", "ReferenceSubsetting.ReferencedFeature"), + ("Flow", "kernel/fl/source/reference", "ReferenceSubsetting.ReferencedFeature"), + ("SuccessionFlow", "kernel/sf/source/reference", "ReferenceSubsetting.ReferencedFeature"), + ("Association", "kernel/As/e2 typing", "FeatureTyping.Type"), + ("AssociationStructure", "kernel/AsS/e2 typing", "FeatureTyping.Type"), + ("Interaction", "kernel/I/e2 typing", "FeatureTyping.Type") + ]; + + [Test] + public void VerifyKerMLUpdateModel() + { + var root = new RootModel(); + var core = new CoreModel(root); + var kernel = new KernelModel(root, core); + + using (Assert.EnterMultipleScope()) + { + Assert.That(() => new KerMLUpdateModel(null, core, kernel), Throws.ArgumentNullException); + Assert.That(() => new KerMLUpdateModel(root, null, kernel), Throws.ArgumentNullException); + Assert.That(() => new KerMLUpdateModel(root, core, null), Throws.ArgumentNullException); + } + + root = new RootModel(); + core = new CoreModel(root); + kernel = new KernelModel(root, core); + + var atStep4 = kernel.Builder.ToDtos(); + var before = atStep4.ToDictionary(dto => dto.Id); + var metaclassesAtStep4 = atStep4.Select(dto => dto.GetType()).Distinct().ToList(); + var model = new KerMLUpdateModel(root, core, kernel); + + var dtos = model.Builder.ToDtos(); + var byId = dtos.ToDictionary(dto => dto.Id); + var changed = ModelBuilder.Changed(atStep4, dtos); + var updated = dtos.Where(dto => before.ContainsKey(dto.Id)).ToList(); + + var withoutU2ToU4 = metaclassesAtStep4 + .Where(metaclass => metaclass.Name != "TypeFeaturing" && !updated.Any(dto => dto.GetType() == metaclass && DiffersBeyondNames(before[dto.Id], dto))) + .Select(metaclass => metaclass.Name); + + var relationshipMetaclasses = metaclassesAtStep4.Where(typeof(IRelationship).IsAssignableFrom).Select(metaclass => metaclass.Name); + + var notRetargeted = Retargets + .Where(retarget => !Differs(before, byId, Element(model.Builder, retarget.Element).Id, retarget.Property)) + .Select(retarget => retarget.Metaclass); + + var corePackage = (Package)byId[core.Package.Id]; + var corePackageBefore = (Package)before[core.Package.Id]; + var chain = model.Builder.Find("kerml update/cf2"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos, Has.Count.GreaterThan(atStep4.Count)); + Assert.That(changed.Select(dto => dto.Id), Does.Contain(model.Added.Id).And.Contain(core.Package.Id)); + Assert.That(metaclassesAtStep4.Where(metaclass => !changed.Any(dto => dto.GetType() == metaclass && dto.DeclaredName?.EndsWith(" renamed") == true)), Is.Empty, "U1: every metaclass has a renamed instance"); + Assert.That(withoutU2ToU4, Is.Empty, "every metaclass but TypeFeaturing gets one of U2 to U4"); + Assert.That(relationshipMetaclasses, Is.EquivalentTo(Retargets.Select(retarget => retarget.Metaclass).Concat(OwningMemberships).Append("TypeFeaturing").Distinct()), "every relationship metaclass is retargeted or exempt"); + Assert.That(notRetargeted, Is.Empty, "U3: the end of each listed relationship changed"); + Assert.That(Value(byId, Element(model.Builder, "root/Nested/import Library").Id, "Import.IsRecursive"), Is.False); + Assert.That(Value(byId, Element(model.Builder, "root/Nested/import Library").Id, "NamespaceImport.ImportedNamespace"), Is.EqualTo(Element(model.Builder, "root/Space").Id)); + Assert.That(Value(byId, Element(model.Builder, "kernel/a/value/42").Id, "LiteralInteger.Value"), Is.EqualTo(43)); + Assert.That(Value(byId, Element(model.Builder, "kernel/inv").Id, "Invariant.IsNegated"), Is.False); + Assert.That(corePackage.OwnedRelationship, Is.EqualTo((Guid[])[.. corePackageBefore.OwnedRelationship, chain.OwningRelationship.Id, model.Added.OwningRelationship.Id]), "U4: Core is extended"); + Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo((string[])["kernel/sum", "kernel/index", "kernel/select", "kernel/collect", "kernel/chain"])); + } + } + + private static bool Differs(IReadOnlyDictionary before, IReadOnlyDictionary after, Guid id, string property) + { + return !DtoMetadata.ValueEquals(Value(before, id, property), Value(after, id, property)); + } + + private static bool DiffersBeyondNames(IElement before, IElement after) + { + return DtoMetadata.PropertiesOf(after.GetType()) + .Where(property => property.Name is not ("Element.DeclaredName" or "Element.DeclaredShortName")) + .Any(property => !DtoMetadata.ValueEquals(property.ValueOf(before), property.ValueOf(after))); + } + + private static PocoElement Element(ModelBuilder builder, string name) + { + if (!name.EndsWith(" typing", StringComparison.Ordinal)) + { + return builder.Find(name); + } + + return builder.Find(name[..^" typing".Length]).OwnedRelationship.OfType().Single(); + } + + private static object Value(IReadOnlyDictionary dtos, Guid id, string property) + { + var dto = dtos[id]; + + var metamodelProperty = DtoMetadata.PropertiesOf(dto.GetType()).SingleOrDefault(candidate => candidate.Name == property) + ?? throw new ArgumentException($"{dto.GetType().Name} has no non-derived property {property}", nameof(property)); + + return metamodelProperty.ValueOf(dto); + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/KernelModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/KernelModelTestFixture.cs new file mode 100644 index 000000000..29500187e --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/KernelModelTestFixture.cs @@ -0,0 +1,78 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System.IO; + using System.Linq; + using System.Text; + using System.Text.Json; + + using NUnit.Framework; + + using SysML2.NET.Serializer.Json; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + [TestFixture] + public class KernelModelTestFixture + { + private static readonly string[] KernelMetaclasses = + [ + "Association", "AssociationStructure", "Behavior", "ParameterMembership", "Step", "Class", "BindingConnector", "Connector", + "Succession", "DataType", "CollectExpression", "ConstructorExpression", "FeatureChainExpression", "FeatureReferenceExpression", + "IndexExpression", "InvocationExpression", "LiteralBoolean", "LiteralExpression", "LiteralInfinity", "LiteralInteger", + "LiteralRational", "LiteralString", "MetadataAccessExpression", "NullExpression", "OperatorExpression", "SelectExpression", + "FeatureValue", "BooleanExpression", "Expression", "Function", "Invariant", "Predicate", "ResultExpressionMembership", + "ReturnParameterMembership", "Flow", "FlowEnd", "Interaction", "PayloadFeature", "SuccessionFlow", "Metaclass", + "MetadataFeature", "MultiplicityRange", "Structure" + ]; + + [Test] + public void VerifyKernelModel() + { + var root = new RootModel(); + var core = new CoreModel(root); + + using (Assert.EnterMultipleScope()) + { + Assert.That(() => new KernelModel(null, core), Throws.ArgumentNullException); + Assert.That(() => new KernelModel(root, null), Throws.ArgumentNullException); + } + + root = new RootModel(); + core = new CoreModel(root); + var atStep3 = core.Builder.ToDtos(); + var model = new KernelModel(root, core); + + var dtos = model.Builder.ToDtos(); + var changed = ModelBuilder.Changed(atStep3, dtos); + var changedIds = changed.Select(dto => dto.Id).ToList(); + + using var stream = new MemoryStream(); + new Serializer().SerializeRequest(ModelBuilder.ToCommitRequest(changed, "kernel model"), SerializationModeKind.JSON, false, stream, new JsonWriterOptions()); + var json = Encoding.UTF8.GetString(stream.ToArray()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(dtos.Select(dto => dto.GetType().Name).Distinct(), Is.SupersetOf(KernelMetaclasses)); + Assert.That(changedIds, Does.Contain(root.Root.Id).And.Contain(core.FirstEnd.Id).And.Contain(core.SecondEnd.Id)); + Assert.That(changedIds, Does.Not.Contain(core.A.Id)); + Assert.That(changed, Has.Count.EqualTo(dtos.Count - atStep3.Count + 3)); + Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); + Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo((string[])["kernel/sum", "kernel/index", "kernel/select", "kernel/collect", "kernel/chain"]), "only the operator expressions, whose instantiated type needs the model library"); + } + + var again = new RootModel(); + Assert.That(new KernelModel(again, new CoreModel(again)).Builder.ToDtos().Select(dto => dto.Id), Is.EqualTo(dtos.Select(dto => dto.Id))); + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs index f2e44511d..15b933e3c 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/RootModelTestFixture.cs @@ -48,6 +48,7 @@ public void VerifyRootModel() Assert.That(owningMemberships.Select(membership => ((IMembership)membership).MemberElement), Is.EquivalentTo(owningMemberships.Select(membership => membership.OwnedRelatedElement[0]))); Assert.That(commitRequest.Change, Has.Count.EqualTo(dtos.Count)); Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); + Assert.That(model.Builder.WithoutDerivedValues, Is.Empty); } Assert.That(new RootModel().Builder.ToDtos().Select(dto => dto.Id), Is.EqualTo(dtos.Select(dto => dto.Id))); diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs index 8b2b64a09..94ecac247 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs @@ -71,6 +71,35 @@ public void VerifyCheck() } } + [Test] + public void VerifyCheckByType() + { + var full = JsonSchema.FromText(MetaclassSchema); + var a = JsonSchema.FromText("{\"type\":\"object\",\"properties\":{\"@type\":{\"const\":\"A\"},\"a\":{\"type\":\"string\"}},\"required\":[\"@type\",\"a\"]}"); + var b = JsonSchema.FromText("{\"type\":\"object\",\"properties\":{\"@type\":{\"const\":\"B\"},\"b\":{\"type\":\"string\"}},\"required\":[\"@type\",\"b\"]}"); + var byType = new Dictionary { ["A"] = a, ["B"] = b }; + var single = new OpenApiContent(new Dictionary { ["application/json"] = full }, byType, false); + var list = new OpenApiContent(new Dictionary { ["application/json"] = JsonSchema.FromText("{\"type\":\"array\"}") }, byType, true); + + Assert.That(() => new OpenApiContent(new Dictionary(), null, false), Throws.ArgumentNullException); + + var missingB = single.Check("application/json", "{\"@type\":\"B\"}"); + var listMissingB = list.Check("application/json", "[{\"@type\":\"A\",\"a\":\"x\"},{\"@type\":\"B\"}]"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(single.SchemasByType, Is.SameAs(byType)); + Assert.That(list.IsArrayOfTypes, Is.True); + Assert.That(single.Check("application/json", "{\"@type\":\"A\",\"a\":\"x\"}"), Is.Empty); + Assert.That(missingB.Select(violation => violation.Message), Is.EqualTo((string[])["/ required: Required properties [\"b\"] are not present"])); + Assert.That(list.Check("application/json", "[{\"@type\":\"A\",\"a\":\"x\"},{\"@type\":\"B\",\"b\":\"y\"}]"), Is.Empty); + Assert.That(listMissingB.Select(violation => violation.Message), Is.EqualTo((string[])["/1 required: Required properties [\"b\"] are not present"])); + Assert.That(single.Check("application/json", "{\"@type\":\"C\"}")[0].Message, Does.Contain("@type const"), "an unknown @type is left to the declared schema"); + Assert.That(Kinds(single.Check("application/json", "5")), Is.Not.Empty.And.All.EqualTo(ContractViolationKind.SchemaMismatch), "a body that is no object is left to the declared schema"); + Assert.That(list.Check("application/json", "{\"@type\":\"A\",\"a\":\"x\"}"), Is.Not.Empty, "an object where an array is declared is left to the declared schema"); + } + } + private static IReadOnlyList Kinds(IReadOnlyList violations) => violations.Select(violation => violation.Kind).ToList(); } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs index d68cf96f1..7cb9a7e06 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiDocumentTestFixture.cs @@ -54,6 +54,33 @@ public class OpenApiDocumentTestFixture } """; + private const string UnionDocument = """ + { + "openapi": "3.1.0", + "paths": { + "/u": { + "get": { + "responses": { + "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Union" } } } } + } + } + } + }, + "components": { + "schemas": { + "Union": { + "anyOf": [ + { "type": "object", "properties": { "@type": { "const": "T1" }, "a": { "type": "string" } } }, + { "type": "object", "properties": { "@type": { "const": "T1" }, "b": { "type": "string" } } }, + { "type": "object", "properties": { "@type": { "const": "T2" } } }, + { "$ref": "#/components/schemas/Union" } + ] + } + } + } + } + """; + private OpenApiDocument openApi; private string smallDocumentPath; @@ -109,6 +136,44 @@ public void VerifyLoad() Assert.That(() => OpenApiDocument.Load(this.smallDocumentPath), Throws.InvalidOperationException.With.Message.Contains("#/components/responses/410")); } + [Test] + public void VerifyUnionMembers() + { + var getElement = this.openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements/{elementId}"); + var getElements = this.openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements"); + var getProject = this.openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}"); + var element = getElement.Responses["200"]; + var flexoPackage = "{\"@id\":\"5d2c1a3e-0000-4000-8000-000000000001\",\"@type\":\"Package\",\"declaredName\":\"P\"}"; + var wrongName = "{\"@id\":\"5d2c1a3e-0000-4000-8000-000000000001\",\"@type\":\"Package\",\"declaredName\":5}"; + var byFullSchema = new OpenApiContent(element.SchemasByMediaType); + + using (Assert.EnterMultipleScope()) + { + Assert.That(element.SchemasByType.Keys, Does.Contain("Package").And.Contain("Feature").And.Contain("PartUsage")); + Assert.That(element.IsArrayOfTypes, Is.False); + Assert.That(getElements.Responses["200"].IsArrayOfTypes, Is.True); + Assert.That(getElements.Responses["200"].SchemasByType.Keys, Does.Contain("Package")); + Assert.That(getProject.Responses["200"].SchemasByType.Keys, Is.EqualTo((string[])["Project"])); + Assert.That(byFullSchema.Check("application/json", flexoPackage), Is.Not.Empty, "the full schema also rejects an element without its derived properties"); + Assert.That(element.Check("application/json", wrongName), Is.Not.Empty); + Assert.That(byFullSchema.Check("application/json", wrongName), Is.Not.Empty); + Assert.That(element.Check("application/json", flexoPackage)[0].Message, Does.Contain("required").And.Contain("owner")); + } + + File.WriteAllText(this.smallDocumentPath, SmallDocument.Replace("\"required\": [\"name\"],", "\"required\": [\"name\"], \"anyOf\": [{ \"properties\": { \"@type\": { \"const\": \"T1\" } } }],")); + + var small = OpenApiDocument.Load(this.smallDocumentPath); + var thing = small.Operations.Single(operation => operation.PathTemplate == "/a/{x}").Responses["200"]; + + Assert.That(thing.SchemasByType, Is.Empty, "a union whose node has constraints of its own is not checked by type"); + + File.WriteAllText(this.smallDocumentPath, UnionDocument); + + var union = OpenApiDocument.Load(this.smallDocumentPath).Operations.Single().Responses["200"]; + + Assert.That(union.SchemasByType.Keys, Is.EqualTo((string[])["T2"]), "a @type fixed by two members is left to the declared schema, and the self reference ends"); + } + [Test] public void VerifyMatch() { diff --git a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs index 03c2057f9..e05431504 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs @@ -12,6 +12,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests using System; using System.Collections.Generic; using System.Linq; + using System.Net; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -32,6 +33,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests using SysML2.NET.Core.DTO.Root.Namespaces; using SysML2.NET.PSM; using SysML2.NET.PSM.DTO; + using SysML2.NET.REST.Exceptions; using Direction = SysML2.NET.PSM.Enumerations.Direction; @@ -107,11 +109,25 @@ public async Task VerifyVerifyCommitAsync() List commits = [commit]; DataVersion changeById = null; Guid? head = this.commitId; + var changesUnreadable = false; - this.client.Setup(api => api.GetCommitByProjectAndIdAsync(this.projectId, this.commitId, It.IsAny())).ReturnsAsync(() => commit); + var commitUnreadable = false; + + var recorded = new List(); + EndpointCall commitResponse = null; + + this.client.Setup(api => api.GetCommitByProjectAndIdAsync(this.projectId, this.commitId, It.IsAny())).ReturnsAsync(() => + { + if (commitResponse != null) + { + recorded.Add(commitResponse); + } + + return commitUnreadable ? throw new InvalidOperationException("previousCommit is an object") : commit; + }); this.client.Setup(api => api.GetCommitsByProjectAsync(this.projectId, It.IsAny(), It.IsAny())).Returns((Guid _, QueryParameters parameters, CancellationToken _) => Paged(commits, parameters)); this.client.Setup(api => api.GetBranchesByProjectAndIdAsync(this.projectId, branchId, It.IsAny())).ReturnsAsync(() => new Branch { Id = branchId, Head = head }); - this.client.Setup(api => api.GetChangesByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).Returns((Guid _, Guid _, QueryParameters parameters, CancellationToken _) => Paged(changes, parameters)); + this.client.Setup(api => api.GetChangesByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).Returns((Guid _, Guid _, QueryParameters parameters, CancellationToken _) => changesUnreadable ? throw new InvalidOperationException("no changes") : Paged(changes, parameters)); this.client.Setup(api => api.GetChangeByProjectCommitIdAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).ReturnsAsync((Guid _, Guid _, Guid changeId, CancellationToken _) => changeById ?? changes.Single(change => change.Id == changeId)); var firstCommit = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, null, changed)); @@ -162,6 +178,36 @@ public async Task VerifyVerifyCommitAsync() var noChanges = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, [])); + changesUnreadable = true; + + var unreadableChanges = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, [])); + + changesUnreadable = false; + + commitUnreadable = true; + + var unreadableCommit = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, [])); + + var recording = new ReadBackAssertions(this.client.Object, this.state, () => recorded); + var commitCall = new EndpointCall(null, "GET /projects/p/commits/c", HttpStatusCode.OK); + + commitResponse = commitCall with { ResponseViolations = [new ContractViolation(ContractViolationKind.SchemaMismatch, "/previousCommit type: Value is \"object\" but should be \"array\"")] }; + + var unreadableOnBreakingResponse = await IsolatedAssertions.RunAsync(() => recording.VerifyCommitAsync(commit, branchId, previousId, [])); + + commitResponse = commitCall with { ResponseViolations = [new ContractViolation(ContractViolationKind.SchemaMismatch, "/ required: Required properties [\"alias\"] are not present")] }; + + var unreadableOnToleratedResponse = await IsolatedAssertions.RunAsync(() => recording.VerifyCommitAsync(commit, branchId, previousId, [])); + + commitResponse = commitCall; + + var unreadableOnConformingResponse = await IsolatedAssertions.RunAsync(() => recording.VerifyCommitAsync(commit, branchId, previousId, [])); + + commitResponse = null; + recorded.Add(commitCall with { ResponseViolations = [new ContractViolation(ContractViolationKind.SchemaMismatch, "/previousCommit type: Value is \"object\" but should be \"array\"")] }); + + var unreadableAfterEarlierBreakingResponse = await IsolatedAssertions.RunAsync(() => recording.VerifyCommitAsync(commit, branchId, previousId, [])); + using (Assert.EnterMultipleScope()) { Assert.That(firstCommit, Is.Empty); @@ -177,11 +223,104 @@ public async Task VerifyVerifyCommitAsync() Assert.That(onePage[0].Message, Does.Contain("paging is untested")); Assert.That(missingChanges, Has.Count.EqualTo(2)); Assert.That(noChanges, Has.Count.EqualTo(1)); + Assert.That(unreadableChanges.Select(result => result.Message), Is.EqualTo((string[])["GetChangesByProjectCommitAsync threw InvalidOperationException: no changes"]), "the commit, the list and the branch head still pass"); + Assert.That(unreadableCommit.Select(result => result.Message), Has.Some.Contains("GetCommitByProjectAndIdAsync threw InvalidOperationException: previousCommit is an object")); + Assert.That(unreadableCommit, Has.Count.EqualTo(2), "the commit read fails, and the other commit checks still run"); + Assert.That(unreadableOnBreakingResponse.Select(result => result.Status), Is.EquivalentTo((AssertionStatus[])[AssertionStatus.Warning, AssertionStatus.Failed])); + Assert.That(unreadableOnBreakingResponse.Single(result => result.Status == AssertionStatus.Warning).Message, Does.Contain(KnownServerDivergences.PreviousCommitAsObject.Summary).And.Contain("(GET /projects/p/commits/c)")); + Assert.That(unreadableOnToleratedResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed, AssertionStatus.Failed]), "a tolerated divergence that does not break deserialization excuses nothing"); + Assert.That(unreadableOnConformingResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed, AssertionStatus.Failed])); + Assert.That(unreadableAfterEarlierBreakingResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed, AssertionStatus.Failed]), "a breaking response of an earlier call excuses nothing"); } this.client.Verify(api => api.GetChangeByProjectCommitIdAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } + [Test] + public async Task VerifyVerifyDiffAsync() + { + var baseCommitId = Guid.NewGuid(); + var compareCommitId = Guid.NewGuid(); + var updated = new Package { Id = Guid.NewGuid() }; + var created = new Package { Id = Guid.NewGuid() }; + this.state.ExpectedModels[baseCommitId] = [updated]; + + static DataVersion Version(IElement element) => new() { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = element.Id }, Payload = element }; + + List differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }, new DataDifference { CompareData = Version(created) }]; + Exception failure = null; + + this.client.Setup(api => api.DiffAsync(this.projectId, baseCommitId, compareCommitId, It.IsAny(), It.IsAny())) + .Returns((Guid _, Guid _, Guid _, QueryParameters parameters, CancellationToken _) => failure != null ? throw failure : Paged(differences, parameters)); + + var expected = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); + + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }]; + + var missing = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); + + differences = [new DataDifference { CompareData = Version(updated) }, new DataDifference { BaseData = Version(created), CompareData = Version(created) }]; + + var misclassified = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); + + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }, new DataDifference { BaseData = Version(created) }, new DataDifference()]; + + var deletedAndUnnamed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); + + failure = new PsmApiException(HttpStatusCode.NotImplemented, null); + + var notImplemented = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); + + failure = new PsmApiException(HttpStatusCode.BadRequest, null); + + var rejected = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); + + using (Assert.EnterMultipleScope()) + { + Assert.That(expected, Is.Empty); + Assert.That(missing, Has.Count.EqualTo(1)); + Assert.That(misclassified.Select(result => result.Message), Has.Some.Contains("UPDATED")); + Assert.That(misclassified.Select(result => result.Message), Has.Some.Contains("CREATED")); + Assert.That(deletedAndUnnamed.Select(result => result.Message), Has.Some.Contains("a difference names the data it is about")); + Assert.That(notImplemented.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(notImplemented[0].Message, Does.Contain(KnownServerDivergences.DiffNotImplemented.Summary)); + Assert.That(rejected.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(rejected[0].Message, Does.Contain("DiffAsync threw PsmApiException")); + } + } + + [Test] + public async Task VerifyVerifyHistoryAsync() + { + var earlierCommitId = Guid.NewGuid(); + var element = new Package { Id = Guid.NewGuid(), DeclaredName = "Before" }; + IElement atEarlierCommit = Clone(element); + var unreadable = false; + + this.client.Setup(api => api.GetElementByProjectCommitIdAsync(this.projectId, earlierCommitId, element.Id, It.IsAny(), It.IsAny())) + .ReturnsAsync(() => unreadable ? throw new InvalidOperationException("gone") : atEarlierCommit); + + var unchanged = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyHistoryAsync(earlierCommitId, element)); + + var rewritten = (Package)Clone(element); + rewritten.DeclaredName = "After"; + atEarlierCommit = rewritten; + + var changed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyHistoryAsync(earlierCommitId, element)); + + unreadable = true; + + var failed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyHistoryAsync(earlierCommitId, element)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(unchanged, Is.Empty); + Assert.That(changed.Select(result => result.Message), Is.EqualTo((string[])[$"Package {element.Id} at the earlier commit {earlierCommitId} differs from what was sent: Element.DeclaredName"])); + Assert.That(failed, Has.Count.EqualTo(1)); + Assert.That(failed[0].Message, Does.Contain("threw InvalidOperationException: gone")); + } + } + [Test] public async Task VerifyVerifyModelAsync() { @@ -189,23 +328,26 @@ public async Task VerifyVerifyModelAsync() var elements = model.Builder.ToDtos(); var relationships = elements.OfType().ToList(); var readBack = elements.ToDictionary(element => element.Id, Clone); - var unowned = elements.Where(element => element.owner == null).ToList(); + var unowned = elements.Where(element => element.OwningRelationship == null).ToList(); IReadOnlyList roots = unowned; IReadOnlyList listed = elements; var onePage = false; + var unreadable = new HashSet(); var dropIncoming = false; + var listUnreadable = false; + Direction? unreadableDirection = null; this.client.Setup(api => api.GetElementByProjectCommitIdAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync((Guid _, Guid _, Guid elementId, bool? _, CancellationToken _) => readBack[elementId]); + .ReturnsAsync((Guid _, Guid _, Guid elementId, bool? _, CancellationToken _) => unreadable.Contains(elementId) ? throw new InvalidOperationException("not deserializable") : readBack[elementId]); this.client.Setup(api => api.GetElementsByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((Guid _, Guid _, bool? _, QueryParameters parameters, CancellationToken _) => Paged(listed, onePage ? null : parameters)); + .Returns((Guid _, Guid _, bool? _, QueryParameters parameters, CancellationToken _) => listUnreadable ? throw new InvalidOperationException("no list") : Paged(listed, onePage ? null : parameters)); this.client.Setup(api => api.GetRootsByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) .Returns((Guid _, Guid _, bool? _, QueryParameters parameters, CancellationToken _) => Paged(roots, parameters)); this.client.Setup(api => api.GetRelationshipsByProjectCommitRelatedElementAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((Guid _, Guid _, Guid subjectId, Direction? direction, bool? _, QueryParameters parameters, CancellationToken _) => + .Returns((Guid _, Guid _, Guid subjectId, Direction? direction, bool? _, QueryParameters parameters, CancellationToken _) => direction == unreadableDirection ? throw new InvalidOperationException("no relationships") : Paged(relationships.Where(relationship => direction switch { Direction.@out => relationship.Source.Contains(subjectId), @@ -213,7 +355,7 @@ public async Task VerifyVerifyModelAsync() _ => relationship.Source.Contains(subjectId) || relationship.Target.Contains(subjectId) }).ToList(), parameters)); - var firstRead = elements.Select(element => readBack[element.Id]).ToList(); + var firstRead = elements.ToList(); var identical = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); var recorded = this.state.ReadBack.ToList(); @@ -296,6 +438,34 @@ public async Task VerifyVerifyModelAsync() var emptyReference = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + readBack[dependency.Id] = Clone(dependency); + unreadable.Add(model.Nested.Id); + + var elementUnreadable = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + unreadable.Clear(); + listUnreadable = true; + var readBackBefore = this.state.ReadBack.Count; + + var listUnreadableResults = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var recordedWithoutList = this.state.ReadBack.Skip(readBackBefore).Select(entry => entry.Data).ToList(); + + listUnreadable = false; + unreadableDirection = Direction.@in; + + var incomingUnreadable = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + + unreadableDirection = null; + + var listedRenamed = (Package)Clone(elements.Single(element => element.Id == model.Nested.Id)); + listedRenamed.DeclaredName = "Listed"; + listed = [.. elements.Select(element => element.Id == model.Nested.Id ? listedRenamed : element)]; + this.client.Invocations.Clear(); + + var unchangedListedDifferently = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyModelAsync(this.commitId, elements, [], model.Nested.Id)); + + this.client.Verify(api => api.GetElementByProjectCommitIdAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never, "an element that the commit did not change is not read by id"); + using (Assert.EnterMultipleScope()) { Assert.That(identical, Is.Empty); @@ -324,6 +494,11 @@ public async Task VerifyVerifyModelAsync() Assert.That(memberNameLost.Select(result => result.Message), Has.Some.Contains("lost its memberName (#424)")); Assert.That(memberNameLost.Select(result => result.Message), Has.None.Contains("holds empty references")); Assert.That(emptyReference.Select(result => result.Message), Has.Some.Contains($"Dependency {dependency.Id} holds empty references (#424)")); + Assert.That(unchangedListedDifferently.Select(result => result.Message), Is.EqualTo((string[])[$"Package {model.Nested.Id} as listed differs from what was sent: Element.DeclaredName"])); + Assert.That(listUnreadableResults.Select(result => result.Message), Is.EqualTo((string[])["GetElementsByProjectCommitAsync threw InvalidOperationException: no list"])); + Assert.That(recordedWithoutList, Is.EquivalentTo(elements.Select(element => (IData)readBack[element.Id])).Using((actual, expected) => ReferenceEquals(actual, expected)), "without the list, the elements read by id are recorded"); + Assert.That(incomingUnreadable.Select(result => result.Message), Is.EqualTo((string[])["GetRelationshipsByProjectCommitRelatedElementAsync in threw InvalidOperationException: no relationships"]), "the out and both directions still pass"); + Assert.That(elementUnreadable.Select(result => result.Message), Is.EqualTo((string[])[$"GetElementByProjectCommitIdAsync of Package {model.Nested.Id} threw InvalidOperationException: not deserializable"])); } } @@ -342,6 +517,6 @@ private static Task> Paged(IReadOnlyList records, QueryPara }); } - private Func VerifyModel(IReadOnlyList elements, Guid relationshipSubjectId) => () => this.assertions.VerifyModelAsync(this.commitId, elements, relationshipSubjectId); + private Func VerifyModel(IReadOnlyList elements, Guid relationshipSubjectId) => () => this.assertions.VerifyModelAsync(this.commitId, elements, elements, relationshipSubjectId); } } diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index db57a473a..025d1cbf2 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -135,6 +135,15 @@ references it by that `$id`. the step is wired, the builder converts every POCO with its generated Dal `ToDto(includeDerivedProperties: true)`, naming the element when a conversion fails, and produces the `DataVersionRequest`s for the commit. +- **One builder holds the whole model.** Each step starts its own scope (`BeginStep`) and wires into + the elements of earlier steps, through the `StepModel` base class (`Helpers/Models/`). A commit + sends only the delta: the elements that are new, or whose DTO differs from the previous commit + under `ComparerProvider` (`ModelBuilder.Changed`); every check runs against the whole model. +- **Derived values that cannot be computed.** Without the model library, an operator expression has + no instantiated type, and the generated `ToDto(true)` dereferences it. Such an element is + converted without derived values and listed in `ModelBuilder.WithoutDerivedValues`; derived values + are never sent, so the payload is unaffected. The Kernel fixture pins that list to the five + operator expressions. - Why POCOs: a DTO cannot hold the value of a non-derived member that a derived property redefines (`OwningMembership.memberElement`, `Import.source`, … — 173 no-op setters in 90 DTO classes), so a hand-built DTO would send the empty GUID for it. Only the POCO conversion fills those values. @@ -168,11 +177,13 @@ After each commit: the previous head; the branch `head` moved (`GetBranchesByProjectAndIdAsync`). - `GetChangesByProjectCommitAsync` / `GetChangeByProjectCommitIdAsync` → exactly the sent `DataVersion`s: one per element, its payload equal to the element sent. -- `GetElementByProjectCommitIdAsync` for each element of the step → equal to the expected DTO under - `ComparerProvider`. +- `GetElementByProjectCommitIdAsync` for each element the commit created or changed → equal to the + expected DTO under `ComparerProvider`. An unchanged element was read by id at the commit that + last changed it; its content is compared as listed instead, which keeps a step on a large model + fast. - `GetElementsByProjectCommitAsync`, paged (`page[size]=10`, following `Link` to the end, so that every step's model spans several pages) → exactly the expected id set at that commit, no - duplicates. + duplicates, and every element equal to the expected DTO. - `GetRootsByProjectCommitAsync` → exactly the elements without an `owner`. Systems Modeling API and Services, Clause 7.2.2, Table 2: "A root element is an element that does not have any other element as an owner. Hence, Element.owner is not specified for a root element." KerML derives `owner` as @@ -194,6 +205,12 @@ After each commit: call may tolerate one named known divergence (§8); any other answer fails. - Every request and response of the step conforms to the OpenAPI document (§3.3). - An element that differs from what was sent names the properties that differ. +- Every read is guarded: a read that throws is a failure naming the call, and the step's other checks + still run. It is a warning instead only when a response of that very read shows a known divergence + that breaks deserialization (today only `PreviousCommitAsObject`), because a client cannot be + faulted for an answer the document does not allow; the conformance check reports that answer. + Every Flexo response breaks the document in some tolerated way, so any other violation excuses + nothing. Comparisons over a list of elements run inside `Assert.EnterMultipleScope`, so one run reports every failing metaclass, not just the first. @@ -230,13 +247,17 @@ creates it. ### 6.1 Update scenarios Every concrete metaclass gets U1 and at least one of U2–U4, in step 5 (KerML) or step 8 (SysML). +Exceptions, asserted by `KerMLUpdateModelTestFixture`: an owning membership is not retargeted, +because that moves its member, which the public SDK cannot do (#427), so it gets U2 (its +visibility); a `TypeFeaturing` keeps its ends, because its featuring type is the type that owns its +feature. A connector, flow or association is retargeted through the reference or typing of an end. | Id | Change | Applies to | |---|---|---| | U1 | `declaredName` / `declaredShortName` changed | all 167 | | U2 | the carried non-derived attribute changed (flip a boolean, another literal value, another enum literal) | every row of A.3 / A.4 | | U3 | a relationship end retargeted (`FeatureTyping.type`, `Redefinition.redefinedFeature`, …) | the 62 concrete `Relationship` subclasses | -| U4 | an ordered collection reordered, extended and shrunk (`ownedRelationship` of a `Namespace`) | one per metamodel package — ordering survives the round trip | +| U4 | an ordered collection reordered, extended and shrunk (`ownedRelationship` of a `Namespace`) | one per metamodel package — ordering survives the round trip; only *extended* for now: the public SDK cannot reorder or shrink an ownership list (#427) | ### 6.2 Delete scenarios @@ -297,6 +318,10 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen - `RecordsWithoutRequiredProperties`: projects, branches, commits and data versions leave out the required `alias`, `name`, `description` and `deleted`, and send `null` for an empty `previousCommit` (step 2); +- `PreviousCommitAsObject`: a commit with one previous commit sends `previousCommit` as that one + object instead of an array (step 3); the client's deserializer then throws on a response it cannot + be expected to read, so that read is reported as a warning (§4.3) and the step's other checks + still run; - `ElementsWithoutDerivedProperties`: elements come back without their derived properties (`owner`, `qualifiedName`, …), which the response schemas require; it matches only when every missing property is derived, so a missing non-derived property still fails (step 2); @@ -304,8 +329,9 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen Expected from the Flexo source, added with the step that observes them: -- diff and merge answer 501 Not Implemented (steps 5, 8); -- real values come back as single-precision floats (step 4); +- merge answers 501 Not Implemented (step 8); +- real values come back as single-precision floats (step 4); 2.5 and 3.5 are exact in single + precision, so this is not observed yet; - deleting an element leaves the elements it owns in place (no cascade, §6.2 D3, step 12). Client defects found so far, each red until fixed: @@ -315,6 +341,18 @@ Client defects found so far, each red until fixed: - #425 — the PSM JSON serializers write `null` for optional references that the OpenAPI document does not make nullable (`ProjectRequest.defaultBranch`, …). +SDK defects found while building the fixture, outside the client: + +- #426 — the generated comparers treat equal floating-point values as different, so a + `LiteralRational` read back equal is reported as differing (step 4); +- #427 — `AssignOwnership` duplicates the member when an owning membership is re-assigned, and the + public API cannot reorder or shrink an ownership list or let any relationship other than an + owning membership or an annotation own a related element. Step 3 therefore makes the feature + chain of its `CrossSubsetting` a member of the package, and step 5 only extends (U4). +- #428 — the Dal conversions share value lists (`aliasIds`, `text`) between a POCO and its DTO, so a + later change to the POCO rewrites the expected model of an earlier commit; `ModelBuilder` gives + every DTO its own copy. + ## 9. Open questions 1. **Query by `@type` and subtypes** — Flexo matches subtypes; check whether the spec requires it. diff --git a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs index fc8731b8a..6573a81e1 100644 --- a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs +++ b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs @@ -10,6 +10,7 @@ namespace SySML2.NET.REST.Tests.IntegrationTests { using System; + using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; @@ -23,6 +24,8 @@ namespace SySML2.NET.REST.Tests.IntegrationTests using SySML2.NET.REST.Tests.Helpers; using SySML2.NET.REST.Tests.Helpers.Models; + using SysML2.NET.Core.DTO.Root.Elements; + using SysML2.NET.PSM; using SysML2.NET.PSM.DTO; using SysML2.NET.REST.Exceptions; using SysML2.NET.Serializer.Json; @@ -56,6 +59,14 @@ public class FlexoModelScenarioTestFixture private int verifiedCalls; + private RootModel rootModel; + + private CoreModel coreModel; + + private KernelModel kernelModel; + + private KerMLUpdateModel kermlUpdateModel; + [OneTimeSetUp] public async Task OneTimeSetUp() { @@ -71,7 +82,7 @@ public async Task OneTimeSetUp() await this.session.Open(this.host.BaseAddress, CancellationToken.None); this.client = this.session.Client; - this.readBack = new ReadBackAssertions(this.client, this.state); + this.readBack = new ReadBackAssertions(this.client, this.state, () => this.httpClientFactory.Recorder.Calls); } [OneTimeTearDown] @@ -95,9 +106,10 @@ public void TearDown() } var calls = this.httpClientFactory.Recorder.Calls.ToList(); - - OpenApiConformance.Verify(calls[this.verifiedCalls..], KnownServerDivergences.All); + var unverified = calls[this.verifiedCalls..]; this.verifiedCalls = calls.Count; + + OpenApiConformance.Verify(unverified, KnownServerDivergences.All); } [Test] @@ -143,20 +155,15 @@ public async Task VerifyProjectAndRootModel() Assert.That(projects.Select(project => project.Id), Is.EqualTo([created.Id])); } - var model = new RootModel(); - var elements = model.Builder.ToDtos(); - - var commit = await this.client.PostCommitByProjectAsync(created.Id, ModelBuilder.ToCommitRequest(elements, "Root model"), created.DefaultBranch); - - this.state.HeadCommitId = commit.Id; - this.state.ExpectedModels[commit.Id] = elements; + this.rootModel = new RootModel(); + var committed = await this.CommitModelAsync(this.rootModel.Builder, "Root model"); + var commit = committed.Commit; + var elements = committed.Model; var unknown = Guid.NewGuid(); using (Assert.EnterMultipleScope()) { - Assert.That(this.httpClientFactory.Recorder.EmptyGuidRequests, Is.Empty, "a request referenced the empty GUID"); - await this.ExpectNotFoundAsync(() => this.client.PutProjectByIdAsync(unknown, new ProjectRequest { Name = "Unknown" })); await ExpectClientErrorAsync(() => this.client.PostCommitByProjectAsync(unknown, ModelBuilder.ToCommitRequest(elements, "Unknown project"))); await this.ExpectNotFoundAsync(() => this.client.GetCommitsByProjectAsync(unknown), KnownServerDivergences.UnknownResourceNotFound); @@ -168,14 +175,84 @@ public async Task VerifyProjectAndRootModel() await this.ExpectNotFoundAsync(() => this.client.GetRootsByProjectCommitAsync(created.Id, unknown)); await this.ExpectNotFoundAsync(() => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(created.Id, commit.Id, unknown), KnownServerDivergences.UnknownResourceAccepted); await this.ExpectNotFoundAsync(() => this.client.GetBranchesByProjectAndIdAsync(created.Id, unknown)); - - await this.readBack.VerifyCommitAsync(commit, created.DefaultBranch, null, elements); - await this.readBack.VerifyModelAsync(commit.Id, elements, model.Nested.Id); } + + await this.VerifyCommittedModelAsync(committed, this.rootModel.Nested.Id); } [Test] [DependsOnTest(nameof(VerifyProjectAndRootModel), AllowFailure = true)] + public async Task VerifyKerMLCore() + { + if (this.rootModel == null || this.state.HeadCommitId == null) + { + Assert.Ignore("step 2 committed no model to build on"); + } + + this.coreModel = new CoreModel(this.rootModel); + + var committed = await this.CommitModelAsync(this.coreModel.Builder, "KerML Core"); + + await this.VerifyCommittedModelAsync(committed, this.coreModel.A.Id); + } + + [Test] + [DependsOnTest(nameof(VerifyKerMLCore), AllowFailure = true)] + public async Task VerifyKerMLKernel() + { + if (this.coreModel == null) + { + Assert.Ignore("step 3 built no model to build on"); + } + + this.kernelModel = new KernelModel(this.rootModel, this.coreModel); + + var committed = await this.CommitModelAsync(this.kernelModel.Builder, "KerML Kernel"); + var projectId = this.state.ProjectId!.Value; + + var tag = await this.client.PostTagByProjectAsync(projectId, new TagRequest { Name = "kernel", Description = "The KerML model of step 4", TaggedCommit = committed.Commit.Id }); + this.state.TagIds["kernel"] = tag.Id; + + var tagById = await this.client.GetTagByProjectAndIdAsync(projectId, tag.Id); + var (tags, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetTagsByProjectAsync(projectId, parameters)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(tag.Name, Is.EqualTo("kernel")); + Assert.That(tag.TaggedCommit, Is.EqualTo(committed.Commit.Id)); + Assert.That(tag.OwningProject, Is.EqualTo(projectId)); + Assert.That(tagById.Id, Is.EqualTo(tag.Id)); + Assert.That(tagById.TaggedCommit, Is.EqualTo(committed.Commit.Id)); + Assert.That(tags.Select(record => record.Id), Is.EqualTo((Guid[])[tag.Id])); + + await this.ExpectNotFoundAsync(() => this.client.GetTagByProjectAndIdAsync(projectId, Guid.NewGuid())); + } + + await this.VerifyCommittedModelAsync(committed, this.kernelModel.Class.Id); + } + + [Test] + [DependsOnTest(nameof(VerifyKerMLKernel), AllowFailure = true)] + public async Task VerifyKerMLUpdate() + { + if (this.kernelModel == null || !this.state.TagIds.ContainsKey("kernel")) + { + Assert.Ignore("step 4 built no tagged model to update"); + } + + var projectId = this.state.ProjectId!.Value; + var kernelTag = await this.client.GetTagByProjectAndIdAsync(projectId, this.state.TagIds["kernel"]); + + this.kermlUpdateModel = new KerMLUpdateModel(this.rootModel, this.coreModel, this.kernelModel); + + var committed = await this.CommitModelAsync(this.kermlUpdateModel.Builder, "KerML update"); + + await this.readBack.VerifyDiffAsync(kernelTag.TaggedCommit, committed.Commit.Id, committed.Changed); + await this.VerifyCommittedModelAsync(committed, this.coreModel.A.Id); + } + + [Test] + [DependsOnTest(nameof(VerifyKerMLUpdate), AllowFailure = true)] public async Task VerifyCoverage() { var verdict = new CoverageVerdict(this.state.ReadBack, this.httpClientFactory.Recorder.Calls, this.openApi); @@ -186,6 +263,7 @@ public async Task VerifyCoverage() await TestContext.Out.WriteLineAsync($"Missing literals ({verdict.MissingLiterals.Count}): {string.Join(", ", verdict.MissingLiterals)}"); await TestContext.Out.WriteLineAsync($"Uncovered operations ({verdict.UncoveredOperations.Count}): {string.Join(", ", verdict.UncoveredOperations)}"); await TestContext.Out.WriteLineAsync($"Unmatched requests ({verdict.UnmatchedRequests.Count}): {string.Join(", ", verdict.UnmatchedRequests)}"); + await TestContext.Out.WriteLineAsync($"{this.httpClientFactory.Recorder.Calls.Count} calls: {this.httpClientFactory.Recorder.ServerTime} waiting for the server, {this.httpClientFactory.Recorder.CheckTime} checking against the OpenAPI document"); using (Assert.EnterMultipleScope()) { @@ -204,9 +282,43 @@ private static async Task ExpectClientErrorAsync(Func call, [CallerArgumen await Assert.ThatAsync(() => call(), Throws.InstanceOf().With.Property(nameof(PsmApiException.StatusCode)).Matches(status => (int)status is >= 400 and < 500), description); } + private async Task<(Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead)> CommitModelAsync(ModelBuilder builder, string description) + { + var previousHead = this.state.HeadCommitId; + IReadOnlyList previous = previousHead is { } head ? this.state.ExpectedModels[head] : []; + var model = builder.ToDtos(); + var changed = ModelBuilder.Changed(previous, model); + + var commit = await this.client.PostCommitByProjectAsync(this.state.ProjectId!.Value, ModelBuilder.ToCommitRequest(changed, description), this.state.DefaultBranchId); + + this.state.HeadCommitId = commit.Id; + this.state.ExpectedModels[commit.Id] = model; + + return (commit, model, changed, previousHead); + } + private Task ExpectNotFoundAsync(Func call, ServerDivergence tolerated = null, [CallerArgumentExpression(nameof(call))] string description = null) { return KnownServerDivergences.ExpectNotFoundAsync(call, () => this.httpClientFactory.Recorder.LastCall, tolerated, description); } + + private async Task VerifyCommittedModelAsync((Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead) committed, Guid relationshipSubjectId) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(this.httpClientFactory.Recorder.EmptyGuidRequests, Is.Empty, "a request referenced the empty GUID"); + + await this.readBack.VerifyCommitAsync(committed.Commit, this.state.DefaultBranchId!.Value, committed.PreviousHead, committed.Changed); + await this.readBack.VerifyModelAsync(committed.Commit.Id, committed.Model, committed.Changed, relationshipSubjectId); + + if (committed.PreviousHead is { } previousHead) + { + var previous = this.state.ExpectedModels[previousHead]; + var changedIds = committed.Changed.Select(element => element.Id).ToHashSet(); + + await this.readBack.VerifyHistoryAsync(previousHead, previous.FirstOrDefault(element => changedIds.Contains(element.Id)) ?? previous[0]); + } + } + } } } diff --git a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md index b7571881c..ed4a6f0ba 100644 --- a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md +++ b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md @@ -22,10 +22,14 @@ SySML2.NET.REST.Tests/ ├── Helpers/ the scenario's infrastructure (no tests) │ ├── FlexoTestHost.cs, FlexoJwt.cs, ModelBuilder.cs, … see below │ └── Models/ the model each step commits -│ └── RootModel.cs step 2 +│ ├── StepModel.cs the base: naming and ownership conventions +│ ├── RootModel.cs step 2: KerML Root and Packages +│ ├── CoreModel.cs step 3: KerML Core +│ ├── KernelModel.cs step 4: KerML Kernel +│ └── KerMLUpdateModel.cs step 5: updates U1–U4 of steps 2–4 ├── HelpersTests/ offline: one fixture per helper, mirroring Helpers/ │ ├── FlexoJwtTestFixture.cs, ModelBuilderTestFixture.cs, … -│ └── Models/RootModelTestFixture.cs +│ └── Models/ one fixture per model class ├── IntegrationTests/ needs Docker │ └── FlexoModelScenarioTestFixture.cs the scenario: one [Test] per step ├── Resources/Flexo/cluster.trig Flexo's initial quad-store content (Apache-2.0, see NOTICE) @@ -76,7 +80,7 @@ Session → PsmApiClient → HttpClient |---|---| | `IntegrationHttpClientFactory` | `IHttpClientFactory` that hands out clients over the shared chain. The chain is disposed once, at the end of the fixture. | | `BearerTokenHandler` | Adds the bearer token, because `Session` has no authentication option of its own. | -| `EndpointRecorder` | Records every request as an `EndpointCall`: the OpenAPI operation it matched, the request line, the status, and how the request and the response break the document. It buffers the response body, so the client still reads it. It also collects request bodies that reference `00000000-0000-0000-0000-000000000000`. | +| `EndpointRecorder` | Records every request as an `EndpointCall`: the OpenAPI operation it matched, the request line, the status, and how the request and the response break the document. It buffers the response body, so the client still reads it. It also collects request bodies that reference `00000000-0000-0000-0000-000000000000`, and totals the time spent waiting for the server and checking the contract; the coverage step prints both. | | `EndpointCall` | One recorded request, with its `RequestViolations` (client defects) and `ResponseViolations` (server divergences). | ### 3. The OpenAPI contract @@ -85,7 +89,7 @@ Session → PsmApiClient → HttpClient |---|---| | `OpenApiDocument` | Reads the OpenAPI 3.1 document as JSON Schema 2020-12, with JsonSchema.Net, and matches a request path to its operation. When templates overlap, the one with the most literal segments wins. It removes the `$id`s of the component schemas and makes every reference absolute, because the document references its schemas both by JSON pointer and by those `$id`s. | | `OpenApiOperation` | One operation: its parameters, request body and responses. `CheckRequest` checks the query and the body a client sends; `CheckResponse` checks the status and the body a server answers. | -| `OpenApiParameter`, `OpenApiContent` | A declared parameter, and a declared body (a schema per media type). They check one value or one body; schema errors are summarized to the branch whose `@type` matched. | +| `OpenApiParameter`, `OpenApiContent` | A declared parameter, and a declared body (a schema per media type). They check one value or one body; schema errors are summarized to the branch whose `@type` matched. Where the declared schema is a union of object schemas that each fix their `@type`, as the element schemas are, an object is validated against the member of its `@type` alone: the verdict is the same and the evaluation is far cheaper. | | `ContractViolation`, `ContractViolationKind` | One way a request or a response breaks the document, by kind, so a known divergence can match it. | | `OpenApiConformance` | After each step: fails on any request violation; reports a response violation as the known divergence that explains it, or fails. | @@ -93,16 +97,16 @@ Session → PsmApiClient → HttpClient | Type | Responsibility | |---|---| -| `ModelBuilder` | Creates POCOs with deterministic ids; the step wires them with `AssignOwnership`. Once the step is complete, they are converted with the Dal's `ToDto(includeDerivedProperties: true)` and turned into a `CommitRequest`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | +| `ModelBuilder` | Holds the whole model across the steps: each step starts its own scope (`BeginStep`) and creates POCOs with deterministic ids, wired with `AssignOwnership`. It converts them with the Dal's `ToDto(includeDerivedProperties: true)`, `Changed` selects the delta a commit sends, and `Find` looks an element up by its scoped name. An element whose derived values cannot be computed without the model library is converted without them and listed in `WithoutDerivedValues`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | | `DeterministicGuid` | Name-based UUID v5 of `"/"`, so the elements have the same ids in every run. | -| `Models/*` | One class per step, describing the model that step commits (for example `RootModel` for step 2). | +| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5). | ### 5. Checking what came back | Type | Responsibility | |---|---| | `ScenarioState` | What the steps hand on to each other: the ids the server assigned (project, branch, commits), the expected model at each commit, and everything the server returned. | -| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, every element by id, paged element reads, roots (the elements without an `owner`), relationships, the member element and name of every membership, and that no returned DTO holds an empty GUID. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. | +| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Every read is guarded: a read that throws fails, or warns when the response it failed on breaks the OpenAPI document. | | `KnownServerDivergences`, `ServerDivergence` | The named ways Flexo diverges from the specification, each with a reference: an upstream issue, or a Flexo source location at the pinned commit. A divergence can explain response violations. `Report` raises an `Assert.Warn`. `ExpectNotFoundAsync` expects a 404, tolerates one named divergence, and fails when a conforming 404 reaches the caller without its `Error`. | | `IsolatedAssertions` | Runs a check in an isolated NUnit context and returns its failures and warnings, without failing the calling test. The offline fixtures use it to prove that a check fails when it should. | @@ -130,7 +134,10 @@ Having one `[Test]` per step goes against the one-test-per-method rule in `TESTI |---|---|---| | 1 | `VerifyEmptyServer` | implemented | | 2 | `VerifyProjectAndRootModel` | implemented | -| 3–13 | see plan §5 | planned | +| 3 | `VerifyKerMLCore` | implemented | +| 4 | `VerifyKerMLKernel` | implemented, with the tag `kernel` | +| 5 | `VerifyKerMLUpdate` | implemented, with the diff from the tag `kernel` | +| 6–13 | see plan §5 | planned | | 14 | `VerifyCoverage` | implemented, red by design | ### Reading the outcome @@ -158,10 +165,11 @@ The Docker endpoint is taken from `DOCKER_HOST`, and otherwise, on Windows, from To add a step: -1. Add a model class under `Helpers/Models/` that builds the step's elements with `ModelBuilder`, and its offline fixture under `HelpersTests/Models/`. +1. Add a model class under `Helpers/Models/`, deriving from `StepModel`, that adds the step's elements to the shared `ModelBuilder`, and its offline fixture under `HelpersTests/Models/`. 2. Add a `[Test]` to `IntegrationTests/FlexoModelScenarioTestFixture.cs` that depends on the previous step with `AllowFailure = true`, commits the model, and calls `ReadBackAssertions`. -3. Make `VerifyCoverage` depend on the new last step. -4. When Flexo diverges, add an entry to `KnownServerDivergences` with its reference, and list it under "Observed" in plan §8. -5. Check the coverage verdict output: the step should remove items from it. +3. Commit with `CommitModelAsync` and verify with `VerifyCommittedModelAsync`, which send the delta and check the whole model. +4. Make `VerifyCoverage` depend on the new last step. +5. When Flexo diverges, add an entry to `KnownServerDivergences` with its reference, and list it under "Observed" in plan §8. +6. Check the coverage verdict output: the step should remove items from it. Fixture rules (`TESTING.md`, `DEVELOPMENT_STANDARDS.md`) apply to every file here, with the one exception noted above. From 40853f93d3cd7bd873f88f2aac330824792311f4 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Sun, 8 Nov 2026 08:25:42 +0100 Subject: [PATCH 05/11] =?UTF-8?q?[Add]=20Flexo=20integration=20scenario=20?= =?UTF-8?q?stage=203:=20SysML=20structure,=20behaviour=20and=20merge=20ste?= =?UTF-8?q?ps=206=E2=80=938,=20concurrent=20reads=20(#407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Helpers/KnownServerDivergences.cs | 12 +- SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs | 25 + .../Helpers/Models/KernelModel.cs | 135 ---- .../Helpers/Models/StepModel.cs | 139 ++++ .../Helpers/Models/SystemsBehaviorModel.cs | 672 ++++++++++++++++++ .../Helpers/Models/SystemsStructureModel.cs | 435 ++++++++++++ .../Helpers/ReadBackAssertions.cs | 154 +++- .../Helpers/ScenarioState.cs | 14 +- .../KnownServerDivergencesTestFixture.cs | 2 +- .../HelpersTests/ModelBuilderTestFixture.cs | 25 + .../Models/SystemsBehaviorModelTestFixture.cs | 76 ++ .../SystemsStructureModelTestFixture.cs | 70 ++ .../ReadBackAssertionsTestFixture.cs | 53 +- .../INTEGRATION_TEST_PLAN.md | 33 +- .../FlexoModelScenarioTestFixture.cs | 176 ++++- .../TEST_PROJECT_STRUCTURE.md | 18 +- 16 files changed, 1835 insertions(+), 204 deletions(-) create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs diff --git a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs index 65a03756f..7ff3a6cc7 100644 --- a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs +++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs @@ -88,6 +88,16 @@ public static class KnownServerDivergences /// public static ServerDivergence DiffNotImplemented { get; } = new("GET /projects/{projectId}/commits/{compareCommitId}/diff answers 501 Not Implemented", $"{FlexoRevision}, observed on GET /projects/{{projectId}}/commits/{{compareCommitId}}/diff"); + /// + /// Gets the divergence that the merge of commits into a branch is not implemented + /// + public static ServerDivergence MergeNotImplemented { get; } = new("POST /projects/{projectId}/branches/{targetBranchId}/merge answers 501 Not Implemented", $"{FlexoRevision}, observed on POST /projects/{{projectId}}/branches/{{targetBranchId}}/merge"); + + /// + /// Gets the divergence that a merge fails on the request bodies the OpenAPI document allows besides an array + /// + public static ServerDivergence MergeRequiresArrayBody { get; } = new("POST /projects/{projectId}/branches/{targetBranchId}/merge answers 500 Internal Server Error without a body and 400 Bad Request for a null body, both of which the OpenAPI document allows", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/DiffMergeApi.kt, the route receives the body as a list"); + /// /// Gets the divergence that a create answers 200 OK, where the OpenAPI document declares 201 Created and no 200 /// @@ -135,7 +145,7 @@ public static class KnownServerDivergences /// /// Gets every known divergence /// - public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri]; + public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, MergeNotImplemented, MergeRequiresArrayBody, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri]; /// /// Asserts that a call for an unknown resource fails with 404 Not Found, or reports the one tolerated divergence diff --git a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs index 2074a00d6..440a1f8a8 100644 --- a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs +++ b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs @@ -37,6 +37,11 @@ public sealed class ModelBuilder /// private static readonly ConcurrentDictionary StringListsByClass = new(); + /// + /// The memberwise copy of , which copies a DTO of any class + /// + private static readonly MethodInfo CopyMethod = typeof(object).GetMethod(nameof(MemberwiseClone), BindingFlags.Instance | BindingFlags.NonPublic); + /// /// The prefix of the names that the ids of the current step are derived from /// @@ -96,6 +101,26 @@ public static IReadOnlyList Changed(IReadOnlyList previo .ToList(); } + /// + /// Copies a DTO, with its own string lists, so that a change to the copy leaves the expected model it came from + /// intact + /// + /// + /// The type of the DTO + /// + /// + /// The DTO + /// + /// + /// The copy + /// + public static TElement Copy(TElement dto) where TElement : DtoElement + { + ArgumentNullException.ThrowIfNull(dto); + + return (TElement)Detach((DtoElement)CopyMethod.Invoke(dto, null)); + } + /// /// Creates the commit request that creates or replaces the given elements /// diff --git a/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs index 9f688d675..d6d441d0e 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs @@ -490,77 +490,6 @@ private FeatureReferenceExpression FeatureReference(string name, IFeature refere } } - /// - /// Creates a literal expression with its result parameter - /// - /// - /// The literal POCO type - /// - /// - /// The name the elements are derived from - /// - /// - /// The generated ToDto extension of - /// - /// - /// Sets the value of the literal - /// - /// - /// The literal expression - /// - private TLiteral Literal(string name, Func toDto, Action setValue) where TLiteral : IExpression, new() - { - var literal = this.Builder.Create(name, toDto); - setValue(literal); - this.Result(literal, name); - - return literal; - } - - /// - /// Gives a feature the multiplicity [1], featured like the feature - /// - /// - /// The feature - /// - /// - /// The type that features - /// - private void MultiplicityOne(IFeature feature, IType featuringType) - { - this.MultiplicityRange(feature, featuringType, this.Literal($"{feature.ElementId}/multiplicity/1", LiteralIntegerExtensions.ToDto, literal => literal.Value = 1)); - } - - /// - /// Gives a feature a multiplicity range with the given bounds, featured like the feature as KerML requires - /// (validateFeatureMultiplicityDomain) - /// - /// - /// The feature - /// - /// - /// The type that features - /// - /// - /// The bounds: the upper bound alone, or the lower and the upper bound - /// - private void MultiplicityRange(IFeature feature, IType featuringType, params IExpression[] bounds) - { - var range = this.Builder.Create($"{feature.ElementId}/multiplicity", MultiplicityRangeExtensions.ToDto); - - foreach (var bound in bounds) - { - this.OwnMember(range, bound); - } - - this.OwnMember(feature, range); - - var featuring = this.Builder.Create($"{feature.ElementId}/multiplicity/featuring", TypeFeaturingExtensions.ToDto); - featuring.FeatureOfType = range; - featuring.FeaturingType = featuringType; - range.AssignOwnership(featuring); - } - /// /// Creates an expression with its result parameter as a feature of /// @@ -585,39 +514,6 @@ private void MultiplicityRange(IFeature feature, IType featuringType, params IEx return expression; } - /// - /// Adds a parameter to a behavior or expression through a parameter membership - /// - /// - /// The parameter membership POCO type - /// - /// - /// The behavior or expression - /// - /// - /// The name of the parameter - /// - /// - /// The direction of the parameter - /// - /// - /// The generated ToDto extension of - /// - /// - /// The parameter - /// - private Feature Parameter(IType owner, string name, FeatureDirectionKind direction, Func toDto) where TMembership : PocoRelationship, new() - { - var parameter = this.Builder.Create(name, FeatureExtensions.ToDto); - parameter.DeclaredName = name[(name.LastIndexOf('/') + 1)..]; - parameter.Direction = direction; - - var membership = this.Builder.Create($"{name}/membership", toDto); - owner.AssignOwnership(membership, parameter); - - return parameter; - } - /// /// Refers an expression to an element through a plain, non-owning /// @@ -635,37 +531,6 @@ private void Reference(IExpression expression, PocoElement element) expression.AssignOwnership(membership); } - /// - /// Adds the result parameter to an expression or function, through a - /// - /// - /// The expression or function - /// - /// - /// The name the elements are derived from - /// - private void Result(IType owner, string name) - { - this.Parameter(owner, $"{name}/result", FeatureDirectionKind.Out, ReturnParameterMembershipExtensions.ToDto); - } - - /// - /// Types a feature with a - /// - /// - /// The feature - /// - /// - /// The type - /// - private void Typed(IFeature feature, IType type) - { - var typing = this.Builder.Create($"{feature.ElementId}/typing", FeatureTypingExtensions.ToDto); - typing.TypedFeature = feature; - typing.Type = type; - feature.AssignOwnership(typing); - } - /// /// Creates a feature of a type, typed by another type /// diff --git a/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs index ba5a45ee1..0cc9613e5 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs @@ -11,8 +11,12 @@ namespace SySML2.NET.REST.Tests.Helpers.Models { using System; + using SysML2.NET.Core.Core.Types; using SysML2.NET.Core.POCO.Core.Features; using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Kernel.Expressions; + using SysML2.NET.Core.POCO.Kernel.Functions; + using SysML2.NET.Core.POCO.Kernel.Multiplicities; using SysML2.NET.Core.POCO.Root.Namespaces; using SysML2.NET.Dal; using SysML2.NET.Extensions; @@ -75,6 +79,77 @@ protected StepModel(ModelBuilder builder, string scope) return element; } + /// + /// Creates a literal expression with its result parameter + /// + /// + /// The literal POCO type + /// + /// + /// The name the elements are derived from + /// + /// + /// The generated ToDto extension of + /// + /// + /// Sets the value of the literal + /// + /// + /// The literal expression + /// + protected TLiteral Literal(string name, Func toDto, Action setValue) where TLiteral : IExpression, new() + { + var literal = this.Builder.Create(name, toDto); + setValue(literal); + this.Result(literal, name); + + return literal; + } + + /// + /// Gives a feature the multiplicity [1], featured like the feature + /// + /// + /// The feature + /// + /// + /// The type that features + /// + protected void MultiplicityOne(IFeature feature, IType featuringType) + { + this.MultiplicityRange(feature, featuringType, this.Literal($"{feature.ElementId}/multiplicity/1", LiteralIntegerExtensions.ToDto, literal => literal.Value = 1)); + } + + /// + /// Gives a feature a multiplicity range with the given bounds, featured like the feature as KerML requires + /// (validateFeatureMultiplicityDomain) + /// + /// + /// The feature + /// + /// + /// The type that features + /// + /// + /// The bounds: the upper bound alone, or the lower and the upper bound + /// + protected void MultiplicityRange(IFeature feature, IType featuringType, params IExpression[] bounds) + { + var range = this.Builder.Create($"{feature.ElementId}/multiplicity", MultiplicityRangeExtensions.ToDto); + + foreach (var bound in bounds) + { + this.OwnMember(range, bound); + } + + this.OwnMember(feature, range); + + var featuring = this.Builder.Create($"{feature.ElementId}/multiplicity/featuring", TypeFeaturingExtensions.ToDto); + featuring.FeatureOfType = range; + featuring.FeaturingType = featuringType; + range.AssignOwnership(featuring); + } + /// /// Makes a feature an owned feature of a type, through a or, for an end /// feature, an , and features it by that type with a @@ -113,5 +188,69 @@ protected void OwnMember(PocoElement owner, PocoElement member) var membership = this.Builder.Create($"{member.ElementId}/membership", OwningMembershipExtensions.ToDto); owner.AssignOwnership(membership, member); } + + /// + /// Adds a parameter to a behavior or expression through a parameter membership + /// + /// + /// The parameter membership POCO type + /// + /// + /// The behavior or expression + /// + /// + /// The name of the parameter + /// + /// + /// The direction of the parameter + /// + /// + /// The generated ToDto extension of + /// + /// + /// The parameter + /// + protected Feature Parameter(IType owner, string name, FeatureDirectionKind direction, Func toDto) where TMembership : PocoRelationship, new() + { + var parameter = this.Builder.Create(name, FeatureExtensions.ToDto); + parameter.DeclaredName = name[(name.LastIndexOf('/') + 1)..]; + parameter.Direction = direction; + + var membership = this.Builder.Create($"{name}/membership", toDto); + owner.AssignOwnership(membership, parameter); + + return parameter; + } + + /// + /// Adds the result parameter to an expression or function, through a + /// + /// + /// The expression or function + /// + /// + /// The name the elements are derived from + /// + protected void Result(IType owner, string name) + { + this.Parameter(owner, $"{name}/result", FeatureDirectionKind.Out, ReturnParameterMembershipExtensions.ToDto); + } + + /// + /// Types a feature with a + /// + /// + /// The feature + /// + /// + /// The type + /// + protected void Typed(IFeature feature, IType type) + { + var typing = this.Builder.Create($"{feature.ElementId}/typing", FeatureTypingExtensions.ToDto); + typing.TypedFeature = feature; + typing.Type = type; + feature.AssignOwnership(typing); + } } } diff --git a/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs new file mode 100644 index 000000000..23fc81efe --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs @@ -0,0 +1,672 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + + using SysML2.NET.Core.Core.Types; + using SysML2.NET.Core.POCO.Core.Classifiers; + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Kernel.Behaviors; + using SysML2.NET.Core.POCO.Kernel.Connectors; + using SysML2.NET.Core.POCO.Kernel.Expressions; + using SysML2.NET.Core.POCO.Kernel.FeatureValues; + using SysML2.NET.Core.POCO.Kernel.Functions; + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Core.POCO.Root.Annotations; + using SysML2.NET.Core.POCO.Root.Namespaces; + using SysML2.NET.Core.POCO.Systems.Actions; + using SysML2.NET.Core.POCO.Systems.AnalysisCases; + using SysML2.NET.Core.POCO.Systems.Calculations; + using SysML2.NET.Core.POCO.Systems.Cases; + using SysML2.NET.Core.POCO.Systems.Constraints; + using SysML2.NET.Core.POCO.Systems.DefinitionAndUsage; + using SysML2.NET.Core.POCO.Systems.Metadata; + using SysML2.NET.Core.POCO.Systems.Occurrences; + using SysML2.NET.Core.POCO.Systems.Parts; + using SysML2.NET.Core.POCO.Systems.Requirements; + using SysML2.NET.Core.POCO.Systems.States; + using SysML2.NET.Core.POCO.Systems.UseCases; + using SysML2.NET.Core.POCO.Systems.VerificationCases; + using SysML2.NET.Core.POCO.Systems.Views; + using SysML2.NET.Core.Root.Namespaces; + using SysML2.NET.Core.Systems.Actions; + using SysML2.NET.Core.Systems.Requirements; + using SysML2.NET.Core.Systems.States; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using PocoRelationship = SysML2.NET.Core.POCO.Root.Elements.IRelationship; + + /// + /// The model of scenario step 7: the SysML behaviour, requirement, case, view and metadata metaclasses, in a package + /// Behaviour of the root package, committed on the branch systems + /// + /// + /// + /// An action definition Act holds every action and control node kind; a state definition St has entry, + /// do and exit subactions and a transition with a trigger, a guard and an effect; calculation and constraint + /// definitions own their results. RBase owns the subject and the result that every requirement-like and, + /// through Cs, every case-like definition inherits, so that the subject and objective memberships are owned + /// by exactly a requirement or case definition, as validateSubjectMembershipOwningType and + /// validateObjectiveMembershipOwningType read literally (oclIsType); that reading is one of two the + /// OCL admits. A view usage exposes the structure of step 6, and a metadata usage annotates its part definition. + /// + /// + /// The rules that need the model library cannot hold: the check…Specialization rules, the trigger argument + /// rules, the Boolean result of a guard, and validateFeatureIsVariable for the assigned feature. + /// + /// + public sealed class SystemsBehaviorModel : StepModel + { + /// + /// Initializes a new instance of the class and builds the model on that of + /// step 6 + /// + /// + /// The model of step 2 + /// + /// + /// The model of step 6 + /// + public SystemsBehaviorModel(RootModel root, SystemsStructureModel structure) : base((structure ?? throw new ArgumentNullException(nameof(structure))).Builder, "systems behaviour") + { + ArgumentNullException.ThrowIfNull(root); + + this.Package = this.CreateNamed("Behaviour", "beh", PackageExtensions.ToDto); + this.OwnMember(root.Root, this.Package); + + this.Actions(structure); + this.States(); + var (calculation, constraint) = this.Calculations(); + var requirement = this.Requirements(constraint, structure); + this.Cases(requirement); + this.Views(structure); + this.Metadata(structure); + + var top = this.Member("calc", CalculationUsageExtensions.ToDto); + this.Typed(top, calculation); + } + + /// + /// Gets the package that holds the step + /// + public Package Package { get; } + + /// + /// Gets the action definition Act, which holds every action and control node kind + /// + public ActionDefinition ActionDefinition { get; private set; } + + /// + /// Gets the requirement definition RBase, which owns the subject and the result that requirements and cases + /// inherit + /// + public RequirementDefinition RequirementBase { get; private set; } + + /// + /// Adds a trigger-like accept action to , whose payload is the value of a trigger + /// invocation of the given kind + /// + /// + /// The name of the accept action + /// + /// + /// The kind of the trigger + /// + /// + /// The behavior the trigger invokes, with one in parameter + /// + /// + /// The in parameter of + /// + private void Accept(string name, TriggerKind kind, ActionDefinition triggered, ReferenceUsage triggeredInput) + { + var accept = this.Owned(this.ActionDefinition, name, AcceptActionUsageExtensions.ToDto); + var payload = this.Param(accept, $"{name}/payload", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + + var trigger = this.Builder.Create($"{name}/trigger", TriggerInvocationExpressionExtensions.ToDto); + trigger.Kind = kind; + this.Refer(trigger, triggered); + + var argument = this.Param(trigger, $"{name}/trigger/argument", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + this.Redefine(argument, triggeredInput); + this.Value(argument, this.Literal($"{name}/trigger/argument/true", LiteralBooleanExtensions.ToDto, literal => literal.Value = true)); + this.Result(trigger, $"{name}/trigger"); + + this.Value(payload, trigger); + } + + /// + /// Adds the action definition Act with one instance of every action and control node kind + /// + /// + /// The model of step 6 + /// + private void Actions(SystemsStructureModel structure) + { + this.ActionDefinition = this.Member("Act", ActionDefinitionExtensions.ToDto); + this.Param(this.ActionDefinition, "Act/x", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + + foreach (var node in new PocoElement[] + { + this.Owned(this.ActionDefinition, "decide", DecisionNodeExtensions.ToDto), + this.Owned(this.ActionDefinition, "fork", ForkNodeExtensions.ToDto), + this.Owned(this.ActionDefinition, "join", JoinNodeExtensions.ToDto), + this.Owned(this.ActionDefinition, "merge", MergeNodeExtensions.ToDto) + }) + { + ((IFeature)node).IsComposite = true; + } + + var performed = this.Owned(this.ActionDefinition, "a0", ActionUsageExtensions.ToDto); + performed.IsComposite = true; + + var triggered = this.Member("Trig", ActionDefinitionExtensions.ToDto); + var triggeredInput = this.Param(triggered, "Trig/condition", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + + this.Accept("accept when", TriggerKind.When, triggered, triggeredInput); + this.Accept("accept at", TriggerKind.At, triggered, triggeredInput); + this.Accept("accept after", TriggerKind.After, triggered, triggeredInput); + + var send = this.Owned(this.ActionDefinition, "send", SendActionUsageExtensions.ToDto); + this.Value(this.Param(send, "send/payload", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto), this.Literal("send/payload/1", LiteralIntegerExtensions.ToDto, literal => literal.Value = 1)); + + var level = this.Owned(structure.OccurrenceDefinition, "level", FeatureExtensions.ToDto); + level.IsVariable = true; + + var assign = this.Owned(this.ActionDefinition, "assign", AssignmentActionUsageExtensions.ToDto); + this.Refer(assign, level); + this.Value(this.Param(assign, "assign/target", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto), this.Literal("assign/target/0", LiteralIntegerExtensions.ToDto, literal => literal.Value = 0)); + this.Value(this.Param(assign, "assign/value", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto), this.Literal("assign/value/5", LiteralIntegerExtensions.ToDto, literal => literal.Value = 5)); + + var ifAction = this.Owned(this.ActionDefinition, "if", IfActionUsageExtensions.ToDto); + this.Condition(ifAction, "if/condition"); + this.Param(ifAction, "if/then", ActionUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + + var whileLoop = this.Owned(this.ActionDefinition, "while", WhileLoopActionUsageExtensions.ToDto); + this.Condition(whileLoop, "while/condition"); + this.Param(whileLoop, "while/body", ActionUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + + var forLoop = this.Owned(this.ActionDefinition, "for", ForLoopActionUsageExtensions.ToDto); + var loopVariable = this.Builder.Create("for/variable", ReferenceUsageExtensions.ToDto); + loopVariable.DeclaredName = "n"; + this.OwnFeature(forLoop, loopVariable); + this.Value(this.Param(forLoop, "for/sequence", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto), this.Literal("for/sequence/3", LiteralIntegerExtensions.ToDto, literal => literal.Value = 3)); + this.Param(forLoop, "for/body", ActionUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + + var perform = this.Owned(this.ActionDefinition, "perform", PerformActionUsageExtensions.ToDto); + this.Subset(perform, performed); + + this.Owned(this.ActionDefinition, "terminate", TerminateActionUsageExtensions.ToDto); + + var action = this.Member("act", ActionUsageExtensions.ToDto); + this.Typed(action, this.ActionDefinition); + } + + /// + /// Adds the calculation and constraint definitions and usages + /// + /// + /// The calculation definition and the constraint definition + /// + private (CalculationDefinition Calculation, ConstraintDefinition Constraint) Calculations() + { + var calculation = this.Member("Calc", CalculationDefinitionExtensions.ToDto); + this.Result(calculation, "Calc"); + calculation.AssignOwnership(this.Builder.Create("Calc/body", ResultExpressionMembershipExtensions.ToDto), this.Literal("Calc/body/3", LiteralIntegerExtensions.ToDto, literal => literal.Value = 3)); + + var constraint = this.Member("Cons", ConstraintDefinitionExtensions.ToDto); + this.Result(constraint, "Cons"); + constraint.AssignOwnership(this.Builder.Create("Cons/body", ResultExpressionMembershipExtensions.ToDto), this.Literal("Cons/body/true", LiteralBooleanExtensions.ToDto, literal => literal.Value = true)); + + var asserted = this.Member("cTop", ConstraintUsageExtensions.ToDto); + this.Typed(asserted, constraint); + + var assertion = this.Member("assert", AssertConstraintUsageExtensions.ToDto); + assertion.IsNegated = true; + this.Subset(assertion, asserted); + + return (calculation, constraint); + } + + /// + /// Adds the case definitions and usages: Cs with its subject, result and objective, which the analysis, + /// verification and use case definitions specialize + /// + /// + /// The requirement usage rq that the objective verifies + /// + private void Cases(RequirementUsage requirement) + { + var caseDefinition = this.Member("Cs", CaseDefinitionExtensions.ToDto); + this.Param(caseDefinition, "Cs/subject", ReferenceUsageExtensions.ToDto, SubjectMembershipExtensions.ToDto); + this.Result(caseDefinition, "Cs"); + + var objective = this.Builder.Create("Cs/objective", RequirementUsageExtensions.ToDto); + objective.IsComposite = true; + caseDefinition.AssignOwnership(this.Builder.Create("Cs/objective/membership", ObjectiveMembershipExtensions.ToDto), objective); + this.Typed(objective, this.RequirementBase); + + var verified = this.Builder.Create("Cs/objective/verified", RequirementUsageExtensions.ToDto); + verified.IsComposite = true; + var verification = this.Builder.Create("Cs/objective/verified/membership", RequirementVerificationMembershipExtensions.ToDto); + verification.Kind = RequirementConstraintKind.Requirement; + objective.AssignOwnership(verification, verified); + this.Subset(verified, requirement); + + var analysis = this.Specialized("ACD", AnalysisCaseDefinitionExtensions.ToDto, caseDefinition); + var verificationCase = this.Specialized("VCD", VerificationCaseDefinitionExtensions.ToDto, caseDefinition); + var useCase = this.Specialized("UCD", UseCaseDefinitionExtensions.ToDto, caseDefinition); + + this.Typed(this.Member("cs", CaseUsageExtensions.ToDto), caseDefinition); + this.Typed(this.Member("acu", AnalysisCaseUsageExtensions.ToDto), analysis); + this.Typed(this.Member("vcu", VerificationCaseUsageExtensions.ToDto), verificationCase); + + var useCaseUsage = this.Member("ucu", UseCaseUsageExtensions.ToDto); + this.Typed(useCaseUsage, useCase); + + var include = this.Owned(useCase, "include", IncludeUseCaseUsageExtensions.ToDto); + this.Subset(include, useCaseUsage); + } + + /// + /// Makes a Boolean literal the first in parameter of a conditional action + /// + /// + /// The if or while action + /// + /// + /// The name the literal is derived from + /// + private void Condition(IType action, string name) + { + var condition = this.Literal(name, LiteralBooleanExtensions.ToDto, literal => literal.Value = true); + condition.Direction = FeatureDirectionKind.In; + action.AssignOwnership(this.Builder.Create($"{name}/membership", ParameterMembershipExtensions.ToDto), condition); + } + + /// + /// Creates a named member of ; a usage owned by a package is referential + /// + /// + /// The POCO type + /// + /// + /// The declared name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The member + /// + private TPoco Member(string name, Func toDto) where TPoco : PocoElement, new() + { + var member = this.CreateNamed(name, name.ToLowerInvariant().Replace(' ', '_'), toDto); + this.OwnMember(this.Package, member); + + return member; + } + + /// + /// Adds the metadata definition and a metadata usage that annotates the part definition of step 6 + /// + /// + /// The model of step 6 + /// + private void Metadata(SystemsStructureModel structure) + { + var definition = this.Member("MD", MetadataDefinitionExtensions.ToDto); + + var usage = this.Member("mu", MetadataUsageExtensions.ToDto); + this.Typed(usage, definition); + + var about = this.Builder.Create("mu/about P", AnnotationExtensions.ToDto); + about.AnnotatedElement = structure.Part; + usage.AssignOwnership(about); + } + + /// + /// Creates a named feature owned by a type through a + /// + /// + /// The feature POCO type + /// + /// + /// The owning type + /// + /// + /// The declared name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The feature + /// + private TFeature Owned(IType owner, string name, Func toDto) where TFeature : IFeature, new() + { + var feature = this.CreateNamed(name, name.Replace(' ', '_'), toDto); + this.OwnFeature(owner, feature); + + return feature; + } + + /// + /// Adds an in parameter usage to a behavior, step or requirement through a parameter membership + /// + /// + /// The parameter usage POCO type + /// + /// + /// The parameter membership POCO type + /// + /// + /// The owning type + /// + /// + /// The name the parameter is derived from + /// + /// + /// The generated ToDto extension of + /// + /// + /// The generated ToDto extension of + /// + /// + /// The parameter usage + /// + private TUsage Param(IType owner, string name, Func toDto, Func membershipToDto) + where TUsage : IFeature, new() + where TMembership : PocoRelationship, new() + { + var parameter = this.Builder.Create(name, toDto); + parameter.DeclaredName = name[(name.LastIndexOf('/') + 1)..]; + parameter.Direction = FeatureDirectionKind.In; + owner.AssignOwnership(this.Builder.Create($"{name}/membership", membershipToDto), parameter); + + return parameter; + } + + /// + /// Makes a feature redefine another through a + /// + /// + /// The redefining feature + /// + /// + /// The redefined feature + /// + private void Redefine(IFeature feature, IFeature redefined) + { + var redefinition = this.Builder.Create($"{feature.ElementId}/redefinition", RedefinitionExtensions.ToDto); + redefinition.RedefiningFeature = feature; + redefinition.RedefinedFeature = redefined; + feature.AssignOwnership(redefinition); + } + + /// + /// Refers a namespace to an element through a plain, non-owning + /// + /// + /// The referring namespace + /// + /// + /// The referenced element + /// + private void Refer(PocoElement owner, PocoElement element) + { + var membership = this.Builder.Create($"{owner.ElementId}/reference {element.ElementId}", MembershipExtensions.ToDto); + membership.MemberElement = element; + membership.MemberName = element.DeclaredName; + owner.AssignOwnership(membership); + } + + /// + /// Adds the requirement definitions and usages: RBase with its subject and result, R with its actor, + /// stakeholder, assumed and required constraints and framed concern, and the concern and viewpoint definitions + /// + /// + /// The constraint definition that types the assumed and required constraints + /// + /// + /// The model of step 6 + /// + /// + /// The requirement usage rq + /// + private RequirementUsage Requirements(ConstraintDefinition constraint, SystemsStructureModel structure) + { + this.RequirementBase = this.Member("RBase", RequirementDefinitionExtensions.ToDto); + var subject = this.Param(this.RequirementBase, "RBase/subject", ReferenceUsageExtensions.ToDto, SubjectMembershipExtensions.ToDto); + this.Result(this.RequirementBase, "RBase"); + + var concern = this.Specialized("CDn", ConcernDefinitionExtensions.ToDto, this.RequirementBase); + this.Specialized("VPD", ViewpointDefinitionExtensions.ToDto, this.RequirementBase); + + var requirement = this.Specialized("R", RequirementDefinitionExtensions.ToDto, this.RequirementBase); + requirement.ReqId = "R-1"; + + var text = this.Builder.Create("R/text", DocumentationExtensions.ToDto); + text.Body = "The coverage requirement."; + this.OwnMember(requirement, text); + + this.Param(requirement, "R/actor", PartUsageExtensions.ToDto, ActorMembershipExtensions.ToDto); + this.Param(requirement, "R/stakeholder", PartUsageExtensions.ToDto, StakeholderMembershipExtensions.ToDto); + + foreach (var (name, kind) in new[] { ("R/assumed", RequirementConstraintKind.Assumption), ("R/required", RequirementConstraintKind.Requirement) }) + { + var constraintUsage = this.Builder.Create(name, ConstraintUsageExtensions.ToDto); + constraintUsage.IsComposite = true; + var membership = this.Builder.Create($"{name}/membership", RequirementConstraintMembershipExtensions.ToDto); + membership.Kind = kind; + requirement.AssignOwnership(membership, constraintUsage); + this.Typed(constraintUsage, constraint); + } + + var framed = this.Builder.Create("R/framed", ConcernUsageExtensions.ToDto); + framed.IsComposite = true; + var framing = this.Builder.Create("R/framed/membership", FramedConcernMembershipExtensions.ToDto); + framing.Kind = RequirementConstraintKind.Requirement; + requirement.AssignOwnership(framing, framed); + this.Typed(framed, concern); + + var usage = this.Member("rq", RequirementUsageExtensions.ToDto); + this.Typed(usage, requirement); + + var satisfy = this.Member("satisfy", SatisfyRequirementUsageExtensions.ToDto); + this.Subset(satisfy, usage); + + var binding = this.Builder.Create("satisfy/binding", BindingConnectorExtensions.ToDto); + this.OwnFeature(satisfy, binding); + + foreach (var (name, related) in new[] { ("satisfy/binding/subject", (IFeature)subject), ("satisfy/binding/satisfier", this.Builder.Find("systems structure/sub1")) }) + { + var end = this.Builder.Create(name, ReferenceUsageExtensions.ToDto); + end.IsEnd = true; + this.OwnFeature(binding, end); + this.MultiplicityOne(end, binding); + this.Subset(end, related); + } + + return usage; + } + + /// + /// Creates a named member of that specializes a definition through a + /// + /// + /// + /// The definition POCO type + /// + /// + /// The declared name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The specialized definition + /// + /// + /// The definition + /// + private TDefinition Specialized(string name, Func toDto, IClassifier general) where TDefinition : IClassifier, new() + { + var definition = this.Member(name, toDto); + + var subclassification = this.Builder.Create($"{name}/subclassification", SubclassificationExtensions.ToDto); + subclassification.Subclassifier = definition; + subclassification.Superclassifier = general; + definition.AssignOwnership(subclassification); + + return definition; + } + + /// + /// Adds the state definition St with entry, do and exit subactions, two states and a transition between + /// them with a trigger, a guard and an effect, and a state usage that a part definition exhibits + /// + private void States() + { + var state = this.Member("St", StateDefinitionExtensions.ToDto); + + foreach (var (name, kind) in new[] { ("entry", StateSubactionKind.Entry), ("do", StateSubactionKind.Do), ("exit", StateSubactionKind.Exit) }) + { + PocoElement action = kind == StateSubactionKind.Entry + ? this.Builder.Create($"St/{name}", SendActionUsageExtensions.ToDto) + : this.Builder.Create($"St/{name}", ActionUsageExtensions.ToDto); + + ((IFeature)action).IsComposite = true; + var membership = this.Builder.Create($"St/{name}/membership", StateSubactionMembershipExtensions.ToDto); + membership.Kind = kind; + state.AssignOwnership(membership, action); + + if (action is SendActionUsage send) + { + this.Value(this.Param(send, $"St/{name}/payload", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto), this.Literal($"St/{name}/payload/2", LiteralIntegerExtensions.ToDto, literal => literal.Value = 2)); + } + } + + var first = this.Owned(state, "s1", StateUsageExtensions.ToDto); + first.IsComposite = true; + var second = this.Owned(state, "s2", StateUsageExtensions.ToDto); + second.IsComposite = true; + + var transition = this.Owned(state, "t", TransitionUsageExtensions.ToDto); + this.Refer(transition, first); + this.Param(transition, "t/source", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + this.Param(transition, "t/payload", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + + var succession = this.Builder.Create("t/succession", SuccessionExtensions.ToDto); + this.OwnFeature(transition, succession); + + foreach (var (name, related) in new[] { ("t/succession/first", first), ("t/succession/then", second) }) + { + var end = this.Builder.Create(name, FeatureExtensions.ToDto); + end.IsEnd = true; + this.OwnFeature(succession, end); + this.MultiplicityOne(end, succession); + this.Subset(end, related); + } + + var trigger = this.Builder.Create("t/trigger", AcceptActionUsageExtensions.ToDto); + this.Param(trigger, "t/trigger/payload", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto); + var guard = this.Literal("t/guard", LiteralBooleanExtensions.ToDto, literal => literal.Value = true); + var effect = this.Builder.Create("t/effect", ActionUsageExtensions.ToDto); + + foreach (var (kind, feature) in new[] { (TransitionFeatureKind.Trigger, (IFeature)trigger), (TransitionFeatureKind.Guard, guard), (TransitionFeatureKind.Effect, effect) }) + { + feature.IsComposite = true; + var membership = this.Builder.Create($"t/{kind}/membership", TransitionFeatureMembershipExtensions.ToDto); + membership.Kind = kind; + transition.AssignOwnership(membership, feature); + } + + var exhibited = this.Member("stu", StateUsageExtensions.ToDto); + this.Typed(exhibited, state); + + var exhibit = this.Owned(this.Member("Exhibitor", PartDefinitionExtensions.ToDto), "exhibit", ExhibitStateUsageExtensions.ToDto); + this.Subset(exhibit, exhibited); + } + + /// + /// Makes a feature reference another through a + /// + /// + /// The referencing feature + /// + /// + /// The referenced feature + /// + private void Subset(IFeature feature, IFeature referenced) + { + var reference = this.Builder.Create($"{feature.ElementId}/reference", ReferenceSubsettingExtensions.ToDto); + reference.ReferencedFeature = referenced; + feature.AssignOwnership(reference); + } + + /// + /// Gives a feature a value through a + /// + /// + /// The feature + /// + /// + /// The value expression + /// + private void Value(IFeature feature, IExpression value) + { + feature.AssignOwnership(this.Builder.Create($"{feature.ElementId}/value", FeatureValueExtensions.ToDto), value); + } + + /// + /// Adds the view, viewpoint and rendering definitions and usages, and a view usage that exposes the part definition + /// and the package of step 6 + /// + /// + /// The model of step 6 + /// + private void Views(SystemsStructureModel structure) + { + var rendering = this.Member("RD", RenderingDefinitionExtensions.ToDto); + this.Typed(this.Member("rend", RenderingUsageExtensions.ToDto), rendering); + + var view = this.Member("VD", ViewDefinitionExtensions.ToDto); + var viewRendering = this.Builder.Create("VD/rendering", RenderingUsageExtensions.ToDto); + viewRendering.IsComposite = true; + view.AssignOwnership(this.Builder.Create("VD/rendering/membership", ViewRenderingMembershipExtensions.ToDto), viewRendering); + this.Typed(viewRendering, rendering); + + var usage = this.Member("v", ViewUsageExtensions.ToDto); + this.Typed(usage, view); + + var viewpoint = this.Owned(usage, "vp", ViewpointUsageExtensions.ToDto); + viewpoint.IsComposite = true; + this.Typed(viewpoint, this.Builder.Find("systems behaviour/VPD")); + + var membershipExpose = this.Builder.Create("v/expose P", MembershipExposeExtensions.ToDto); + membershipExpose.IsImportAll = true; + membershipExpose.Visibility = VisibilityKind.Protected; + membershipExpose.ImportedMembership = (IMembership)structure.Part.OwningRelationship; + usage.AssignOwnership(membershipExpose); + + var namespaceExpose = this.Builder.Create("v/expose Systems", NamespaceExposeExtensions.ToDto); + namespaceExpose.IsImportAll = true; + namespaceExpose.Visibility = VisibilityKind.Protected; + namespaceExpose.ImportedNamespace = structure.Package; + usage.AssignOwnership(namespaceExpose); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs new file mode 100644 index 000000000..ba124ecee --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs @@ -0,0 +1,435 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Kernel.Interactions; + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Core.POCO.Systems.Allocations; + using SysML2.NET.Core.POCO.Systems.Attributes; + using SysML2.NET.Core.POCO.Systems.Connections; + using SysML2.NET.Core.POCO.Systems.DefinitionAndUsage; + using SysML2.NET.Core.POCO.Systems.Enumerations; + using SysML2.NET.Core.POCO.Systems.Flows; + using SysML2.NET.Core.POCO.Systems.Interfaces; + using SysML2.NET.Core.POCO.Systems.Items; + using SysML2.NET.Core.POCO.Systems.Occurrences; + using SysML2.NET.Core.POCO.Systems.Parts; + using SysML2.NET.Core.POCO.Systems.Ports; + using SysML2.NET.Core.Systems.Occurrences; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + + /// + /// The model of scenario step 6: the SysML structure metaclasses, in a package Systems of the root package, + /// committed on the branch systems + /// + /// + /// + /// package Systems { + /// part def Q; attribute def A; occurrence def O; item def I { attribute content : A; } + /// abstract enum def E { enum e1; enum e2; } + /// abstract variation part def PV { variant part pv1 : PV; } + /// port def PD { attribute pa : A; } // owns ~PD through a port conjugation + /// connection def CD { end ref cdA : P [1]; end ref cdB : P [1]; } + /// interface def IF { end port ifA : PD [1]; end port ifB : ~PD [1]; } + /// allocation def AD { end ref adA : P [1]; end ref adB : I [1]; } + /// flow def FD { end ref fdA : I [1]; end ref fdB : I [1]; } + /// part def P { + /// attribute x : A; attribute y : A; enum ev : E; + /// occurrence o1 : O; occurrence o2 : O; timeslice ts : O; snapshot sn : O; event occurrence ev1 = o1; + /// item it1 : I; item it2 : I; part sub1 : Q; part sub2 : Q; port p1 : PD; port p2 : ~PD; ref r; + /// connection c : CD connect sub1 to sub2; interface i : IF connect p1 to p2; + /// allocation al : AD allocate sub1 to it1; binding b of x = y; succession s first o1 then o2; + /// flow f : FD from it1.content to it2.content; succession flow sf from it1.content to it2.content; + /// } + /// definition D { usage u; } + /// } + /// + /// Every end has the multiplicity [1], every directed or end usage is referential, and the rules that need + /// the model library (the check…Specialization rules) cannot hold without one. + /// + public sealed class SystemsStructureModel : StepModel + { + /// + /// Initializes a new instance of the class and builds the model on that of + /// steps 2 to 5 + /// + /// + /// The model of step 2 + /// + public SystemsStructureModel(RootModel root) : base((root ?? throw new ArgumentNullException(nameof(root))).Builder, "systems structure") + { + this.Package = this.CreateNamed("Systems", "sys", PackageExtensions.ToDto); + this.OwnMember(root.Root, this.Package); + + var q = this.Member("Q", PartDefinitionExtensions.ToDto); + this.AttributeDefinition = this.Member("A", AttributeDefinitionExtensions.ToDto); + this.OccurrenceDefinition = this.Member("O", OccurrenceDefinitionExtensions.ToDto); + + this.ItemDefinition = this.Member("I", ItemDefinitionExtensions.ToDto); + this.ItemContent = this.Owned(this.ItemDefinition, "content", AttributeUsageExtensions.ToDto, this.AttributeDefinition); + + var enumeration = this.Member("E", EnumerationDefinitionExtensions.ToDto); + enumeration.IsVariation = true; + enumeration.IsAbstract = true; + + foreach (var name in new[] { "e1", "e2" }) + { + var value = this.CreateNamed(name, name, EnumerationUsageExtensions.ToDto); + enumeration.AssignOwnership(this.Builder.Create($"E/{name}/membership", VariantMembershipExtensions.ToDto), value); + this.Typed(value, enumeration); + } + + var variation = this.Member("PV", PartDefinitionExtensions.ToDto); + variation.IsVariation = true; + variation.IsAbstract = true; + var variant = this.CreateNamed("pv1", "pv1", PartUsageExtensions.ToDto); + variation.AssignOwnership(this.Builder.Create("PV/pv1/membership", VariantMembershipExtensions.ToDto), variant); + this.Typed(variant, variation); + + this.PortDefinition = this.Member("PD", PortDefinitionExtensions.ToDto); + this.Owned(this.PortDefinition, "pa", AttributeUsageExtensions.ToDto, this.AttributeDefinition); + + this.ConjugatedPortDefinition = this.Builder.Create("PD/conjugated", ConjugatedPortDefinitionExtensions.ToDto); + this.OwnMember(this.PortDefinition, this.ConjugatedPortDefinition); + + var conjugation = this.Builder.Create("PD/conjugated/conjugation", PortConjugationExtensions.ToDto); + conjugation.OriginalPortDefinition = this.PortDefinition; + conjugation.ConjugatedType = this.ConjugatedPortDefinition; + this.ConjugatedPortDefinition.AssignOwnership(conjugation); + + this.Part = this.Member("P", PartDefinitionExtensions.ToDto); + + var connection = this.Member("CD", ConnectionDefinitionExtensions.ToDto); + connection.IsSufficient = true; + this.End(connection, "cdA", ReferenceUsageExtensions.ToDto, this.Part); + this.End(connection, "cdB", ReferenceUsageExtensions.ToDto, this.Part); + + var interfaceDefinition = this.Member("IF", InterfaceDefinitionExtensions.ToDto); + interfaceDefinition.IsSufficient = true; + this.End(interfaceDefinition, "ifA", PortUsageExtensions.ToDto, this.PortDefinition); + var conjugatedEnd = this.End(interfaceDefinition, "ifB", PortUsageExtensions.ToDto, null); + this.ConjugatedTyping(conjugatedEnd); + + var allocation = this.Member("AD", AllocationDefinitionExtensions.ToDto); + allocation.IsSufficient = true; + this.End(allocation, "adA", ReferenceUsageExtensions.ToDto, this.Part); + this.End(allocation, "adB", ReferenceUsageExtensions.ToDto, this.ItemDefinition); + + var flowDefinition = this.Member("FD", FlowDefinitionExtensions.ToDto); + this.End(flowDefinition, "fdA", ReferenceUsageExtensions.ToDto, this.ItemDefinition); + this.End(flowDefinition, "fdB", ReferenceUsageExtensions.ToDto, this.ItemDefinition); + + var x = this.Owned(this.Part, "x", AttributeUsageExtensions.ToDto, this.AttributeDefinition); + var y = this.Owned(this.Part, "y", AttributeUsageExtensions.ToDto, this.AttributeDefinition); + this.Owned(this.Part, "ev", EnumerationUsageExtensions.ToDto, enumeration); + + var o1 = this.Owned(this.Part, "o1", OccurrenceUsageExtensions.ToDto, this.OccurrenceDefinition); + var o2 = this.Owned(this.Part, "o2", OccurrenceUsageExtensions.ToDto, this.OccurrenceDefinition); + + foreach (var (name, kind) in new[] { ("ts", PortionKind.Timeslice), ("sn", PortionKind.Snapshot) }) + { + var portion = this.Owned(this.Part, name, OccurrenceUsageExtensions.ToDto, this.OccurrenceDefinition); + portion.IsPortion = true; + portion.PortionKind = kind; + } + + var eventOccurrence = this.Owned(this.Part, "ev1", EventOccurrenceUsageExtensions.ToDto, null); + this.Reference(eventOccurrence, "ev1/reference", o1); + + this.FirstItem = this.Owned(this.Part, "it1", ItemUsageExtensions.ToDto, this.ItemDefinition); + var secondItem = this.Owned(this.Part, "it2", ItemUsageExtensions.ToDto, this.ItemDefinition); + var sub1 = this.Owned(this.Part, "sub1", PartUsageExtensions.ToDto, q); + var sub2 = this.Owned(this.Part, "sub2", PartUsageExtensions.ToDto, q); + var p1 = this.Owned(this.Part, "p1", PortUsageExtensions.ToDto, this.PortDefinition); + var p2 = this.Owned(this.Part, "p2", PortUsageExtensions.ToDto, null); + this.ConjugatedTyping(p2); + this.Owned(this.Part, "r", ReferenceUsageExtensions.ToDto, null); + + this.Connect("c", ConnectionUsageExtensions.ToDto, ReferenceUsageExtensions.ToDto, connection, sub1, sub2); + this.Connect("i", InterfaceUsageExtensions.ToDto, PortUsageExtensions.ToDto, interfaceDefinition, p1, p2); + this.Connect("al", AllocationUsageExtensions.ToDto, ReferenceUsageExtensions.ToDto, allocation, sub1, this.FirstItem); + this.Connect("b", BindingConnectorAsUsageExtensions.ToDto, ReferenceUsageExtensions.ToDto, null, x, y); + this.Connect("s", SuccessionAsUsageExtensions.ToDto, ReferenceUsageExtensions.ToDto, null, o1, o2); + + this.Flow("f", FlowUsageExtensions.ToDto, flowDefinition, this.FirstItem, secondItem); + this.Flow("sf", SuccessionFlowUsageExtensions.ToDto, null, this.FirstItem, secondItem); + + var definition = this.Member("D", DefinitionExtensions.ToDto); + var usage = this.Owned(definition, "u", UsageExtensions.ToDto, null); + usage.IsComposite = true; + } + + /// + /// Gets the package that holds the step + /// + public Package Package { get; } + + /// + /// Gets the part definition P, which owns a usage of every kind + /// + public PartDefinition Part { get; } + + /// + /// Gets the attribute definition A + /// + public AttributeDefinition AttributeDefinition { get; } + + /// + /// Gets the occurrence definition O + /// + public OccurrenceDefinition OccurrenceDefinition { get; } + + /// + /// Gets the item definition I + /// + public ItemDefinition ItemDefinition { get; } + + /// + /// Gets the attribute content of , which the flow features redefine + /// + public AttributeUsage ItemContent { get; } + + /// + /// Gets the item usage it1 of + /// + public ItemUsage FirstItem { get; } + + /// + /// Gets the port definition PD + /// + public PortDefinition PortDefinition { get; } + + /// + /// Gets the conjugated port definition ~PD, owned by + /// + public ConjugatedPortDefinition ConjugatedPortDefinition { get; } + + /// + /// Types a port usage by through a + /// + /// + /// The port usage + /// + private void ConjugatedTyping(PortUsage port) + { + var typing = this.Builder.Create($"{port.ElementId}/conjugated typing", ConjugatedPortTypingExtensions.ToDto); + typing.TypedFeature = port; + typing.ConjugatedPortDefinition = this.ConjugatedPortDefinition; + port.AssignOwnership(typing); + } + + /// + /// Creates a connector usage of between two of its features: two referential end usages with + /// the multiplicity [1], each referencing a related feature + /// + /// + /// The connector usage POCO type + /// + /// + /// The end usage POCO type + /// + /// + /// The name of the connector usage + /// + /// + /// The generated ToDto extension of + /// + /// + /// The generated ToDto extension of + /// + /// + /// The definition that types the connector usage, or null + /// + /// + /// The first related feature + /// + /// + /// The second related feature + /// + private void Connect(string name, Func toDto, Func endToDto, IType definition, IFeature source, IFeature target) + where TConnector : IFeature, new() + where TEnd : IFeature, new() + { + var connector = this.Owned(this.Part, name, toDto, definition); + + foreach (var (endName, related) in new[] { ($"{name}/source", source), ($"{name}/target", target) }) + { + var end = this.Builder.Create(endName, endToDto); + end.IsEnd = true; + this.OwnFeature(connector, end); + this.MultiplicityOne(end, connector); + this.Reference(end, $"{endName}/reference", related); + } + } + + /// + /// Creates an end usage of a connection-like definition, typed by one type, with the multiplicity [1] + /// + /// + /// The end usage POCO type + /// + /// + /// The definition + /// + /// + /// The name of the end + /// + /// + /// The generated ToDto extension of + /// + /// + /// The type of the end, or null when the caller types it + /// + /// + /// The end usage + /// + private TEnd End(IType owner, string name, Func toDto, IType type) where TEnd : IFeature, new() + { + var end = this.CreateNamed(name, name, toDto); + end.IsEnd = true; + this.OwnFeature(owner, end); + + if (type != null) + { + this.Typed(end, type); + } + + this.MultiplicityOne(end, owner); + + return end; + } + + /// + /// Creates a flow-like usage of from the content of one item usage to that of another + /// + /// + /// The flow usage POCO type + /// + /// + /// The name of the flow usage + /// + /// + /// The generated ToDto extension of + /// + /// + /// The flow definition that types the flow usage, or null + /// + /// + /// The source item usage + /// + /// + /// The target item usage + /// + private void Flow(string name, Func toDto, IType definition, IFeature source, IFeature target) where TFlow : IFeature, new() + { + var flow = this.Owned(this.Part, name, toDto, definition); + + foreach (var (endName, related) in new[] { ($"{name}/source", source), ($"{name}/target", target) }) + { + var end = this.Builder.Create(endName, FlowEndExtensions.ToDto); + end.IsEnd = true; + this.OwnFeature(flow, end); + this.MultiplicityOne(end, flow); + this.Reference(end, $"{endName}/reference", related); + + var flowFeature = this.Builder.Create($"{endName}/feature", ReferenceUsageExtensions.ToDto); + this.OwnFeature(end, flowFeature); + + var redefinition = this.Builder.Create($"{endName}/feature/redefinition", RedefinitionExtensions.ToDto); + redefinition.RedefiningFeature = flowFeature; + redefinition.RedefinedFeature = this.ItemContent; + flowFeature.AssignOwnership(redefinition); + } + } + + /// + /// Creates a named member of + /// + /// + /// The POCO type + /// + /// + /// The declared name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The member + /// + private TPoco Member(string name, Func toDto) where TPoco : SysML2.NET.Core.POCO.Root.Elements.IElement, new() + { + var member = this.CreateNamed(name, name.ToLowerInvariant(), toDto); + this.OwnMember(this.Package, member); + + return member; + } + + /// + /// Creates a named usage owned by a type, typed by another type when one is given + /// + /// + /// The usage POCO type + /// + /// + /// The owning type + /// + /// + /// The declared name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The type of the usage, or null to leave it untyped + /// + /// + /// The usage + /// + private TUsage Owned(IType owner, string name, Func toDto, IType type) where TUsage : IFeature, new() + { + var usage = this.CreateNamed(name, name, toDto); + this.OwnFeature(owner, usage); + + if (type != null) + { + this.Typed(usage, type); + } + + return usage; + } + + /// + /// Makes a feature reference another through a + /// + /// + /// The referencing feature + /// + /// + /// The name the reference subsetting is derived from + /// + /// + /// The referenced feature + /// + private void Reference(IFeature feature, string name, IFeature referenced) + { + var reference = this.Builder.Create(name, ReferenceSubsettingExtensions.ToDto); + reference.ReferencedFeature = referenced; + feature.AssignOwnership(reference); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs index 96210c851..6a1e533c2 100644 --- a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs +++ b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs @@ -13,6 +13,7 @@ namespace SySML2.NET.REST.Tests.Helpers using System.Collections.Generic; using System.Linq; using System.Net; + using System.Threading; using System.Threading.Tasks; using NUnit.Framework; @@ -45,6 +46,11 @@ public sealed class ReadBackAssertions /// private const int MaximumPages = 1000; + /// + /// The number of independent reads sent to the server at the same time + /// + private const int ReadConcurrency = 4; + /// /// The client under test /// @@ -188,7 +194,10 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous } Assert.That(changes.Select(change => change.Identity.Id), Is.EquivalentTo(changed.Select(element => element.Id))); - Assert.That(changePages, Is.GreaterThan(1), "the changes did not span several pages, so paging is untested"); + if (changed.Count > PageSize) + { + Assert.That(changePages, Is.GreaterThan(1), "the changes did not span several pages, so paging is untested"); + } var sentById = changed.ToDictionary(element => element.Id); @@ -331,14 +340,15 @@ public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expect using (Assert.EnterMultipleScope()) { - foreach (var element in changed) - { - var (succeeded, actual) = await this.TryReadAsync(() => this.client.GetElementByProjectCommitIdAsync(projectId, commitId, element.Id), $"GetElementByProjectCommitIdAsync of {element.GetType().Name} {element.Id}"); + var byId = await this.ReadManyAsync( + changed, + element => this.client.GetElementByProjectCommitIdAsync(projectId, commitId, element.Id), + element => $"GetElementByProjectCommitIdAsync of {element.GetType().Name} {element.Id}", + (element, call) => call.RequestLine.Contains(element.Id.ToString(), StringComparison.OrdinalIgnoreCase)); - if (succeeded) - { - readById[element.Id] = actual; - } + foreach (var (element, actual) in byId.Where(outcome => outcome.Succeeded).Select(outcome => (outcome.Key, outcome.Value))) + { + readById[element.Id] = actual; } var read = changed.Where(element => readById.ContainsKey(element.Id)).ToList(); @@ -507,13 +517,106 @@ private async Task ReadAsync(Func> read, string description) return value; } + /// + /// Runs independent reads, at a time, and reports every read that throws once all + /// have ended, so that every assertion runs on the context of the test + /// + /// + /// The type of what a read is about + /// + /// + /// The type of what is read + /// + /// + /// What the reads are about, one read each + /// + /// + /// The read for a key + /// + /// + /// The description of the read for a key in the failure message + /// + /// + /// Whether a recorded call is the request of the read for a key; concurrent reads share the recorder + /// + /// + /// Per key, in order, whether its read succeeded and what it read + /// + private async Task> ReadManyAsync(IReadOnlyList keys, Func> read, Func describe, Func isCallOf) + { + var callsBefore = this.recordedCalls?.Invoke().Count ?? 0; + + using var gate = new SemaphoreSlim(ReadConcurrency); + + var outcomes = await Task.WhenAll(keys.Select(async key => + { + await gate.WaitAsync(); + + try + { + return (Key: key, Failure: (Exception)null, Value: await read(key)); + } + catch (Exception exception) when (exception is not ResultStateException) + { + return (Key: key, Failure: exception, Value: default(T)); + } + finally + { + gate.Release(); + } + })); + + var recorded = (this.recordedCalls?.Invoke() ?? []).Skip(callsBefore).ToList(); + + foreach (var (key, failure, _) in outcomes.Where(outcome => outcome.Failure != null)) + { + this.ReportFailedRead(describe(key), failure, recorded.Where(call => isCallOf(key, call))); + } + + return [.. outcomes.Select(outcome => (outcome.Key, outcome.Failure == null, outcome.Value))]; + } + + /// + /// Reports a read that threw: as a warning when one of its calls got a response showing a known divergence that + /// breaks deserialization, which reports, and as a failure otherwise + /// + /// + /// Every Flexo response breaks the document in some tolerated way, so only a divergence that breaks + /// deserialization excuses a failed read; a client defect must still fail. + /// + /// + /// The description of the read + /// + /// + /// What the read threw + /// + /// + /// The calls that the read made + /// + private void ReportFailedRead(string description, Exception exception, IEnumerable calls) + { + var failure = $"{description} threw {exception.GetType().Name}: {exception.Message}"; + + var excused = calls + .SelectMany(call => call.ResponseViolations.Select(violation => (Call: call, Divergence: this.divergences.FirstOrDefault(divergence => divergence.BreaksDeserialization && divergence.Explains?.Invoke(call, violation) == true)))) + .FirstOrDefault(entry => entry.Divergence != null); + + if (excused.Divergence != null) + { + Assert.Warn($"{failure}, on a response that shows the known divergence that {excused.Divergence.Summary} ({excused.Call.RequestLine}); the OpenAPI conformance check reports the response"); + } + else + { + Assert.Fail(failure); + } + } + /// /// Reads from the server, reporting a read that throws as a failure, or as a warning when a response of that /// read shows a known divergence that breaks deserialization, which reports /// /// - /// Only the calls recorded while the read ran count, and only divergences that break deserialization: every - /// Flexo response breaks the document in some tolerated way, and a client defect must still fail. + /// Only the calls recorded while the read ran count, so that a response of an earlier read excuses nothing. /// /// /// The type of what is read @@ -537,21 +640,7 @@ private async Task ReadAsync(Func> read, string description) } catch (Exception exception) when (exception is not ResultStateException) { - var failure = $"{description} threw {exception.GetType().Name}: {exception.Message}"; - - var excused = (this.recordedCalls?.Invoke() ?? []).Skip(callsBefore) - .SelectMany(call => call.ResponseViolations.Select(violation => (Call: call, Divergence: this.divergences.FirstOrDefault(divergence => divergence.BreaksDeserialization && divergence.Explains?.Invoke(call, violation) == true)))) - .FirstOrDefault(entry => entry.Divergence != null); - - if (excused.Divergence != null) - { - Assert.Warn($"{failure}, on a response that shows the known divergence that {excused.Divergence.Summary} ({excused.Call.RequestLine}); the OpenAPI conformance check reports the response"); - } - else - { - Assert.Fail(failure); - } - + this.ReportFailedRead(description, exception, (this.recordedCalls?.Invoke() ?? []).Skip(callsBefore)); return (false, default); } } @@ -586,14 +675,15 @@ private async Task VerifyRelationshipsAsync(Guid commitId, IReadOnlyList ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, direction, queryParameters: parameters)), $"GetRelationshipsByProjectCommitRelatedElementAsync {direction}"); + var reads = await this.ReadManyAsync( + directions, + entry => ReadAllPagesAsync(parameters => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(projectId, commitId, subjectId, entry.Direction, queryParameters: parameters)), + entry => $"GetRelationshipsByProjectCommitRelatedElementAsync {entry.Direction}", + (entry, call) => call.RequestLine.Contains($"direction={entry.Direction}", StringComparison.Ordinal)); - if (read != null) - { - Assert.That(read.Select(relationship => relationship.Id), Is.EquivalentTo(expectedIds), $"the {direction} relationships"); - } + foreach (var ((direction, expectedIds), _, (read, _)) in reads.Where(outcome => outcome.Succeeded)) + { + Assert.That(read.Select(relationship => relationship.Id), Is.EquivalentTo(expectedIds), $"the {direction} relationships"); } } } diff --git a/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs index 0c9469f09..333368a86 100644 --- a/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs +++ b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs @@ -33,9 +33,19 @@ public sealed class ScenarioState public Guid? DefaultBranchId { get; set; } /// - /// Gets or sets the id of the latest commit on the default branch, or null before the first commit + /// Gets the head commit of every branch the scenario committed on, by branch id /// - public Guid? HeadCommitId { get; set; } + public Dictionary BranchHeads { get; } = []; + + /// + /// Gets the ids of the branches the scenario created, by name + /// + public Dictionary BranchIds { get; } = []; + + /// + /// Gets the head commit of the default branch, or null before its first commit + /// + public Guid? HeadCommitId => this.DefaultBranchId is { } branch && this.BranchHeads.TryGetValue(branch, out var head) ? head : null; /// /// Gets the expected model at each commit, by commit id diff --git a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs index 443956b74..61be73b0a 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs @@ -36,7 +36,7 @@ public void VerifyAll() { using (Assert.EnterMultipleScope()) { - Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.DiffNotImplemented, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri])); + Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.DiffNotImplemented, KnownServerDivergences.MergeNotImplemented, KnownServerDivergences.MergeRequiresArrayBody, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri])); Assert.That(KnownServerDivergences.All.Select(divergence => divergence.Reference), Has.All.Contains("Open-MBEE/flexo-mms-sysmlv2@836d904d")); } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs index f66fb6dce..1a47c379b 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs @@ -70,6 +70,31 @@ public void VerifyChanged() } } + [Test] + public void VerifyCopy() + { + Assert.That(() => ModelBuilder.Copy(null), Throws.ArgumentNullException); + + var builder = new ModelBuilder("scope"); + var package = builder.Create("Package", PackageExtensions.ToDto); + package.DeclaredName = "Original"; + package.AliasIds = ["first"]; + var dto = builder.ToDtos()[0]; + + var copy = ModelBuilder.Copy(dto); + copy.DeclaredName = "Copy"; + copy.AliasIds.Add("second"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(copy, Is.Not.SameAs(dto)); + Assert.That(copy, Is.TypeOf(dto.GetType())); + Assert.That(copy.Id, Is.EqualTo(dto.Id)); + Assert.That(dto.DeclaredName, Is.EqualTo("Original")); + Assert.That(dto.AliasIds, Is.EqualTo((string[])["first"])); + } + } + [Test] public void VerifyCreate() { diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs new file mode 100644 index 000000000..082a4805d --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs @@ -0,0 +1,76 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System.IO; + using System.Linq; + using System.Text; + using System.Text.Json; + + using NUnit.Framework; + + using SysML2.NET.Serializer.Json; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + [TestFixture] + public class SystemsBehaviorModelTestFixture + { + private static readonly string[] BehaviorMetaclasses = + [ + "AcceptActionUsage", "ActionDefinition", "ActionUsage", "AssignmentActionUsage", "DecisionNode", "ForLoopActionUsage", "ForkNode", + "IfActionUsage", "JoinNode", "MergeNode", "PerformActionUsage", "SendActionUsage", "TerminateActionUsage", "TriggerInvocationExpression", + "WhileLoopActionUsage", "StateDefinition", "StateUsage", "ExhibitStateUsage", "StateSubactionMembership", "TransitionUsage", + "TransitionFeatureMembership", "CalculationDefinition", "CalculationUsage", "ConstraintDefinition", "ConstraintUsage", + "AssertConstraintUsage", "RequirementDefinition", "RequirementUsage", "SatisfyRequirementUsage", "ConcernDefinition", "ConcernUsage", + "ActorMembership", "StakeholderMembership", "SubjectMembership", "FramedConcernMembership", "RequirementConstraintMembership", + "CaseDefinition", "CaseUsage", "ObjectiveMembership", "AnalysisCaseDefinition", "AnalysisCaseUsage", "VerificationCaseDefinition", + "VerificationCaseUsage", "RequirementVerificationMembership", "UseCaseDefinition", "UseCaseUsage", "IncludeUseCaseUsage", + "ViewDefinition", "ViewUsage", "ViewpointDefinition", "ViewpointUsage", "RenderingDefinition", "RenderingUsage", + "ViewRenderingMembership", "MembershipExpose", "NamespaceExpose", "MetadataDefinition", "MetadataUsage" + ]; + + [Test] + public void VerifySystemsBehaviorModel() + { + var root = new RootModel(); + var structure = new SystemsStructureModel(root); + + using (Assert.EnterMultipleScope()) + { + Assert.That(() => new SystemsBehaviorModel(null, structure), Throws.ArgumentNullException); + Assert.That(() => new SystemsBehaviorModel(root, null), Throws.ArgumentNullException); + } + + root = new RootModel(); + structure = new SystemsStructureModel(root); + + var atStep6 = root.Builder.ToDtos(); + var model = new SystemsBehaviorModel(root, structure); + + var dtos = model.Builder.ToDtos(); + var changed = ModelBuilder.Changed(atStep6, dtos); + + using var stream = new MemoryStream(); + new Serializer().SerializeRequest(ModelBuilder.ToCommitRequest(changed, "systems behaviour"), SerializationModeKind.JSON, false, stream, new JsonWriterOptions()); + var json = Encoding.UTF8.GetString(stream.ToArray()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(dtos.Select(dto => dto.GetType().Name).Distinct(), Is.SupersetOf(BehaviorMetaclasses)); + Assert.That(changed.Select(dto => dto.Id), Does.Contain(root.Root.Id).And.Contain(structure.OccurrenceDefinition.Id), "the root package and the occurrence definition of step 6 change"); + Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); + Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo((string[])["systems behaviour/accept when/trigger", "systems behaviour/accept at/trigger", "systems behaviour/accept after/trigger"]), "only the trigger invocations, whose instantiated type needs the model library"); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs new file mode 100644 index 000000000..5edaf64ca --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System; + using System.IO; + using System.Linq; + using System.Text; + using System.Text.Json; + + using NUnit.Framework; + + using SysML2.NET.Core.POCO.Kernel.Expressions; + using SysML2.NET.Serializer.Json; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + [TestFixture] + public class SystemsStructureModelTestFixture + { + private static readonly string[] StructureMetaclasses = + [ + "Definition", "Usage", "ReferenceUsage", "VariantMembership", "AttributeDefinition", "AttributeUsage", "EnumerationDefinition", + "EnumerationUsage", "OccurrenceDefinition", "OccurrenceUsage", "EventOccurrenceUsage", "ItemDefinition", "ItemUsage", + "PartDefinition", "PartUsage", "PortDefinition", "PortUsage", "ConjugatedPortDefinition", "ConjugatedPortTyping", + "PortConjugation", "ConnectionDefinition", "ConnectionUsage", "BindingConnectorAsUsage", "SuccessionAsUsage", + "InterfaceDefinition", "InterfaceUsage", "AllocationDefinition", "AllocationUsage", "FlowDefinition", "FlowUsage", + "SuccessionFlowUsage" + ]; + + [Test] + public void VerifySystemsStructureModel() + { + Assert.That(() => new SystemsStructureModel(null), Throws.ArgumentNullException); + + var root = new RootModel(); + var core = new CoreModel(root); + var kernel = new KernelModel(root, core); + _ = new KerMLUpdateModel(root, core, kernel); + + var atStep5 = root.Builder.ToDtos(); + var model = new SystemsStructureModel(root); + + var dtos = model.Builder.ToDtos(); + var changed = ModelBuilder.Changed(atStep5, dtos); + + using var stream = new MemoryStream(); + new Serializer().SerializeRequest(ModelBuilder.ToCommitRequest(changed, "systems structure"), SerializationModeKind.JSON, false, stream, new JsonWriterOptions()); + var json = Encoding.UTF8.GetString(stream.ToArray()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(dtos.Select(dto => dto.GetType().Name).Distinct(), Is.SupersetOf(StructureMetaclasses)); + Assert.That(changed.Select(dto => dto.Id), Does.Contain(root.Root.Id), "the root package owns the new package"); + Assert.That(changed.Where(dto => atStep5.Any(before => before.Id == dto.Id)).Select(dto => dto.Id), Is.EquivalentTo((Guid[])[root.Root.Id, root.Builder.Find("kernel/rational").Id]), "the root package, and the rational literal that its comparer reports as changed (#426)"); + Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); + Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo((string[])["kernel/sum", "kernel/index", "kernel/select", "kernel/collect", "kernel/chain"]), "no structure element loses its derived values"); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs index e05431504..2fb146811 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs @@ -10,6 +10,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests { using System; + using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; @@ -110,6 +111,7 @@ public async Task VerifyVerifyCommitAsync() DataVersion changeById = null; Guid? head = this.commitId; var changesUnreadable = false; + var changesOnOnePage = false; var commitUnreadable = false; @@ -127,7 +129,7 @@ public async Task VerifyVerifyCommitAsync() }); this.client.Setup(api => api.GetCommitsByProjectAsync(this.projectId, It.IsAny(), It.IsAny())).Returns((Guid _, QueryParameters parameters, CancellationToken _) => Paged(commits, parameters)); this.client.Setup(api => api.GetBranchesByProjectAndIdAsync(this.projectId, branchId, It.IsAny())).ReturnsAsync(() => new Branch { Id = branchId, Head = head }); - this.client.Setup(api => api.GetChangesByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).Returns((Guid _, Guid _, QueryParameters parameters, CancellationToken _) => changesUnreadable ? throw new InvalidOperationException("no changes") : Paged(changes, parameters)); + this.client.Setup(api => api.GetChangesByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).Returns((Guid _, Guid _, QueryParameters parameters, CancellationToken _) => changesUnreadable ? throw new InvalidOperationException("no changes") : Paged(changes, changesOnOnePage ? null : parameters)); this.client.Setup(api => api.GetChangeByProjectCommitIdAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).ReturnsAsync((Guid _, Guid _, Guid changeId, CancellationToken _) => changeById ?? changes.Single(change => change.Id == changeId)); var firstCommit = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, null, changed)); @@ -168,9 +170,14 @@ public async Task VerifyVerifyCommitAsync() var changeByIdOther = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); changeById = null; + changesOnOnePage = true; + + var onePage = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); + + changesOnOnePage = false; changes = changes[..5]; - var onePage = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed[..5])); + var smallCommit = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed[..5])); var missingChanges = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCommitAsync(commit, branchId, previousId, changed)); changes = []; @@ -221,16 +228,17 @@ public async Task VerifyVerifyCommitAsync() Assert.That(changeByIdOther, Has.Count.EqualTo(1)); Assert.That(onePage, Has.Count.EqualTo(1)); Assert.That(onePage[0].Message, Does.Contain("paging is untested")); + Assert.That(smallCommit, Is.Empty, "a commit that fits on one page does not test paging, and need not"); Assert.That(missingChanges, Has.Count.EqualTo(2)); - Assert.That(noChanges, Has.Count.EqualTo(1)); + Assert.That(noChanges, Is.Empty); Assert.That(unreadableChanges.Select(result => result.Message), Is.EqualTo((string[])["GetChangesByProjectCommitAsync threw InvalidOperationException: no changes"]), "the commit, the list and the branch head still pass"); Assert.That(unreadableCommit.Select(result => result.Message), Has.Some.Contains("GetCommitByProjectAndIdAsync threw InvalidOperationException: previousCommit is an object")); - Assert.That(unreadableCommit, Has.Count.EqualTo(2), "the commit read fails, and the other commit checks still run"); - Assert.That(unreadableOnBreakingResponse.Select(result => result.Status), Is.EquivalentTo((AssertionStatus[])[AssertionStatus.Warning, AssertionStatus.Failed])); + Assert.That(unreadableCommit, Has.Count.EqualTo(1), "the commit read fails, and the other commit checks still run"); + Assert.That(unreadableOnBreakingResponse.Select(result => result.Status), Is.EquivalentTo((AssertionStatus[])[AssertionStatus.Warning])); Assert.That(unreadableOnBreakingResponse.Single(result => result.Status == AssertionStatus.Warning).Message, Does.Contain(KnownServerDivergences.PreviousCommitAsObject.Summary).And.Contain("(GET /projects/p/commits/c)")); - Assert.That(unreadableOnToleratedResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed, AssertionStatus.Failed]), "a tolerated divergence that does not break deserialization excuses nothing"); - Assert.That(unreadableOnConformingResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed, AssertionStatus.Failed])); - Assert.That(unreadableAfterEarlierBreakingResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed, AssertionStatus.Failed]), "a breaking response of an earlier call excuses nothing"); + Assert.That(unreadableOnToleratedResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed]), "a tolerated divergence that does not break deserialization excuses nothing"); + Assert.That(unreadableOnConformingResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(unreadableAfterEarlierBreakingResponse.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed]), "a breaking response of an earlier call excuses nothing"); } this.client.Verify(api => api.GetChangeByProjectCommitIdAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); @@ -333,12 +341,26 @@ public async Task VerifyVerifyModelAsync() IReadOnlyList listed = elements; var onePage = false; var unreadable = new HashSet(); + var breakingFor = new HashSet(); + var breaking = new ContractViolation(ContractViolationKind.SchemaMismatch, "/previousCommit type: Value is \"object\" but should be \"array\""); + var recordedReads = new ConcurrentQueue(); + var inFlight = 0; + var maximumInFlight = 0; var dropIncoming = false; var listUnreadable = false; Direction? unreadableDirection = null; this.client.Setup(api => api.GetElementByProjectCommitIdAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync((Guid _, Guid _, Guid elementId, bool? _, CancellationToken _) => unreadable.Contains(elementId) ? throw new InvalidOperationException("not deserializable") : readBack[elementId]); + .Returns(async (Guid _, Guid _, Guid elementId, bool? _, CancellationToken _) => + { + var now = Interlocked.Increment(ref inFlight); + Interlocked.Exchange(ref maximumInFlight, Math.Max(Interlocked.CompareExchange(ref maximumInFlight, 0, 0), now)); + await Task.Delay(5); + recordedReads.Enqueue(new EndpointCall(null, $"GET /elements/{elementId}", HttpStatusCode.OK) { ResponseViolations = breakingFor.Contains(elementId) ? [breaking] : [] }); + Interlocked.Decrement(ref inFlight); + + return unreadable.Contains(elementId) ? throw new InvalidOperationException("not deserializable") : readBack[elementId]; + }); this.client.Setup(api => api.GetElementsByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) .Returns((Guid _, Guid _, bool? _, QueryParameters parameters, CancellationToken _) => listUnreadable ? throw new InvalidOperationException("no list") : Paged(listed, onePage ? null : parameters)); @@ -466,6 +488,16 @@ public async Task VerifyVerifyModelAsync() this.client.Verify(api => api.GetElementByProjectCommitIdAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never, "an element that the commit did not change is not read by id"); + listed = elements; + unreadable.UnionWith([model.Nested.Id, model.Root.Id]); + breakingFor.Add(model.Root.Id); + var recording = new ReadBackAssertions(this.client.Object, this.state, () => [.. recordedReads], [KnownServerDivergences.PreviousCommitAsObject with { Explains = (_, violation) => violation == breaking }]); + Interlocked.Exchange(ref maximumInFlight, 0); + + var concurrentFailures = await IsolatedAssertions.RunAsync(() => recording.VerifyModelAsync(this.commitId, elements, elements, model.Nested.Id)); + + unreadable.Clear(); + using (Assert.EnterMultipleScope()) { Assert.That(identical, Is.Empty); @@ -494,6 +526,9 @@ public async Task VerifyVerifyModelAsync() Assert.That(memberNameLost.Select(result => result.Message), Has.Some.Contains("lost its memberName (#424)")); Assert.That(memberNameLost.Select(result => result.Message), Has.None.Contains("holds empty references")); Assert.That(emptyReference.Select(result => result.Message), Has.Some.Contains($"Dependency {dependency.Id} holds empty references (#424)")); + Assert.That(concurrentFailures.Single(result => result.Message.Contains(model.Nested.Id.ToString()) && result.Message.Contains("threw")).Status, Is.EqualTo(AssertionStatus.Failed), "a breaking response of a concurrent read excuses nothing"); + Assert.That(concurrentFailures.Single(result => result.Message.Contains(model.Root.Id.ToString()) && result.Message.Contains("threw")).Status, Is.EqualTo(AssertionStatus.Warning), "its own breaking response excuses a read"); + Assert.That(maximumInFlight, Is.InRange(2, 4), "the reads run concurrently, at most four at a time"); Assert.That(unchangedListedDifferently.Select(result => result.Message), Is.EqualTo((string[])[$"Package {model.Nested.Id} as listed differs from what was sent: Element.DeclaredName"])); Assert.That(listUnreadableResults.Select(result => result.Message), Is.EqualTo((string[])["GetElementsByProjectCommitAsync threw InvalidOperationException: no list"])); Assert.That(recordedWithoutList, Is.EquivalentTo(elements.Select(element => (IData)readBack[element.Id])).Using((actual, expected) => ReferenceEquals(actual, expected)), "without the list, the elements read by id are recorded"); diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index 025d1cbf2..34454f75c 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -137,13 +137,13 @@ references it by that `$id`. the `DataVersionRequest`s for the commit. - **One builder holds the whole model.** Each step starts its own scope (`BeginStep`) and wires into the elements of earlier steps, through the `StepModel` base class (`Helpers/Models/`). A commit - sends only the delta: the elements that are new, or whose DTO differs from the previous commit + sends only the delta against the head of its branch: the elements that are new, or whose DTO differs from the previous commit under `ComparerProvider` (`ModelBuilder.Changed`); every check runs against the whole model. - **Derived values that cannot be computed.** Without the model library, an operator expression has no instantiated type, and the generated `ToDto(true)` dereferences it. Such an element is converted without derived values and listed in `ModelBuilder.WithoutDerivedValues`; derived values are never sent, so the payload is unaffected. The Kernel fixture pins that list to the five - operator expressions. + operator expressions, and the behaviour fixture to the three trigger invocations of step 7. - Why POCOs: a DTO cannot hold the value of a non-derived member that a derived property redefines (`OwningMembership.memberElement`, `Import.source`, … — 173 no-op setters in 90 DTO classes), so a hand-built DTO would send the empty GUID for it. Only the POCO conversion fills those values. @@ -176,11 +176,12 @@ After each commit: - `PostCommitByProjectAsync` returned a commit on the expected branch whose `previousCommits` is the previous head; the branch `head` moved (`GetBranchesByProjectAndIdAsync`). - `GetChangesByProjectCommitAsync` / `GetChangeByProjectCommitIdAsync` → exactly the sent - `DataVersion`s: one per element, its payload equal to the element sent. + `DataVersion`s: one per element, its payload equal to the element sent; a commit that changes + more than a page of elements must be read over several pages. - `GetElementByProjectCommitIdAsync` for each element the commit created or changed → equal to the expected DTO under `ComparerProvider`. An unchanged element was read by id at the commit that last changed it; its content is compared as listed instead, which keeps a step on a large model - fast. + fast. Reads by id run four at a time; a read that fails is excused only by its own response. - `GetElementsByProjectCommitAsync`, paged (`page[size]=10`, following `Link` to the end, so that every step's model spans several pages) → exactly the expected id set at that commit, no duplicates, and every element equal to the expected DTO. @@ -239,6 +240,15 @@ a step ignores itself only when the state it builds on is missing. The verdict a | 13 | **Tear down** | delete tag (13), branch (9), the `Library` project and the main project (5); each is unreadable afterwards; negative cases (§6.3) | 13, 9, 5, 3, 8, 12 | | 14 | **Coverage verdict** | — | asserts §7 | +Steps 6 and 7 follow the metamodel where the grammar differs from it (`ConjugatedPortTyping` has +no `originalPortDefinition`). `validateSubjectMembershipOwningType` and +`validateObjectiveMembershipOwningType` test the owning type with `oclIsType`, which, read +literally, admits only the exact metaclass; the OCL admits a second reading (any kind of it), so +step 7 declares the subject and objective on a `RequirementDefinition` and a `CaseDefinition` and +lets the other definitions inherit them by specialization, which satisfies both. Step 8 checks the +two conflicting commits in the same scope as the merges, so a red read-back does not hide the +merge. + Step numbers are fixed in Appendix A.1, which assigns every concrete metaclass to the step that creates it. @@ -325,11 +335,15 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen - `ElementsWithoutDerivedProperties`: elements come back without their derived properties (`owner`, `qualifiedName`, …), which the response schemas require; it matches only when every missing property is derived, so a missing non-derived property still fails (step 2); -- `DatatypeIdNotUri`: a datatype comes back with an `$id` that is not a URI (step 1). +- `DatatypeIdNotUri`: a datatype comes back with an `$id` that is not a URI (step 1); +- `DiffNotImplemented`: diff answers 501 Not Implemented (step 5); +- `MergeNotImplemented`: merge answers 501 Not Implemented (step 8); +- `MergeRequiresArrayBody`: merge reads its optional body as a required array, so a merge without + a body answers 500 and one with a `null` body 400, before the 501 (step 8). Step 8 then sends + the resolution merge, whose body is an array, and stops at its 501. Expected from the Flexo source, added with the step that observes them: -- merge answers 501 Not Implemented (step 8); - real values come back as single-precision floats (step 4); 2.5 and 3.5 are exact in single precision, so this is not observed yet; - deleting an element leaves the elements it owns in place (no cascade, §6.2 D3, step 12). @@ -339,12 +353,15 @@ Client defects found so far, each red until fixed: - #424 — the JSON round trip loses non-derived members that a derived property redefines (`memberElement`, `memberName`, `source`, `target`); - #425 — the PSM JSON serializers write `null` for optional references that the OpenAPI document - does not make nullable (`ProjectRequest.defaultBranch`, …). + does not make nullable (`ProjectRequest.defaultBranch`, …); +- #429 — `MergeAsync` sends its resolution elements without the derived properties that the + `Data` schema of the merge body requires (step 8). SDK defects found while building the fixture, outside the client: - #426 — the generated comparers treat equal floating-point values as different, so a - `LiteralRational` read back equal is reported as differing (step 4); + `LiteralRational` read back equal is reported as differing (step 4); from step 6 on it also puts + that literal in the delta, so the changes of a commit miss one expected element; - #427 — `AssignOwnership` duplicates the member when an owning membership is re-assigned, and the public API cannot reorder or shrink an ownership list or let any relationship other than an owning membership or an annotation own a related element. Step 3 therefore makes the feature diff --git a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs index 6573a81e1..660364225 100644 --- a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs +++ b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs @@ -67,6 +67,10 @@ public class FlexoModelScenarioTestFixture private KerMLUpdateModel kermlUpdateModel; + private SystemsStructureModel structureModel; + + private SystemsBehaviorModel behaviorModel; + [OneTimeSetUp] public async Task OneTimeSetUp() { @@ -253,6 +257,150 @@ public async Task VerifyKerMLUpdate() [Test] [DependsOnTest(nameof(VerifyKerMLUpdate), AllowFailure = true)] + public async Task VerifySystemsStructure() + { + if (this.rootModel == null || this.state.HeadCommitId == null) + { + Assert.Ignore("the default branch has no commit to branch from"); + } + + var projectId = this.state.ProjectId!.Value; + var head = this.state.HeadCommitId.Value; + + var branch = await this.client.PostBranchByProjectAsync(projectId, new BranchRequest { Name = "systems", Description = "The SysML model of steps 6 and 7", Head = head }); + this.state.BranchIds["systems"] = branch.Id; + this.state.BranchHeads[branch.Id] = head; + + var branchById = await this.client.GetBranchesByProjectAndIdAsync(projectId, branch.Id); + var (branches, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetBranchesByProjectAsync(projectId, parameters)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(branch.Name, Is.EqualTo("systems")); + Assert.That(branch.Head, Is.EqualTo(head)); + Assert.That(branch.OwningProject, Is.EqualTo(projectId)); + Assert.That(branchById.Id, Is.EqualTo(branch.Id)); + Assert.That(branches.Select(record => record.Id), Is.EquivalentTo((Guid[])[this.state.DefaultBranchId!.Value, branch.Id])); + + await this.ExpectNotFoundAsync(() => this.client.GetBranchesByProjectAsync(Guid.NewGuid()), KnownServerDivergences.UnknownResourceNotFound); + } + + this.structureModel = new SystemsStructureModel(this.rootModel); + + var committed = await this.CommitModelAsync(this.structureModel.Builder, "SysML structure", branch.Id); + + await this.VerifyCommittedModelAsync(committed, this.structureModel.Part.Id); + } + + [Test] + [DependsOnTest(nameof(VerifySystemsStructure), AllowFailure = true)] + public async Task VerifySystemsBehavior() + { + if (this.structureModel == null || !this.state.BranchIds.ContainsKey("systems")) + { + Assert.Ignore("step 6 built no structure on the systems branch"); + } + + var branchId = this.state.BranchIds["systems"]; + + this.behaviorModel = new SystemsBehaviorModel(this.rootModel, this.structureModel); + + var committed = await this.CommitModelAsync(this.behaviorModel.Builder, "SysML behaviour", branchId); + + await this.VerifyCommittedModelAsync(committed, this.behaviorModel.ActionDefinition.Id); + } + + [Test] + [DependsOnTest(nameof(VerifySystemsBehavior), AllowFailure = true)] + public async Task VerifyMerge() + { + if (this.behaviorModel == null || this.state.HeadCommitId == null || !this.state.BranchIds.ContainsKey("systems")) + { + Assert.Ignore("step 7 built no model on the systems branch to merge"); + } + + using (Assert.EnterMultipleScope()) + { + var systems = this.state.BranchIds["systems"]; + + var projectId = this.state.ProjectId!.Value; + var defaultBranch = this.state.DefaultBranchId!.Value; + var defaultModel = this.state.ExpectedModels[this.state.HeadCommitId.Value]; + + var onDefault = ModelBuilder.Copy(defaultModel.Single(element => element.Id == this.rootModel.Root.Id)); + onDefault.DeclaredName = "CoverageModel, changed on the default branch"; + var defaultChange = await this.CommitElementsAsync(Replace(defaultModel, onDefault), [onDefault], "A conflicting change on the default branch", defaultBranch); + + this.rootModel.Root.DeclaredName = "CoverageModel, changed on systems"; + var systemsChange = await this.CommitModelAsync(this.behaviorModel.Builder, "A conflicting change on systems", systems); + + await this.readBack.VerifyCommitAsync(defaultChange.Commit, defaultBranch, defaultChange.PreviousHead, defaultChange.Changed); + await this.readBack.VerifyCommitAsync(systemsChange.Commit, systems, systemsChange.PreviousHead, systemsChange.Changed); + + MergeConflictException conflict = null; + var rejectedWithoutBody = false; + + try + { + await this.client.MergeAsync(projectId, [systemsChange.Commit.Id], defaultBranch, description: "Merge systems"); + } + catch (MergeConflictException exception) + { + conflict = exception; + } + catch (PsmApiException exception) when (exception.StatusCode == HttpStatusCode.NotImplemented) + { + KnownServerDivergences.Report(KnownServerDivergences.MergeNotImplemented, $"MergeAsync of {systemsChange.Commit.Id} into the default branch answered 501"); + return; + } + catch (PsmApiException exception) when (exception.StatusCode == HttpStatusCode.InternalServerError) + { + KnownServerDivergences.Report(KnownServerDivergences.MergeRequiresArrayBody, $"MergeAsync of {systemsChange.Commit.Id} without a body answered 500"); + rejectedWithoutBody = true; + } + + if (!rejectedWithoutBody) + { + Assert.That(conflict?.Conflicts.Select(identity => identity.Id), Does.Contain(this.rootModel.Root.Id), "merging changes of the same element on both branches reports the conflict"); + } + + var resolution = ModelBuilder.Copy(systemsChange.Model.Single(element => element.Id == this.rootModel.Root.Id)); + resolution.DeclaredName = "CoverageModel, resolved"; + + Commit resolved; + + try + { + resolved = await this.client.MergeAsync(projectId, [systemsChange.Commit.Id], defaultBranch, [resolution], "Merge systems with a resolution"); + } + catch (PsmApiException exception) when (exception.StatusCode == HttpStatusCode.NotImplemented) + { + KnownServerDivergences.Report(KnownServerDivergences.MergeNotImplemented, $"MergeAsync of {systemsChange.Commit.Id} with a resolution into the default branch answered 501"); + return; + } + + var resolvedModel = Replace(systemsChange.Model, resolution); + this.state.ExpectedModels[resolved.Id] = resolvedModel; + this.state.BranchHeads[defaultBranch] = resolved.Id; + + Assert.That(resolved.PreviousCommit, Is.EquivalentTo((Guid[])[defaultChange.Commit.Id, systemsChange.Commit.Id])); + await this.readBack.VerifyModelAsync(resolved.Id, resolvedModel, [resolution], this.rootModel.Root.Id); + + this.behaviorModel.Package.DeclaredName = "Behaviour, changed on systems"; + var systemsOnly = await this.CommitModelAsync(this.behaviorModel.Builder, "A change on systems only", systems); + + var clean = await this.client.MergeAsync(projectId, [systemsOnly.Commit.Id], defaultBranch, description: "Merge systems without conflict"); + var cleanModel = Replace(systemsOnly.Model, resolution); + this.state.ExpectedModels[clean.Id] = cleanModel; + this.state.BranchHeads[defaultBranch] = clean.Id; + + Assert.That(clean.PreviousCommit, Is.EquivalentTo((Guid[])[resolved.Id, systemsOnly.Commit.Id])); + await this.readBack.VerifyModelAsync(clean.Id, cleanModel, systemsOnly.Changed, this.rootModel.Root.Id); + } + } + + [Test] + [DependsOnTest(nameof(VerifyMerge), AllowFailure = true)] public async Task VerifyCoverage() { var verdict = new CoverageVerdict(this.state.ReadBack, this.httpClientFactory.Recorder.Calls, this.openApi); @@ -282,19 +430,27 @@ private static async Task ExpectClientErrorAsync(Func call, [CallerArgumen await Assert.ThatAsync(() => call(), Throws.InstanceOf().With.Property(nameof(PsmApiException.StatusCode)).Matches(status => (int)status is >= 400 and < 500), description); } - private async Task<(Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead)> CommitModelAsync(ModelBuilder builder, string description) + private static IReadOnlyList Replace(IReadOnlyList model, IElement replacement) => [.. model.Select(element => element.Id == replacement.Id ? replacement : element)]; + + private async Task<(Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead, Guid BranchId)> CommitElementsAsync(IReadOnlyList model, IReadOnlyList changed, string description, Guid branch) { - var previousHead = this.state.HeadCommitId; - IReadOnlyList previous = previousHead is { } head ? this.state.ExpectedModels[head] : []; - var model = builder.ToDtos(); - var changed = ModelBuilder.Changed(previous, model); + Guid? previousHead = this.state.BranchHeads.TryGetValue(branch, out var head) ? head : null; - var commit = await this.client.PostCommitByProjectAsync(this.state.ProjectId!.Value, ModelBuilder.ToCommitRequest(changed, description), this.state.DefaultBranchId); + var commit = await this.client.PostCommitByProjectAsync(this.state.ProjectId!.Value, ModelBuilder.ToCommitRequest(changed, description), branch); - this.state.HeadCommitId = commit.Id; + this.state.BranchHeads[branch] = commit.Id; this.state.ExpectedModels[commit.Id] = model; - return (commit, model, changed, previousHead); + return (commit, model, changed, previousHead, branch); + } + + private Task<(Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead, Guid BranchId)> CommitModelAsync(ModelBuilder builder, string description, Guid? branchId = null) + { + var branch = branchId ?? this.state.DefaultBranchId!.Value; + IReadOnlyList previous = this.state.BranchHeads.TryGetValue(branch, out var head) ? this.state.ExpectedModels[head] : []; + var model = builder.ToDtos(); + + return this.CommitElementsAsync(model, ModelBuilder.Changed(previous, model), description, branch); } private Task ExpectNotFoundAsync(Func call, ServerDivergence tolerated = null, [CallerArgumentExpression(nameof(call))] string description = null) @@ -302,13 +458,13 @@ private Task ExpectNotFoundAsync(Func call, ServerDivergence tolerated = n return KnownServerDivergences.ExpectNotFoundAsync(call, () => this.httpClientFactory.Recorder.LastCall, tolerated, description); } - private async Task VerifyCommittedModelAsync((Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead) committed, Guid relationshipSubjectId) + private async Task VerifyCommittedModelAsync((Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead, Guid BranchId) committed, Guid relationshipSubjectId) { using (Assert.EnterMultipleScope()) { Assert.That(this.httpClientFactory.Recorder.EmptyGuidRequests, Is.Empty, "a request referenced the empty GUID"); - await this.readBack.VerifyCommitAsync(committed.Commit, this.state.DefaultBranchId!.Value, committed.PreviousHead, committed.Changed); + await this.readBack.VerifyCommitAsync(committed.Commit, committed.BranchId, committed.PreviousHead, committed.Changed); await this.readBack.VerifyModelAsync(committed.Commit.Id, committed.Model, committed.Changed, relationshipSubjectId); if (committed.PreviousHead is { } previousHead) diff --git a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md index ed4a6f0ba..2c803adbf 100644 --- a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md +++ b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md @@ -26,7 +26,9 @@ SySML2.NET.REST.Tests/ │ ├── RootModel.cs step 2: KerML Root and Packages │ ├── CoreModel.cs step 3: KerML Core │ ├── KernelModel.cs step 4: KerML Kernel -│ └── KerMLUpdateModel.cs step 5: updates U1–U4 of steps 2–4 +│ ├── KerMLUpdateModel.cs step 5: updates U1–U4 of steps 2–4 +│ ├── SystemsStructureModel.cs step 6: SysML structure, on the branch systems +│ └── SystemsBehaviorModel.cs step 7: SysML behaviour, requirements, cases and views ├── HelpersTests/ offline: one fixture per helper, mirroring Helpers/ │ ├── FlexoJwtTestFixture.cs, ModelBuilderTestFixture.cs, … │ └── Models/ one fixture per model class @@ -97,16 +99,16 @@ Session → PsmApiClient → HttpClient | Type | Responsibility | |---|---| -| `ModelBuilder` | Holds the whole model across the steps: each step starts its own scope (`BeginStep`) and creates POCOs with deterministic ids, wired with `AssignOwnership`. It converts them with the Dal's `ToDto(includeDerivedProperties: true)`, `Changed` selects the delta a commit sends, and `Find` looks an element up by its scoped name. An element whose derived values cannot be computed without the model library is converted without them and listed in `WithoutDerivedValues`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | +| `ModelBuilder` | Holds the whole model across the steps: each step starts its own scope (`BeginStep`) and creates POCOs with deterministic ids, wired with `AssignOwnership`. It converts them with the Dal's `ToDto(includeDerivedProperties: true)`, `Changed` selects the delta a commit sends, `Copy` copies a DTO for a change outside the builder, and `Find` looks an element up by its scoped name. An element whose derived values cannot be computed without the model library is converted without them and listed in `WithoutDerivedValues`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | | `DeterministicGuid` | Name-based UUID v5 of `"/"`, so the elements have the same ids in every run. | -| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5). | +| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5), `SystemsStructureModel` (step 6), `SystemsBehaviorModel` (step 7). The base class holds the helpers the steps share: naming, ownership, features, parameters, results, literals and multiplicities. | ### 5. Checking what came back | Type | Responsibility | |---|---| -| `ScenarioState` | What the steps hand on to each other: the ids the server assigned (project, branch, commits), the expected model at each commit, and everything the server returned. | -| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Every read is guarded: a read that throws fails, or warns when the response it failed on breaks the OpenAPI document. | +| `ScenarioState` | What the steps hand on to each other: the ids the server assigned (project, branches, commits), the head of every branch the scenario committed on, the expected model at each commit, and everything the server returned. | +| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Reads by id run four at a time. Every read is guarded: a read that throws fails, or warns when its own response shows a known divergence that breaks deserialization. | | `KnownServerDivergences`, `ServerDivergence` | The named ways Flexo diverges from the specification, each with a reference: an upstream issue, or a Flexo source location at the pinned commit. A divergence can explain response violations. `Report` raises an `Assert.Warn`. `ExpectNotFoundAsync` expects a 404, tolerates one named divergence, and fails when a conforming 404 reaches the caller without its `Error`. | | `IsolatedAssertions` | Runs a check in an isolated NUnit context and returns its failures and warnings, without failing the calling test. The offline fixtures use it to prove that a check fails when it should. | @@ -127,6 +129,7 @@ Session → PsmApiClient → HttpClient - The last test, `VerifyCoverage`, always runs and prints the coverage verdict. It stays red until the scenario covers everything. - `[OneTimeTearDown]` closes the session and disposes the handler chain and the containers. - Starting the host has a 15-minute timeout. +- Steps 1–8 take about 75 minutes, most of it waiting for Flexo, whose answers slow down as the model grows; steps 6 and 7 take about an hour together. Having one `[Test]` per step goes against the one-test-per-method rule in `TESTING.md`. This is accepted for this scenario only (see plan §9). @@ -137,7 +140,10 @@ Having one `[Test]` per step goes against the one-test-per-method rule in `TESTI | 3 | `VerifyKerMLCore` | implemented | | 4 | `VerifyKerMLKernel` | implemented, with the tag `kernel` | | 5 | `VerifyKerMLUpdate` | implemented, with the diff from the tag `kernel` | -| 6–13 | see plan §5 | planned | +| 6 | `VerifySystemsStructure` | implemented, on the branch `systems` | +| 7 | `VerifySystemsBehavior` | implemented, on the branch `systems` | +| 8 | `VerifyMerge` | implemented: a conflict, its resolution, and a clean merge into the default branch | +| 9–13 | see plan §5 | planned | | 14 | `VerifyCoverage` | implemented, red by design | ### Reading the outcome From c3a9f7162cf6ac6a4d935f321f8130de2cfc149f Mon Sep 17 00:00:00 2001 From: samatstarion Date: Sun, 8 Nov 2026 09:43:03 +0100 Subject: [PATCH 06/11] [Update] Flexo integration scenario: read lists in large pages, check paging on a short walk, read one element per metaclass by id; full run from 80 to 7 minutes (#407) --- .../Helpers/ReadBackAssertions.cs | 153 +++++++++++++----- .../ReadBackAssertionsTestFixture.cs | 88 ++++++---- .../INTEGRATION_TEST_PLAN.md | 27 ++-- .../TEST_PROJECT_STRUCTURE.md | 4 +- 4 files changed, 192 insertions(+), 80 deletions(-) diff --git a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs index 6a1e533c2..f18ced593 100644 --- a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs +++ b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs @@ -37,9 +37,19 @@ namespace SySML2.NET.REST.Tests.Helpers public sealed class ReadBackAssertions { /// - /// The page size used to read lists, small enough that a step's model spans several pages + /// The page size used to read a whole list /// - private const int PageSize = 10; + private const int ListPageSize = 100; + + /// + /// The page size of the paging walk, small enough that a step's model spans several pages + /// + private const int PagingPageSize = 10; + + /// + /// The number of pages the paging walk reads + /// + private const int PagingWalkPages = 3; /// /// The maximum number of pages read from one list, guarding against a server that never ends a list @@ -112,29 +122,9 @@ public ReadBackAssertions(IPsmApiClient client, ScenarioState state, Func public static async Task<(IReadOnlyList Records, int Pages)> ReadAllPagesAsync(Func>> readPage) { - var records = new List(); - var cursors = new HashSet(); - var parameters = new QueryParameters { PageSize = PageSize }; - - for (var pages = 1; pages <= MaximumPages; pages++) - { - var page = await readPage(parameters); - records.AddRange(page.Records); - - if (page.Next == null) - { - return (records, pages); - } - - if (!cursors.Add(page.Next.Value.Token)) - { - throw new InvalidOperationException($"The server repeated the page cursor {page.Next.Value.Token} after {pages} pages"); - } - - parameters = new QueryParameters { PageSize = PageSize, PageAfter = page.Next }; - } + var (records, pages, ended) = await ReadPagesAsync(readPage, ListPageSize, MaximumPages); - throw new InvalidOperationException($"The list did not end within {MaximumPages} pages"); + return ended ? (records, pages) : throw new InvalidOperationException($"The list did not end within {MaximumPages} pages"); } /// @@ -194,7 +184,7 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous } Assert.That(changes.Select(change => change.Identity.Id), Is.EquivalentTo(changed.Select(element => element.Id))); - if (changed.Count > PageSize) + if (changed.Count > ListPageSize) { Assert.That(changePages, Is.GreaterThan(1), "the changes did not span several pages, so paging is untested"); } @@ -312,11 +302,12 @@ public async Task VerifyHistoryAsync(Guid earlierCommitId, IElement expected) /// /// Verifies the model at a commit through every element read operation, recording what the server returned: - /// the elements the commit changed are read by id, and every element is compared as listed + /// one changed element of each metaclass is read by id, every element is compared as listed, and the first + /// pages of the list are read in small pages /// /// - /// An element that the commit did not change was read by id at the commit that last changed it; reading it - /// by id again would repeat that check against a growing model, so its content is compared in the list. + /// The list already compares every element, so one read by id per metaclass covers that operation for every + /// metaclass the commit changed; the membership checks still cover every changed element. /// /// /// The commit to read the model at @@ -337,11 +328,12 @@ public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expect { var projectId = this.state.ProjectId!.Value; var readById = new Dictionary(); + var sample = changed.GroupBy(element => element.GetType()).Select(metaclass => metaclass.First()).ToList(); using (Assert.EnterMultipleScope()) { var byId = await this.ReadManyAsync( - changed, + sample, element => this.client.GetElementByProjectCommitIdAsync(projectId, commitId, element.Id), element => $"GetElementByProjectCommitIdAsync of {element.GetType().Name} {element.Id}", (element, call) => call.RequestLine.Contains(element.Id.ToString(), StringComparison.OrdinalIgnoreCase)); @@ -351,23 +343,20 @@ public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expect readById[element.Id] = actual; } - var read = changed.Where(element => readById.ContainsKey(element.Id)).ToList(); - - foreach (var element in read) + foreach (var element in sample.Where(element => readById.ContainsKey(element.Id))) { VerifySame(element, readById[element.Id], $"{element.GetType().Name} {element.Id}"); } - var (listed, listPages) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetElementsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)), "GetElementsByProjectCommitAsync"); + var (listed, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetElementsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)), "GetElementsByProjectCommitAsync"); this.state.ReadBack.AddRange((listed ?? [.. readById.Values]).Select(element => (commitId, (IData)element))); + var listedById = (listed ?? []).GroupBy(element => element.Id).ToDictionary(group => group.Key, group => group.First()); + if (listed != null) { Assert.That(listed.Select(element => element.Id), Is.EquivalentTo(expected.Select(element => element.Id))); - Assert.That(listPages, Is.GreaterThan(1), "the elements did not span several pages, so paging is untested"); - - var listedById = listed.GroupBy(element => element.Id).ToDictionary(group => group.Key, group => group.First()); foreach (var element in expected.Where(element => !readById.ContainsKey(element.Id) && listedById.ContainsKey(element.Id))) { @@ -375,6 +364,8 @@ public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expect } } + await this.VerifyPagingAsync(commitId, expected); + var (roots, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetRootsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)), "GetRootsByProjectCommitAsync"); if (roots != null) @@ -382,13 +373,66 @@ public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expect VerifyRoots(roots, expected); } - VerifyMemberships(read, readById); - VerifyNoEmptyReferences(readById.Values); + var readBack = changed + .Select(element => readById.GetValueOrDefault(element.Id) ?? listedById.GetValueOrDefault(element.Id)) + .Where(element => element != null) + .ToDictionary(element => element.Id); + + VerifyMemberships([.. changed.Where(element => readBack.ContainsKey(element.Id))], readBack); + VerifyNoEmptyReferences(readBack.Values); await this.VerifyRelationshipsAsync(commitId, expected, relationshipSubjectId); } } + /// + /// Reads pages of a list operation, following , up to a number of pages + /// + /// + /// The type of the records + /// + /// + /// Reads one page for the given + /// + /// + /// The page size to request + /// + /// + /// The number of pages after which reading stops + /// + /// + /// The records of the pages read, in order, the number of pages read, and whether the list ended + /// + /// + /// Thrown when the server repeats a page cursor + /// + private static async Task<(IReadOnlyList Records, int Pages, bool Ended)> ReadPagesAsync(Func>> readPage, int pageSize, int pageLimit) + { + var records = new List(); + var cursors = new HashSet(); + var parameters = new QueryParameters { PageSize = pageSize }; + + for (var pages = 1; pages <= pageLimit; pages++) + { + var page = await readPage(parameters); + records.AddRange(page.Records); + + if (page.Next == null) + { + return (records, pages, true); + } + + if (!cursors.Add(page.Next.Value.Token)) + { + throw new InvalidOperationException($"The server repeated the page cursor {page.Next.Value.Token} after {pages} pages"); + } + + parameters = new QueryParameters { PageSize = pageSize, PageAfter = page.Next }; + } + + return (records, pageLimit, false); + } + /// /// Verifies that every membership read back names the member element and member name that were sent, /// which the generated comparers do not compare @@ -645,6 +689,39 @@ private void ReportFailedRead(string description, Exception exception, IEnumerab } } + /// + /// Verifies paging on the first small pages of the element list: the model spans + /// several pages, and the pages read hold distinct elements of the model + /// + /// + /// The commit to read at + /// + /// + /// The complete model expected at + /// + /// + /// An awaitable + /// + private async Task VerifyPagingAsync(Guid commitId, IReadOnlyList expected) + { + var projectId = this.state.ProjectId!.Value; + var (walked, pages, _) = await this.ReadAsync(() => ReadPagesAsync(parameters => this.client.GetElementsByProjectCommitAsync(projectId, commitId, queryParameters: parameters), PagingPageSize, PagingWalkPages), "GetElementsByProjectCommitAsync in small pages"); + + if (walked == null) + { + return; + } + + var expectedIds = expected.Select(element => element.Id).ToHashSet(); + + if (expected.Count > PagingPageSize) + { + Assert.That(pages, Is.GreaterThan(1), "the elements did not span several pages, so paging is untested"); + } + + Assert.That(walked.Select(element => element.Id), Is.Unique.And.All.Matches(expectedIds.Contains), "the pages hold distinct elements of the model"); + } + /// /// Verifies the relationships of an element in each direction against the sources and targets that were sent /// diff --git a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs index 2fb146811..429d60ea6 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs @@ -87,7 +87,7 @@ public async Task VerifyReadAllPagesAsync() Assert.That(requests[0].PageAfter, Is.Null); Assert.That(requests[1].PageAfter?.Token, Is.EqualTo("cursor-1")); Assert.That(requests[2].PageAfter?.Token, Is.EqualTo("cursor-2")); - Assert.That(requests.TrueForAll(parameters => parameters.PageSize == 10), Is.True); + Assert.That(requests.TrueForAll(parameters => parameters.PageSize == 100), Is.True); Assert.That(single, Is.EqualTo((int[])[7])); Assert.That(singlePages, Is.EqualTo(1)); } @@ -104,7 +104,7 @@ public async Task VerifyVerifyCommitAsync() var branchId = Guid.NewGuid(); var previousId = Guid.NewGuid(); - List changed = [.. Enumerable.Range(0, 25).Select(index => new Package { Id = Guid.NewGuid(), DeclaredName = $"P{index}" })]; + List changed = [.. Enumerable.Range(0, 150).Select(index => new Package { Id = Guid.NewGuid(), DeclaredName = $"P{index}" })]; var changes = changed.Select(element => new DataVersion { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = element.Id }, Payload = Clone(element) }).ToList(); var commit = new Commit { Id = this.commitId, OwningProject = this.projectId }; List commits = [commit]; @@ -334,6 +334,8 @@ public async Task VerifyVerifyModelAsync() { var model = new RootModel(); var elements = model.Builder.ToDtos(); + List changed = [.. elements.OrderBy(element => element.Id != model.Nested.Id)]; + var space = elements.Single(element => element.GetType() == typeof(Namespace)); var relationships = elements.OfType().ToList(); var readBack = elements.ToDictionary(element => element.Id, Clone); var unowned = elements.Where(element => element.OwningRelationship == null).ToList(); @@ -378,79 +380,99 @@ public async Task VerifyVerifyModelAsync() }).ToList(), parameters)); var firstRead = elements.ToList(); - var identical = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var identical = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); var recorded = this.state.ReadBack.ToList(); + var readsById = this.client.Invocations.Count(invocation => invocation.Method.Name == nameof(IPsmApiClient.GetElementByProjectCommitIdAsync)); + var listPageSizes = this.client.Invocations.Where(invocation => invocation.Method.Name == nameof(IPsmApiClient.GetElementsByProjectCommitAsync)).Select(invocation => ((QueryParameters)invocation.Arguments[3]).PageSize).ToList(); + + var larger = new RootModel(); + _ = new CoreModel(larger); + var largerElements = larger.Builder.ToDtos(); + + foreach (var element in largerElements.Where(element => !readBack.ContainsKey(element.Id))) + { + readBack[element.Id] = Clone(element); + } + + listed = largerElements; + roots = [.. largerElements.Where(element => element.OwningRelationship == null)]; + this.client.Invocations.Clear(); + + var largerModel = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyModelAsync(this.commitId, largerElements, [], larger.Nested.Id)); + var walkPages = this.client.Invocations.Count(invocation => invocation.Method.Name == nameof(IPsmApiClient.GetElementsByProjectCommitAsync) && ((QueryParameters)invocation.Arguments[3]).PageSize == 10); + + listed = elements; roots = elements; - var everyElementRoot = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var everyElementRoot = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); roots = [.. elements.Where(element => element is not IRelationship { OwningRelatedElement: not null })]; - var notOwnedRelatedRoots = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var notOwnedRelatedRoots = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); roots = [.. elements.Where(element => element is not IRelationship)]; - var nonRelationshipRoots = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var nonRelationshipRoots = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); roots = [.. unowned.Where(element => element.Id != model.Root.Id)]; - var rootMissing = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var rootMissing = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); roots = [.. unowned, new Package { Id = Guid.NewGuid() }]; - var foreignRoot = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var foreignRoot = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); roots = unowned; var renamed = (Package)Clone(readBack[model.Nested.Id]); renamed.DeclaredName = "Changed"; readBack[model.Nested.Id] = renamed; - var elementChanged = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var elementChanged = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); readBack[model.Nested.Id] = new Namespace { Id = model.Nested.Id }; - var otherMetaclass = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var otherMetaclass = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); readBack[model.Nested.Id] = null; - var nothingRead = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var nothingRead = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); readBack[model.Nested.Id] = Clone(elements.Single(element => element.Id == model.Nested.Id)); listed = elements.Skip(1).ToList(); - var elementNotListed = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var elementNotListed = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); listed = [.. elements, elements[0]]; - var elementListedTwice = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var elementListedTwice = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); listed = elements; onePage = true; - var listOnOnePage = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var listOnOnePage = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); onePage = false; dropIncoming = true; - var incomingLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var incomingLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); dropIncoming = false; - var unrelatedSubject = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, Guid.NewGuid())); + var unrelatedSubject = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, Guid.NewGuid())); var alias = elements.Single(element => element.GetType() == typeof(Membership)); var lostMember = (Membership)Clone(alias); lostMember.MemberElement = Guid.Empty; readBack[alias.Id] = lostMember; - var memberElementLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var memberElementLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); var lostName = (Membership)Clone(alias); lostName.MemberName = null; readBack[alias.Id] = lostName; - var memberNameLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var memberNameLost = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); readBack[alias.Id] = Clone(alias); var dependency = elements.OfType().Single(); @@ -458,24 +480,24 @@ public async Task VerifyVerifyModelAsync() emptyClient.Client = [Guid.Empty]; readBack[dependency.Id] = emptyClient; - var emptyReference = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var emptyReference = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); readBack[dependency.Id] = Clone(dependency); unreadable.Add(model.Nested.Id); - var elementUnreadable = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var elementUnreadable = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); unreadable.Clear(); listUnreadable = true; var readBackBefore = this.state.ReadBack.Count; - var listUnreadableResults = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var listUnreadableResults = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); var recordedWithoutList = this.state.ReadBack.Skip(readBackBefore).Select(entry => entry.Data).ToList(); listUnreadable = false; unreadableDirection = Direction.@in; - var incomingUnreadable = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, model.Nested.Id)); + var incomingUnreadable = await IsolatedAssertions.RunAsync(this.VerifyModel(elements, changed, model.Nested.Id)); unreadableDirection = null; @@ -489,18 +511,23 @@ public async Task VerifyVerifyModelAsync() this.client.Verify(api => api.GetElementByProjectCommitIdAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never, "an element that the commit did not change is not read by id"); listed = elements; - unreadable.UnionWith([model.Nested.Id, model.Root.Id]); - breakingFor.Add(model.Root.Id); + unreadable.UnionWith([model.Nested.Id, space.Id]); + breakingFor.Add(space.Id); var recording = new ReadBackAssertions(this.client.Object, this.state, () => [.. recordedReads], [KnownServerDivergences.PreviousCommitAsObject with { Explains = (_, violation) => violation == breaking }]); Interlocked.Exchange(ref maximumInFlight, 0); - var concurrentFailures = await IsolatedAssertions.RunAsync(() => recording.VerifyModelAsync(this.commitId, elements, elements, model.Nested.Id)); + var concurrentFailures = await IsolatedAssertions.RunAsync(() => recording.VerifyModelAsync(this.commitId, elements, changed, model.Nested.Id)); unreadable.Clear(); using (Assert.EnterMultipleScope()) { Assert.That(identical, Is.Empty); + Assert.That(readsById, Is.EqualTo(elements.Select(element => element.GetType()).Distinct().Count()), "one changed element of each metaclass is read by id"); + Assert.That(listPageSizes, Is.EqualTo((int?[])[100, 10, 10, 10]), "the whole list in large pages, then the paging walk over the three small pages the model fills"); + Assert.That(largerElements, Has.Count.GreaterThan(30)); + Assert.That(largerModel, Is.Empty); + Assert.That(walkPages, Is.EqualTo(3), "the paging walk stops after three small pages"); Assert.That(recorded.TrueForAll(entry => entry.CommitId == this.commitId), Is.True); Assert.That(recorded.Select(entry => entry.Data), Is.EqualTo(firstRead.Cast()).Using((actual, expected) => ReferenceEquals(actual, expected))); Assert.That(unowned, Has.Count.GreaterThan(1), "owned relationships have no owner, so they are roots"); @@ -514,7 +541,8 @@ public async Task VerifyVerifyModelAsync() Assert.That(otherMetaclass.Select(result => result.Message), Has.Some.Contains($"Package {model.Nested.Id} was read back as another metaclass")); Assert.That(nothingRead.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); Assert.That(elementNotListed, Has.Count.EqualTo(1)); - Assert.That(elementListedTwice, Has.Count.EqualTo(1)); + Assert.That(elementListedTwice, Has.Count.EqualTo(2), "the list and the paging walk, which reads all of this small model, both report the duplicate"); + Assert.That(elementListedTwice.Select(result => result.Message), Has.Some.Contains("the pages hold distinct elements of the model")); Assert.That(listOnOnePage, Has.Count.EqualTo(1)); Assert.That(listOnOnePage[0].Message, Does.Contain("the elements did not span several pages, so paging is untested")); Assert.That(incomingLost, Has.Count.EqualTo(1)); @@ -527,11 +555,11 @@ public async Task VerifyVerifyModelAsync() Assert.That(memberNameLost.Select(result => result.Message), Has.None.Contains("holds empty references")); Assert.That(emptyReference.Select(result => result.Message), Has.Some.Contains($"Dependency {dependency.Id} holds empty references (#424)")); Assert.That(concurrentFailures.Single(result => result.Message.Contains(model.Nested.Id.ToString()) && result.Message.Contains("threw")).Status, Is.EqualTo(AssertionStatus.Failed), "a breaking response of a concurrent read excuses nothing"); - Assert.That(concurrentFailures.Single(result => result.Message.Contains(model.Root.Id.ToString()) && result.Message.Contains("threw")).Status, Is.EqualTo(AssertionStatus.Warning), "its own breaking response excuses a read"); + Assert.That(concurrentFailures.Single(result => result.Message.Contains(space.Id.ToString()) && result.Message.Contains("threw")).Status, Is.EqualTo(AssertionStatus.Warning), "its own breaking response excuses a read"); Assert.That(maximumInFlight, Is.InRange(2, 4), "the reads run concurrently, at most four at a time"); Assert.That(unchangedListedDifferently.Select(result => result.Message), Is.EqualTo((string[])[$"Package {model.Nested.Id} as listed differs from what was sent: Element.DeclaredName"])); - Assert.That(listUnreadableResults.Select(result => result.Message), Is.EqualTo((string[])["GetElementsByProjectCommitAsync threw InvalidOperationException: no list"])); - Assert.That(recordedWithoutList, Is.EquivalentTo(elements.Select(element => (IData)readBack[element.Id])).Using((actual, expected) => ReferenceEquals(actual, expected)), "without the list, the elements read by id are recorded"); + Assert.That(listUnreadableResults.Select(result => result.Message), Is.EqualTo((string[])["GetElementsByProjectCommitAsync threw InvalidOperationException: no list", "GetElementsByProjectCommitAsync in small pages threw InvalidOperationException: no list"])); + Assert.That(recordedWithoutList, Is.EquivalentTo(changed.GroupBy(element => element.GetType()).Select(metaclass => (IData)readBack[metaclass.First().Id])).Using((actual, expected) => ReferenceEquals(actual, expected)), "without the list, the elements read by id are recorded"); Assert.That(incomingUnreadable.Select(result => result.Message), Is.EqualTo((string[])["GetRelationshipsByProjectCommitRelatedElementAsync in threw InvalidOperationException: no relationships"]), "the out and both directions still pass"); Assert.That(elementUnreadable.Select(result => result.Message), Is.EqualTo((string[])[$"GetElementByProjectCommitIdAsync of Package {model.Nested.Id} threw InvalidOperationException: not deserializable"])); } @@ -552,6 +580,6 @@ private static Task> Paged(IReadOnlyList records, QueryPara }); } - private Func VerifyModel(IReadOnlyList elements, Guid relationshipSubjectId) => () => this.assertions.VerifyModelAsync(this.commitId, elements, elements, relationshipSubjectId); + private Func VerifyModel(IReadOnlyList elements, IReadOnlyList changed, Guid relationshipSubjectId) => () => this.assertions.VerifyModelAsync(this.commitId, elements, changed, relationshipSubjectId); } } diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index 34454f75c..3e7b17746 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -177,14 +177,16 @@ After each commit: the previous head; the branch `head` moved (`GetBranchesByProjectAndIdAsync`). - `GetChangesByProjectCommitAsync` / `GetChangeByProjectCommitIdAsync` → exactly the sent `DataVersion`s: one per element, its payload equal to the element sent; a commit that changes - more than a page of elements must be read over several pages. -- `GetElementByProjectCommitIdAsync` for each element the commit created or changed → equal to the - expected DTO under `ComparerProvider`. An unchanged element was read by id at the commit that - last changed it; its content is compared as listed instead, which keeps a step on a large model - fast. Reads by id run four at a time; a read that fails is excused only by its own response. -- `GetElementsByProjectCommitAsync`, paged (`page[size]=10`, following `Link` to the end, so that - every step's model spans several pages) → exactly the expected id set at that commit, no - duplicates, and every element equal to the expected DTO. + more than a page of 100 elements must be read over several pages. +- `GetElementByProjectCommitIdAsync` for one element of each metaclass the commit created or + changed → equal to the expected DTO under `ComparerProvider`. Every other element is compared as + listed; the list already compares every element, so one read by id per metaclass covers the + operation for each. Reads by id run four at a time; a read that fails is excused only by its own + response. +- `GetElementsByProjectCommitAsync`, in pages of 100 following `Link` to the end → exactly the + expected id set at that commit, no duplicates, and every element equal to the expected DTO. + Paging itself is checked on the first three pages of 10 (`page[size]=10`, `page[after]` from + `Link`): the model spans several pages, and the pages hold distinct elements of the model. - `GetRootsByProjectCommitAsync` → exactly the elements without an `owner`. Systems Modeling API and Services, Clause 7.2.2, Table 2: "A root element is an element that does not have any other element as an owner. Hence, Element.owner is not specified for a root element." KerML derives `owner` as @@ -197,8 +199,9 @@ After each commit: - `GetRelationshipsByProjectCommitRelatedElementAsync`, `Direction` `in` / `out` / `both`, for the step's relationship ends. - History is immutable: one element of an earlier commit is re-read at that commit and is unchanged. -- Every `Membership` read back has the `memberElement` and `memberName` that were sent, and no - non-derived reference read back is the empty GUID. The comparers do not cover these members, and +- Every changed `Membership` read back, by id or as listed, has the `memberElement` and + `memberName` that were sent, and no non-derived reference of a changed element read back is the + empty GUID. The comparers do not cover these members, and the JSON round trip loses them today (#424), so these checks stay red until #424 is fixed. - No request body references the empty GUID. - A negative case expects 404 for an unknown resource where the OpenAPI document declares 404, and @@ -342,6 +345,10 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen a body answers 500 and one with a `null` body 400, before the 501 (step 8). Step 8 then sends the resolution merge, whose body is an array, and stops at its 501. +Not a divergence from the specification, but it sets the run time: layer1's requests to the quad +store slow down during a run, from a few milliseconds to hundreds, while the quad store stays fast +(Open-MBEE/flexo-mms-layer1-service#293). The scenario therefore keeps its call count low (§4.3). + Expected from the Flexo source, added with the step that observes them: - real values come back as single-precision floats (step 4); 2.5 and 3.5 are exact in single diff --git a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md index 2c803adbf..a9288f894 100644 --- a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md +++ b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md @@ -108,7 +108,7 @@ Session → PsmApiClient → HttpClient | Type | Responsibility | |---|---| | `ScenarioState` | What the steps hand on to each other: the ids the server assigned (project, branches, commits), the head of every branch the scenario committed on, the expected model at each commit, and everything the server returned. | -| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Reads by id run four at a time. Every read is guarded: a read that throws fails, or warns when its own response shows a known divergence that breaks deserialization. | +| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Lists are read in pages of 100, and paging is checked on the first three pages of 10. One changed element of each metaclass is read by id, four reads at a time. Every read is guarded: a read that throws fails, or warns when its own response shows a known divergence that breaks deserialization. | | `KnownServerDivergences`, `ServerDivergence` | The named ways Flexo diverges from the specification, each with a reference: an upstream issue, or a Flexo source location at the pinned commit. A divergence can explain response violations. `Report` raises an `Assert.Warn`. `ExpectNotFoundAsync` expects a 404, tolerates one named divergence, and fails when a conforming 404 reaches the caller without its `Error`. | | `IsolatedAssertions` | Runs a check in an isolated NUnit context and returns its failures and warnings, without failing the calling test. The offline fixtures use it to prove that a check fails when it should. | @@ -129,7 +129,7 @@ Session → PsmApiClient → HttpClient - The last test, `VerifyCoverage`, always runs and prints the coverage verdict. It stays red until the scenario covers everything. - `[OneTimeTearDown]` closes the session and disposes the handler chain and the containers. - Starting the host has a 15-minute timeout. -- Steps 1–8 take about 75 minutes, most of it waiting for Flexo, whose answers slow down as the model grows; steps 6 and 7 take about an hour together. +- Steps 1–8 take about 7 minutes and about 500 calls. Flexo slows down after several hundred requests (Open-MBEE/flexo-mms-layer1-service#293), so a check that adds many calls can lengthen the run far more than its own share. Having one `[Test]` per step goes against the one-test-per-method rule in `TESTING.md`. This is accepted for this scenario only (see plan §9). From 3d53b3d7b8b8e5f8135fcaebf920ac5f9909cf37 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Sun, 8 Nov 2026 15:27:52 +0100 Subject: [PATCH 07/11] =?UTF-8?q?[Add]=20Flexo=20integration=20scenario=20?= =?UTF-8?q?stage=204:=20queries,=20project=20usage=20and=20external=20data?= =?UTF-8?q?=20steps=209=E2=80=9311=20(#407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Helpers/KnownServerDivergences.cs | 64 +++- .../Helpers/Models/LibraryModel.cs | 47 +++ .../Helpers/Models/StepModel.cs | 17 + .../Helpers/Models/SystemsBehaviorModel.cs | 19 +- .../Helpers/Models/SystemsStructureModel.cs | 8 + .../Helpers/OpenApiContent.cs | 30 +- .../Helpers/ReadBackAssertions.cs | 307 ++++++++++++++++-- .../Helpers/ScenarioQueries.cs | 232 +++++++++++++ .../Helpers/ScenarioState.cs | 5 + .../KnownServerDivergencesTestFixture.cs | 78 ++++- .../Models/LibraryModelTestFixture.cs | 44 +++ .../Models/SystemsBehaviorModelTestFixture.cs | 30 ++ .../SystemsStructureModelTestFixture.cs | 18 + .../HelpersTests/OpenApiContentTestFixture.cs | 2 + .../ReadBackAssertionsTestFixture.cs | 253 +++++++++++++++ .../ScenarioQueriesTestFixture.cs | 190 +++++++++++ .../INTEGRATION_TEST_PLAN.md | 48 ++- .../FlexoModelScenarioTestFixture.cs | 174 ++++++++++ .../TEST_PROJECT_STRUCTURE.md | 15 +- 19 files changed, 1532 insertions(+), 49 deletions(-) create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/LibraryModel.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/ScenarioQueries.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/LibraryModelTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/ScenarioQueriesTestFixture.cs diff --git a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs index 7ff3a6cc7..e07f5d2b9 100644 --- a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs +++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs @@ -56,6 +56,21 @@ public static class KnownServerDivergences /// private static readonly Regex PreviousCommitObject = new(@"^\S*/previousCommit type: Value is ""object"" but should be ""array""$", RegexOptions.Compiled); + /// + /// Matches the schema error on an item of an element list whose @type is a kind of data that is no element + /// + private static readonly Regex DataItemInElementList = new(@"^/\d+/@type const: ""(ExternalData|ExternalRelationship|ProjectUsage)"" is none of the types the schema admits$", RegexOptions.Compiled); + + /// + /// The path templates of the operations that list elements + /// + private static readonly HashSet ElementListTemplates = ["/projects/{projectId}/commits/{commitId}/elements", "/projects/{projectId}/commits/{commitId}/roots"]; + + /// + /// The path templates of the operations that answer query results + /// + private static readonly HashSet QueryResultTemplates = ["/projects/{projectId}/queries/{queryId}/results", "/projects/{projectId}/query-results"]; + /// /// Gets the divergence that the roots are the elements without an owningRelatedElement, owned through /// an owningRelationship or not, where Clause 7.2.2 makes them the elements without an owner @@ -72,7 +87,7 @@ public static class KnownServerDivergences /// Gets the divergence that a request naming an unknown resource succeeds, where the OpenAPI document declares /// 404 Not Found for it /// - public static ServerDivergence UnknownResourceAccepted { get; } = new("a request naming an unknown resource succeeds instead of answering 404 Not Found", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/RelationshipApi.kt"); + public static ServerDivergence UnknownResourceAccepted { get; } = new("a request naming an unknown resource succeeds instead of answering 404 Not Found", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/RelationshipApi.kt, and QueryApi.kt, whose PUT creates a missing query"); /// /// Gets the divergence that an error answer carries an empty or plain-text body, where the OpenAPI document @@ -142,10 +157,55 @@ public static class KnownServerDivergences $"{FlexoRevision}, the meta datatypes route", (call, violation) => call.Operation?.PathTemplate == "/meta/datatypes/{datatypeId}" && violation.Message.StartsWith("/$id format:", StringComparison.Ordinal)); + /// + /// Gets the divergence that the element lists include project usages and external data, which are data but no + /// elements, where the OpenAPI document declares a list of elements + /// + public static ServerDivergence DataListedAsElements { get; } = new( + "the elements and roots of a commit include its project usages, external data and external relationships, which are no elements", + $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/ElementApi.kt, every stored subject is listed", + (call, violation) => call.Operation is { } operation && ElementListTemplates.Contains(operation.PathTemplate) && violation.Kind == ContractViolationKind.SchemaMismatch && DataItemInElementList.IsMatch(violation.Message), + BreaksDeserialization: true); + + /// + /// Gets the divergence that the project usage of an element is answered as an array of every project usage of + /// the commit, where the OpenAPI document declares the one project usage that brings the element in + /// + public static ServerDivergence ProjectUsageAsArray { get; } = new( + "GET /projects/{projectId}/commits/{commitId}/elements/{elementId}/projectUsage answers an array of every project usage of the commit, whatever the element, instead of one project usage", + $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/ElementApi.kt", + (call, violation) => call.Operation?.PathTemplate == "/projects/{projectId}/commits/{commitId}/elements/{elementId}/projectUsage" && violation.Message == "/ type: Value is \"array\" but should be \"object\"", + BreaksDeserialization: true); + + /// + /// Gets the divergence that query results keep only the properties the query selects, as Clause 7.1.4 says, where + /// the OpenAPI document declares complete data + /// + public static ServerDivergence QueryResultsProjected { get; } = new( + "query results keep only the properties in the select of the query, as Clause 7.1.4 says, leaving out @type and the other properties that the Data schema of the OpenAPI document requires", + $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/QueryApi.kt, which follows Clause 7.1.4 where the OpenAPI document, ranked first by Clause 2, declares complete Data", + (call, violation) => call.Operation is { } operation && QueryResultTemplates.Contains(operation.PathTemplate) && violation.Kind == ContractViolationKind.SchemaMismatch && MissingNames(violation) is { } names && names.Contains("@type"), + BreaksDeserialization: true); + + /// + /// Gets the divergence that a query is stored without its name, alias and description + /// + public static ServerDivergence QueryLosesNameAndDescription { get; } = new("a query is stored without its name, alias and description, which are lost on every later read", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/QueryApi.kt, createOrUpdateQuery"); + + /// + /// Gets the divergence that a primitive constraint with the instanceOf operator is rejected + /// + public static ServerDivergence InstanceOfRejected { get; } = new("a primitive constraint with the instanceOf operator is answered 400 Bad Request", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/QueryApi.kt, the operator is not read"); + + /// + /// Gets the divergence that the results of a query definition sent with GET are not implemented + /// + public static ServerDivergence QueryResultsGetNotImplemented { get; } = new("GET /projects/{projectId}/query-results answers 501 Not Implemented", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/QueryApi.kt"); + /// /// Gets every known divergence /// - public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, MergeNotImplemented, MergeRequiresArrayBody, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri]; + public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, MergeNotImplemented, MergeRequiresArrayBody, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri, DataListedAsElements, ProjectUsageAsArray, QueryResultsProjected, QueryLosesNameAndDescription, InstanceOfRejected, QueryResultsGetNotImplemented]; /// /// Asserts that a call for an unknown resource fails with 404 Not Found, or reports the one tolerated divergence diff --git a/SySML2.NET.REST.Tests/Helpers/Models/LibraryModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/LibraryModel.cs new file mode 100644 index 000000000..df459c3bc --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/LibraryModel.cs @@ -0,0 +1,47 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Dal; + + /// + /// The model of the second project of scenario step 10, which the main model uses through a project usage + /// + /// + /// + /// library package <lib> UsedLibrary { + /// package <usd> Used; + /// } + /// + /// + public sealed class LibraryModel : StepModel + { + /// + /// Initializes a new instance of the class and builds the model + /// + public LibraryModel() : base(new ModelBuilder("library"), "library") + { + this.Root = this.CreateNamed("UsedLibrary", "lib", LibraryPackageExtensions.ToDto); + this.Used = this.CreateNamed("Used", "usd", PackageExtensions.ToDto); + this.OwnMember(this.Root, this.Used); + } + + /// + /// Gets the root library package + /// + public LibraryPackage Root { get; } + + /// + /// Gets the package that the library package owns, the element whose project usage step 10 reads + /// + public Package Used { get; } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs index 0cc9613e5..596f46115 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/StepModel.cs @@ -236,6 +236,23 @@ protected void Result(IType owner, string name) this.Parameter(owner, $"{name}/result", FeatureDirectionKind.Out, ReturnParameterMembershipExtensions.ToDto); } + /// + /// Makes a feature specialize another through a + /// + /// + /// The subsetting feature + /// + /// + /// The subsetted feature + /// + protected void Subsets(IFeature feature, IFeature subsetted) + { + var subsetting = this.Builder.Create($"{feature.ElementId}/subsetting", SubsettingExtensions.ToDto); + subsetting.SubsettingFeature = feature; + subsetting.SubsettedFeature = subsetted; + feature.AssignOwnership(subsetting); + } + /// /// Types a feature with a /// diff --git a/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs index 23fc81efe..52ddc9c82 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs @@ -185,6 +185,13 @@ private void Actions(SystemsStructureModel structure) var level = this.Owned(structure.OccurrenceDefinition, "level", FeatureExtensions.ToDto); level.IsVariable = true; + var limit = this.Owned(structure.OccurrenceDefinition, "limit", FeatureExtensions.ToDto); + limit.IsVariable = true; + limit.IsConstant = true; + var initialValue = this.Builder.Create($"{limit.ElementId}/value", FeatureValueExtensions.ToDto); + initialValue.IsInitial = true; + limit.AssignOwnership(initialValue, this.Literal("limit/initial/0", LiteralIntegerExtensions.ToDto, literal => literal.Value = 0)); + var assign = this.Owned(this.ActionDefinition, "assign", AssignmentActionUsageExtensions.ToDto); this.Refer(assign, level); this.Value(this.Param(assign, "assign/target", ReferenceUsageExtensions.ToDto, ParameterMembershipExtensions.ToDto), this.Literal("assign/target/0", LiteralIntegerExtensions.ToDto, literal => literal.Value = 0)); @@ -536,7 +543,8 @@ private RequirementUsage Requirements(ConstraintDefinition constraint, SystemsSt /// /// Adds the state definition St with entry, do and exit subactions, two states and a transition between - /// them with a trigger, a guard and an effect, and a state usage that a part definition exhibits + /// them with a trigger, a guard and an effect, a state usage that a part definition exhibits, and a parallel state + /// definition and usage, whose substates have no transitions /// private void States() { @@ -599,6 +607,15 @@ private void States() var exhibit = this.Owned(this.Member("Exhibitor", PartDefinitionExtensions.ToDto), "exhibit", ExhibitStateUsageExtensions.ToDto); this.Subset(exhibit, exhibited); + + var parallel = this.Member("Par", StateDefinitionExtensions.ToDto); + parallel.IsParallel = true; + this.Owned(parallel, "pa1", StateUsageExtensions.ToDto); + this.Owned(parallel, "pa2", StateUsageExtensions.ToDto); + + var parallelUsage = this.Member("pu", StateUsageExtensions.ToDto); + parallelUsage.IsParallel = true; + this.Typed(parallelUsage, parallel); } /// diff --git a/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs index ba124ecee..cd6b113a7 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs @@ -42,6 +42,7 @@ namespace SySML2.NET.REST.Tests.Helpers.Models /// part def Q; attribute def A; occurrence def O; item def I { attribute content : A; } /// abstract enum def E { enum e1; enum e2; } /// abstract variation part def PV { variant part pv1 : PV; } + /// abstract variation part vu { variant part vu1 :> vu; } /// port def PD { attribute pa : A; } // owns ~PD through a port conjugation /// connection def CD { end ref cdA : P [1]; end ref cdB : P [1]; } /// interface def IF { end port ifA : PD [1]; end port ifB : ~PD [1]; } @@ -100,6 +101,13 @@ public sealed class SystemsStructureModel : StepModel variation.AssignOwnership(this.Builder.Create("PV/pv1/membership", VariantMembershipExtensions.ToDto), variant); this.Typed(variant, variation); + var variationUsage = this.Member("vu", PartUsageExtensions.ToDto); + variationUsage.IsVariation = true; + variationUsage.IsAbstract = true; + var variantUsage = this.CreateNamed("vu1", "vu1", PartUsageExtensions.ToDto); + variationUsage.AssignOwnership(this.Builder.Create("vu/vu1/membership", VariantMembershipExtensions.ToDto), variantUsage); + this.Subsets(variantUsage, variationUsage); + this.PortDefinition = this.Member("PD", PortDefinitionExtensions.ToDto); this.Owned(this.PortDefinition, "pa", AttributeUsageExtensions.ToDto, this.AttributeDefinition); diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs index 660545109..62a173760 100644 --- a/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiContent.cs @@ -299,7 +299,8 @@ private static IReadOnlyList Summarize(EvaluationResults results, string /// /// Checks the body against the member of the union for its @type, or for the @type of each of its - /// items + /// items, where an item of a @type that no member admits is a violation of its own, reported ahead of + /// the errors of the other items so that the limit on reported errors cannot hide it /// /// /// The body @@ -318,25 +319,38 @@ private IReadOnlyList CheckByType(JsonElement body) ? body.EnumerateArray().Select((item, index) => (Location: $"/{index}", Instance: item)).ToList() : [(Location: string.Empty, Instance: body)]; - var members = new List<(string Location, JsonElement Instance, JsonSchema Schema)>(); + var members = new List<(string Location, string UnknownType, JsonElement Instance, JsonSchema Schema)>(); foreach (var (location, instance) in instances) { if (instance.ValueKind != JsonValueKind.Object || !instance.TryGetProperty("@type", out var type) - || type.ValueKind != JsonValueKind.String - || !this.SchemasByType.TryGetValue(type.GetString()!, out var member)) + || type.ValueKind != JsonValueKind.String) { return null; } - members.Add((location, instance, member)); + var typeName = type.GetString()!; + + if (this.SchemasByType.TryGetValue(typeName, out var member)) + { + members.Add((location, null, instance, member)); + } + else if (this.IsArrayOfTypes) + { + members.Add((location, typeName, instance, null)); + } + else + { + return null; + } } return [.. members - .Select(entry => (entry.Location, Results: entry.Schema.Evaluate(entry.Instance, Evaluation))) - .Where(entry => !entry.Results.IsValid) - .SelectMany(entry => Summarize(entry.Results, entry.Location)) + .OrderBy(entry => entry.UnknownType == null) + .SelectMany(entry => entry.UnknownType != null + ? [$"{entry.Location}/@type const: \"{entry.UnknownType}\" is none of the types the schema admits"] + : entry.Schema.Evaluate(entry.Instance, Evaluation) is { IsValid: false } results ? Summarize(results, entry.Location) : []) .Take(ReportedErrors) .Select(error => new ContractViolation(ContractViolationKind.SchemaMismatch, error))]; } diff --git a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs index f18ced593..9c5d34a3b 100644 --- a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs +++ b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs @@ -13,6 +13,7 @@ namespace SySML2.NET.REST.Tests.Helpers using System.Collections.Generic; using System.Linq; using System.Net; + using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -127,6 +128,39 @@ public ReadBackAssertions(IPsmApiClient client, ScenarioState state, Func + /// Verifies a query read back against the request it was created or updated with: its project, select and + /// constraint, and its name, description and aliases, or the known divergence that the server lost all three + /// + /// + /// The query read back + /// + /// + /// The request the query was created or updated with + /// + /// + /// The project the query belongs to + /// + /// + /// The description of the query in assertion messages + /// + public static void VerifyQueryRecord(Query query, QueryRequest sent, Guid projectId, string description) + { + Assert.That(query.OwningProject, Is.EqualTo(projectId), $"{description} belongs to the project"); + Assert.That(query.Select, Is.EqualTo(sent.Select), $"{description} selects what was sent"); + Assert.That(ScenarioQueries.ConstraintText(query.Where), Is.EqualTo(ScenarioQueries.ConstraintText(sent.Where)), $"{description} has the constraint that was sent"); + + if (string.IsNullOrWhiteSpace(query.Name) && query.Description == null && query.Alias.Count == 0) + { + KnownServerDivergences.Report(KnownServerDivergences.QueryLosesNameAndDescription, $"{description} came back without the name \"{sent.Name}\""); + return; + } + + Assert.That(query.Name, Is.EqualTo(sent.Name), $"{description} has the name that was sent"); + Assert.That(query.Description, Is.EqualTo(sent.Description), $"{description} has the description that was sent"); + Assert.That(query.Alias, Is.EqualTo(sent.Alias), $"{description} has the aliases that were sent"); + } + /// /// Verifies a commit on a branch: the commit itself, its place in the history, the branch head and its changes /// @@ -149,32 +183,9 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous { var projectId = this.state.ProjectId!.Value; - Guid[] expectedPrevious = previousCommitId.HasValue ? [previousCommitId.Value] : []; - using (Assert.EnterMultipleScope()) { - var commitById = await this.ReadAsync(() => this.client.GetCommitByProjectAndIdAsync(projectId, commit.Id), "GetCommitByProjectAndIdAsync"); - - if (commitById != null) - { - Assert.That(commitById.Id, Is.EqualTo(commit.Id)); - Assert.That(commitById.OwningProject, Is.EqualTo(projectId)); - Assert.That(commitById.PreviousCommit, Is.EqualTo(expectedPrevious)); - } - - var (commits, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetCommitsByProjectAsync(projectId, parameters)), "GetCommitsByProjectAsync"); - - if (commits != null) - { - Assert.That(commits.Select(record => record.Id), Does.Contain(commit.Id)); - } - - var branch = await this.ReadAsync(() => this.client.GetBranchesByProjectAndIdAsync(projectId, branchId), "GetBranchesByProjectAndIdAsync"); - - if (branch != null) - { - Assert.That(branch.Head, Is.EqualTo(commit.Id)); - } + await this.VerifyCommitRecordAsync(commit, branchId, previousCommitId); var (changes, changePages) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetChangesByProjectCommitAsync(projectId, commit.Id, parameters)), "GetChangesByProjectCommitAsync"); @@ -219,6 +230,59 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous } } + /// + /// Verifies a commit of data that is no element, such as project usages and external data, which a client reads + /// back through the changes of the commit: the commit itself, its place in the history, the branch head, and one + /// change per data item, with the payload that was sent or none for a deletion + /// + /// + /// The commit that PostCommitByProjectAsync returned + /// + /// + /// The branch the commit was made on + /// + /// + /// The head of the branch before the commit + /// + /// + /// Per data item, its id and the payload the commit sent, or null when the commit deletes it + /// + /// + /// An awaitable + /// + public async Task VerifyDataCommitAsync(Commit commit, Guid branchId, Guid? previousCommitId, IReadOnlyList<(Guid Id, IData Payload)> expected) + { + var projectId = this.state.ProjectId!.Value; + + using (Assert.EnterMultipleScope()) + { + await this.VerifyCommitRecordAsync(commit, branchId, previousCommitId); + + var (changes, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetChangesByProjectCommitAsync(projectId, commit.Id, parameters)), "GetChangesByProjectCommitAsync"); + + if (changes == null) + { + return; + } + + Assert.That(changes.Select(change => change.Identity?.Id), Is.EquivalentTo(expected.Select(entry => (Guid?)entry.Id)), "one change per data item"); + + var changesById = changes.Where(change => change.Identity != null).GroupBy(change => change.Identity.Id).ToDictionary(group => group.Key, group => group.First()); + + foreach (var (id, payload) in expected.Where(entry => changesById.ContainsKey(entry.Id))) + { + if (payload == null) + { + Assert.That(changesById[id].Payload, Is.Null, $"the change of {id} deletes it"); + } + else + { + VerifySameData(payload, changesById[id].Payload, $"the payload of the change of {payload.GetType().Name} {id}"); + } + } + } + } + /// /// Verifies the diff of two commits: one difference per element created, changed or deleted between them, an /// element of the base commit as updated, and an element added since as created @@ -276,6 +340,31 @@ public async Task VerifyDiffAsync(Guid baseCommitId, Guid compareCommitId, IRead } } + /// + /// Verifies that a list of elements holds exactly the expected elements + /// + /// + /// The description of the read in assertion messages + /// + /// + /// Reads one page of the list for the given + /// + /// + /// The ids of the elements the list must hold + /// + /// + /// An awaitable + /// + public async Task VerifyElementIdsAsync(string description, Func>> readPage, IReadOnlyCollection expectedIds) + { + var (listed, _) = await this.ReadAsync(() => ReadAllPagesAsync(readPage), description); + + if (listed != null) + { + Assert.That(listed.Select(element => element.Id), Is.EquivalentTo(expectedIds), description); + } + } + /// /// Verifies that the history is immutable: an element read at an earlier commit is still the version of that /// commit @@ -385,6 +474,94 @@ public async Task VerifyModelAsync(Guid commitId, IReadOnlyList expect } } + /// + /// Verifies the project usage that brings an element of a used project into a commit + /// + /// + /// The commit + /// + /// + /// The element of the used project + /// + /// + /// The project usage that was committed + /// + /// + /// An awaitable + /// + public async Task VerifyProjectUsageAsync(Guid commitId, Guid elementId, ProjectUsage expected) + { + var (succeeded, actual) = await this.TryReadAsync(() => this.client.GetProjectUsageByProjectCommitElementAsync(this.state.ProjectId!.Value, commitId, elementId), $"GetProjectUsageByProjectCommitElementAsync of {elementId}"); + + if (succeeded) + { + VerifySameData(expected, actual, $"the project usage of {elementId}"); + } + } + + /// + /// Verifies the results of a query: exactly the expected elements, each equal to the element that was sent + /// + /// + /// The description of the read in assertion messages + /// + /// + /// Reads one page of the results for the given + /// + /// + /// The elements the results must hold + /// + /// + /// An awaitable + /// + public async Task VerifyResultsAsync(string description, Func>> readPage, IReadOnlyList expected) + { + var (results, _) = await this.ReadAsync(() => ReadAllPagesAsync(readPage), description); + + if (results == null) + { + return; + } + + using (Assert.EnterMultipleScope()) + { + Assert.That(results.Select(result => result.Id), Is.EquivalentTo(expected.Select(element => element.Id)), description); + + var resultsById = results.GroupBy(result => result.Id).ToDictionary(group => group.Key, group => group.First()); + + foreach (var element in expected.Where(element => resultsById.ContainsKey(element.Id))) + { + VerifySame(element, resultsById[element.Id] as IElement, $"{element.GetType().Name} {element.Id} in {description}"); + } + } + } + + /// + /// Verifies a list of roots against a model: the elements without an owner, or the known divergence + /// + /// + /// + /// The description of the read in assertion messages + /// + /// + /// Reads one page of the roots for the given + /// + /// + /// The model whose roots the list must hold + /// + /// + /// An awaitable + /// + public async Task VerifyRootsAsync(string description, Func>> readPage, IReadOnlyList model) + { + var (roots, _) = await this.ReadAsync(() => ReadAllPagesAsync(readPage), description); + + if (roots != null) + { + VerifyRoots(roots, model); + } + } + /// /// Reads pages of a list operation, following , up to a number of pages /// @@ -538,6 +715,42 @@ private static void VerifySame(IElement sent, IElement actual, string descriptio Assert.Fail($"{description} differs from what was sent: {(differing.Count == 0 ? "a member that only its comparer compares" : string.Join(", ", differing))}"); } + /// + /// Verifies that data read back is of the kind that was sent and equal to it, naming the properties that differ; + /// an element is compared as in + /// + /// + /// The data that was sent + /// + /// + /// The data read back, or null + /// + /// + /// The description of the data in assertion messages + /// + private static void VerifySameData(IData sent, IData actual, string description) + { + if (sent is IElement element) + { + VerifySame(element, actual as IElement, description); + return; + } + + Assert.That(actual, Is.TypeOf(sent.GetType()), $"{description} was read back as another kind of data"); + + if (actual?.GetType() != sent.GetType()) + { + return; + } + + var differing = sent.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public) + .Where(property => !Equals(property.GetValue(sent), property.GetValue(actual))) + .Select(property => property.Name) + .ToList(); + + Assert.That(differing, Is.Empty, $"{description} differs from what was sent"); + } + /// /// Reads from the server, reporting a read that throws as a failure, so that the checks that do not depend on /// it still run @@ -689,6 +902,52 @@ private void ReportFailedRead(string description, Exception exception, IEnumerab } } + /// + /// Verifies the record of a commit: read by id it is the commit, in the project, after the previous head; it is + /// listed; and it is the head of its branch + /// + /// + /// The commit that PostCommitByProjectAsync returned + /// + /// + /// The branch the commit was made on + /// + /// + /// The head of the branch before the commit, or null for the first commit + /// + /// + /// An awaitable + /// + private async Task VerifyCommitRecordAsync(Commit commit, Guid branchId, Guid? previousCommitId) + { + var projectId = this.state.ProjectId!.Value; + + Guid[] expectedPrevious = previousCommitId.HasValue ? [previousCommitId.Value] : []; + + var commitById = await this.ReadAsync(() => this.client.GetCommitByProjectAndIdAsync(projectId, commit.Id), "GetCommitByProjectAndIdAsync"); + + if (commitById != null) + { + Assert.That(commitById.Id, Is.EqualTo(commit.Id)); + Assert.That(commitById.OwningProject, Is.EqualTo(projectId)); + Assert.That(commitById.PreviousCommit, Is.EqualTo(expectedPrevious)); + } + + var (commits, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetCommitsByProjectAsync(projectId, parameters)), "GetCommitsByProjectAsync"); + + if (commits != null) + { + Assert.That(commits.Select(record => record.Id), Does.Contain(commit.Id)); + } + + var branch = await this.ReadAsync(() => this.client.GetBranchesByProjectAndIdAsync(projectId, branchId), "GetBranchesByProjectAndIdAsync"); + + if (branch != null) + { + Assert.That(branch.Head, Is.EqualTo(commit.Id)); + } + } + /// /// Verifies paging on the first small pages of the element list: the model spans /// several pages, and the pages read hold distinct elements of the model diff --git a/SySML2.NET.REST.Tests/Helpers/ScenarioQueries.cs b/SySML2.NET.REST.Tests/Helpers/ScenarioQueries.cs new file mode 100644 index 000000000..c402d305d --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/ScenarioQueries.cs @@ -0,0 +1,232 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers +{ + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using SysML2.NET.Core.DTO.Kernel.Expressions; + using SysML2.NET.Core.DTO.Root.Dependencies; + using SysML2.NET.Core.DTO.Root.Elements; + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.PSM.DTO; + using SysML2.NET.PSM.Enumerations; + + /// + /// The queries of the scenario, each with the elements of a model it must answer, so that the results are checked + /// against the expected model + /// + /// + /// Together they use every PrimitiveConstraint operator, both CompositeConstraint operators, a nested + /// composite and inverse. Every @type they name is a metaclass that no other metaclass specializes, so + /// whether = on @type also matches specializations does not change the results. + /// + public static class ScenarioQueries + { + /// + /// Gets the query that step 9 creates: the integer literals above 1, the dependencies and the rational literals + /// + public static QueryRequest Stored => new() + { + Name = "Literals and dependencies", + Description = "The integer literals above 1, the dependencies and the rational literals", + Alias = ["literals"], + Where = new CompositeConstraintRequest + { + Operator = CompositeConstraintRequestOperator.or, + Constraint = + [ + new CompositeConstraint + { + Operator = CompositeConstraintOperator.and, + Constraint = + [ + Constraint("@type", PrimitiveConstraintOperator.equalto, false, "LiteralInteger"), + Constraint("value", PrimitiveConstraintOperator.greaterthan, false, 1d) + ] + }, + Constraint("@type", PrimitiveConstraintOperator.@in, false, "Dependency", "LiteralRational") + ] + } + }; + + /// + /// Gets the query that step 9 replaces with: the integer literals from 2 to 42 + /// + public static QueryRequest Updated => new() + { + Name = "Integer literals from 2 to 42", + Description = "The integer literals that are not below 2 and at most 42", + Where = new CompositeConstraintRequest + { + Operator = CompositeConstraintRequestOperator.and, + Constraint = + [ + Constraint("@type", PrimitiveConstraintOperator.equalto, false, "LiteralInteger"), + Constraint("value", PrimitiveConstraintOperator.lessthan, true, 2d), + Constraint("value", PrimitiveConstraintOperator.lessthanorequalto, false, 42d) + ] + } + }; + + /// + /// Gets the query definition of the integer literals of at least 42 + /// + public static QueryRequest AtLeast42 => new() + { + Name = "Integer literals of at least 42", + Where = new CompositeConstraintRequest + { + Operator = CompositeConstraintRequestOperator.and, + Constraint = + [ + Constraint("@type", PrimitiveConstraintOperator.equalto, false, "LiteralInteger"), + Constraint("value", PrimitiveConstraintOperator.greaterthanorequalto, false, 42d) + ] + } + }; + + /// + /// Gets the query definition of the namespaces, by the instanceOf operator + /// + public static QueryRequest Namespaces => new() + { + Name = "Namespaces", + Where = new PrimitiveConstraintRequest { Property = "@type", Operator = PrimitiveConstraintRequestOperator.instanceOf, Value = ["Namespace"], Inverse = false } + }; + + /// + /// Renders a constraint, of a request or of a stored query, as text, so that two constraints can be compared; an + /// unset inverse reads as false + /// + /// + /// The constraint + /// + /// + /// The text, or none for anything that is no constraint + /// + public static string ConstraintText(object constraint) + { + static string Primitive(string property, string constraintOperator, bool inverse, IEnumerable values) => + $"{(inverse ? "not " : string.Empty)}{property} {constraintOperator} [{string.Join(", ", (values ?? []).Select(value => value.Match(() => "null", flag => flag.ToString(), number => number.ToString(CultureInfo.InvariantCulture), text => $"\"{text}\"", id => id.ToString())))}]"; + + return constraint switch + { + CompositeConstraintRequest composite => $"{composite.Operator}({string.Join(", ", composite.Constraint.Select(ConstraintText))})", + CompositeConstraint composite => $"{composite.Operator}({string.Join(", ", composite.Constraint.Select(ConstraintText))})", + PrimitiveConstraintRequest primitive => Primitive(primitive.Property, primitive.Operator.ToString(), primitive.Inverse ?? false, primitive.Value), + PrimitiveConstraint primitive => Primitive(primitive.Property, primitive.Operator.ToString(), primitive.Inverse, primitive.Value), + _ => "none" + }; + } + + /// + /// Gets whether an element is a result of + /// + /// + /// The element + /// + /// + /// Whether the query answers it + /// + public static bool IsAtLeast42(IElement element) => element is LiteralInteger { Value: >= 42 }; + + /// + /// Gets whether an element is a result of + /// + /// + /// The element + /// + /// + /// Whether the query answers it + /// + public static bool IsNamespace(IElement element) => element is INamespace; + + /// + /// Gets whether an element is a result of + /// + /// + /// The element + /// + /// + /// Whether the query answers it + /// + public static bool IsStoredResult(IElement element) => element is LiteralInteger { Value: > 1 } || element.GetType() == typeof(Dependency) || element.GetType() == typeof(LiteralRational); + + /// + /// Gets whether an element is a result of + /// + /// + /// The element + /// + /// + /// Whether the query answers it + /// + public static bool IsUpdatedResult(IElement element) => element is LiteralInteger { Value: >= 2 and <= 42 }; + + /// + /// Gets the query definition of the elements of a declared name that selects only their id and name + /// + /// + /// The declared name + /// + /// + /// The query definition + /// + public static QueryRequest Named(string declaredName) => new() + { + Name = $"Named {declaredName}", + Select = ["@id", "declaredName"], + Where = new PrimitiveConstraintRequest { Property = "declaredName", Operator = PrimitiveConstraintRequestOperator.equalto, Value = [declaredName], Inverse = false } + }; + + /// + /// Gets the query definition of the elements of a declared name, whose constraint leaves inverse unset + /// + /// + /// The declared name + /// + /// + /// The query definition + /// + public static QueryRequest NamedWithoutInverse(string declaredName) => new() + { + Name = $"Named {declaredName}", + Where = new PrimitiveConstraintRequest { Property = "declaredName", Operator = PrimitiveConstraintRequestOperator.equalto, Value = [declaredName] } + }; + + /// + /// Creates a primitive constraint, as nested in a composite constraint + /// + /// + /// The property the constraint is about + /// + /// + /// The operator + /// + /// + /// Whether the constraint is inverted + /// + /// + /// The values the property is compared with + /// + /// + /// The constraint + /// + private static PrimitiveConstraint Constraint(string property, PrimitiveConstraintOperator constraintOperator, bool inverse, params ConstraintValue[] values) => new() + { + Property = property, + Operator = constraintOperator, + Inverse = inverse, + Value = [.. values] + }; + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs index 333368a86..6df9079ad 100644 --- a/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs +++ b/SySML2.NET.REST.Tests/Helpers/ScenarioState.cs @@ -27,6 +27,11 @@ public sealed class ScenarioState /// public Guid? ProjectId { get; set; } + /// + /// Gets or sets the id of the project that the main project uses, created in step 10 + /// + public Guid? LibraryProjectId { get; set; } + /// /// Gets or sets the id of the default branch of the project /// diff --git a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs index 61be73b0a..f8abb9f2a 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs @@ -36,7 +36,7 @@ public void VerifyAll() { using (Assert.EnterMultipleScope()) { - Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.DiffNotImplemented, KnownServerDivergences.MergeNotImplemented, KnownServerDivergences.MergeRequiresArrayBody, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri])); + Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.DiffNotImplemented, KnownServerDivergences.MergeNotImplemented, KnownServerDivergences.MergeRequiresArrayBody, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri, KnownServerDivergences.DataListedAsElements, KnownServerDivergences.ProjectUsageAsArray, KnownServerDivergences.QueryResultsProjected, KnownServerDivergences.QueryLosesNameAndDescription, KnownServerDivergences.InstanceOfRejected, KnownServerDivergences.QueryResultsGetNotImplemented])); Assert.That(KnownServerDivergences.All.Select(divergence => divergence.Reference), Has.All.Contains("Open-MBEE/flexo-mms-sysmlv2@836d904d")); } } @@ -61,6 +61,38 @@ public void VerifyCreatedAnsweredOk() } } + [Test] + public void VerifyDataListedAsElements() + { + var openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + var getElements = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements"); + var getRoots = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/roots"); + var getChanges = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/changes"); + var explains = KnownServerDivergences.DataListedAsElements.Explains; + static ContractViolation UnknownType(string type) => new(ContractViolationKind.SchemaMismatch, $"/2/@type const: \"{type}\" is none of the types the schema admits"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(new EndpointCall(getElements, "GET /projects/p/commits/c/elements", HttpStatusCode.OK), UnknownType("ExternalData")), Is.True); + Assert.That(explains(new EndpointCall(getRoots, "GET /projects/p/commits/c/roots", HttpStatusCode.OK), UnknownType("ProjectUsage")), Is.True); + Assert.That(explains(new EndpointCall(getElements, "GET /projects/p/commits/c/elements", HttpStatusCode.OK), UnknownType("ExternalRelationship")), Is.True); + Assert.That(explains(new EndpointCall(getElements, "GET /projects/p/commits/c/elements", HttpStatusCode.OK), UnknownType("Pakage")), Is.False, "a misspelt metaclass is no kind of data"); + Assert.That(explains(new EndpointCall(getChanges, "GET /projects/p/commits/c/changes", HttpStatusCode.OK), UnknownType("ExternalData")), Is.False); + Assert.That(explains(new EndpointCall(null, "GET /unknown", HttpStatusCode.OK), UnknownType("ExternalData")), Is.False); + Assert.That(explains(new EndpointCall(getElements, "GET /projects/p/commits/c/elements", HttpStatusCode.OK), UnknownType("ExternalData") with { Kind = ContractViolationKind.InvalidJson }), Is.False, "only a schema mismatch is explained"); + } + + var dataItem = getElements.CheckResponse(HttpStatusCode.OK, "application/json", "[{\"@type\":\"Package\",\"@id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\"},{\"@type\":\"ExternalData\",\"@id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa7\",\"resourceIdentifier\":\"https://example.org/r\"}]"); + var misspelt = getElements.CheckResponse(HttpStatusCode.OK, "application/json", "[{\"@type\":\"Pakage\",\"@id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\"}]"); + var call = new EndpointCall(getElements, "GET /projects/p/commits/c/elements", HttpStatusCode.OK); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dataItem.Where(violation => explains(call, violation)).Select(violation => violation.Message), Has.Some.StartsWith("/1/@type"), "the violation the conformance check produces for a data item is explained"); + Assert.That(misspelt, Is.Not.Empty.And.None.Matches(violation => explains(call, violation))); + } + } + [Test] public void VerifyDatatypeIdNotUri() { @@ -161,10 +193,52 @@ public void VerifyPreviousCommitAsObject() Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/0/previousCommit type: Value is \"object\" but should be \"array\"")), Is.True); Assert.That(explains(call, new ContractViolation(ContractViolationKind.SchemaMismatch, "/change type: Value is \"object\" but should be \"array\"")), Is.False); Assert.That(explains(call, new ContractViolation(ContractViolationKind.InvalidJson, "/previousCommit type: Value is \"object\" but should be \"array\"")), Is.False); - Assert.That(KnownServerDivergences.All.Where(divergence => divergence.BreaksDeserialization), Is.EqualTo((ServerDivergence[])[KnownServerDivergences.PreviousCommitAsObject])); + Assert.That(KnownServerDivergences.All.Where(divergence => divergence.BreaksDeserialization), Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.DataListedAsElements, KnownServerDivergences.ProjectUsageAsArray, KnownServerDivergences.QueryResultsProjected])); } } + [Test] + public void VerifyProjectUsageAsArray() + { + var openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + var getUsage = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements/{elementId}/projectUsage"); + var getElement = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements/{elementId}"); + var explains = KnownServerDivergences.ProjectUsageAsArray.Explains; + var array = new ContractViolation(ContractViolationKind.SchemaMismatch, "/ type: Value is \"array\" but should be \"object\""); + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(new EndpointCall(getUsage, "GET /projects/p/commits/c/elements/e/projectUsage", HttpStatusCode.OK), array), Is.True); + Assert.That(explains(new EndpointCall(getUsage, "GET /projects/p/commits/c/elements/e/projectUsage", HttpStatusCode.OK), new ContractViolation(ContractViolationKind.SchemaMismatch, "/usedProject type: Value is \"array\" but should be \"object\"")), Is.False); + Assert.That(explains(new EndpointCall(getElement, "GET /projects/p/commits/c/elements/e", HttpStatusCode.OK), array), Is.False); + } + } + + [Test] + public void VerifyQueryResultsProjected() + { + var openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + var queryResults = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/queries/{queryId}/results"); + var postQueryResults = openApi.Operations.Single(operation => operation.ToString() == "POST /projects/{projectId}/query-results"); + var getElements = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements"); + var explains = KnownServerDivergences.QueryResultsProjected.Explains; + var projected = Missing("/0", "\"@type\",\"aliasIds\",\"owner\""); + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(new EndpointCall(queryResults, "GET /projects/p/queries/q/results", HttpStatusCode.OK), projected), Is.True); + Assert.That(explains(new EndpointCall(postQueryResults, "POST /projects/p/query-results", HttpStatusCode.OK), projected), Is.True); + Assert.That(explains(new EndpointCall(queryResults, "GET /projects/p/queries/q/results", HttpStatusCode.OK), Missing("/0", "\"aliasIds\",\"owner\"")), Is.False, "complete results that miss properties are another matter"); + Assert.That(explains(new EndpointCall(getElements, "GET /projects/p/commits/c/elements", HttpStatusCode.OK), projected), Is.False); + Assert.That(explains(new EndpointCall(queryResults, "GET /projects/p/queries/q/results", HttpStatusCode.OK), projected with { Kind = ContractViolationKind.InvalidJson }), Is.False, "only a schema mismatch is explained"); + } + + var selected = postQueryResults.CheckResponse(HttpStatusCode.OK, "application/json", "[{\"@id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\",\"declaredName\":\"x\"}]"); + var call = new EndpointCall(postQueryResults, "POST /projects/p/query-results", HttpStatusCode.OK); + + Assert.That(selected.Where(violation => explains(call, violation)), Is.Not.Empty, "the violation the conformance check produces for a projected result is explained"); + } + [Test] public void VerifyRecordsWithoutRequiredProperties() { diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/LibraryModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/LibraryModelTestFixture.cs new file mode 100644 index 000000000..5cf2f19a2 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/LibraryModelTestFixture.cs @@ -0,0 +1,44 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System; + using System.Linq; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers.Models; + + using SysML2.NET.Core.DTO.Kernel.Packages; + using SysML2.NET.Core.DTO.Root.Namespaces; + + [TestFixture] + public class LibraryModelTestFixture + { + [Test] + public void VerifyLibraryModel() + { + var model = new LibraryModel(); + var dtos = model.Builder.ToDtos(); + var membership = dtos.OfType().Single(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos.Select(dto => dto.GetType()), Is.EquivalentTo((Type[])[typeof(LibraryPackage), typeof(OwningMembership), typeof(Package)])); + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(model.Root.DeclaredName, Is.EqualTo("UsedLibrary")); + Assert.That(membership.OwningRelatedElement, Is.EqualTo(model.Root.Id)); + Assert.That(membership.OwnedRelatedElement, Is.EqualTo((Guid[])[model.Used.Id])); + Assert.That(new LibraryModel().Used.Id, Is.EqualTo(model.Used.Id), "the ids are the same in every run"); + Assert.That(model.Used.Id, Is.Not.EqualTo(new RootModel().Nested.Id)); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs index 082a4805d..09bf17ee4 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsBehaviorModelTestFixture.cs @@ -9,6 +9,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests.Models { + using System; using System.IO; using System.Linq; using System.Text; @@ -16,6 +17,11 @@ namespace SySML2.NET.REST.Tests.HelpersTests.Models using NUnit.Framework; + using SysML2.NET.Core.DTO.Core.Features; + using SysML2.NET.Core.DTO.Kernel.Expressions; + using SysML2.NET.Core.DTO.Kernel.FeatureValues; + using SysML2.NET.Core.DTO.Root.Elements; + using SysML2.NET.Core.DTO.Systems.States; using SysML2.NET.Serializer.Json; using SySML2.NET.REST.Tests.Helpers; @@ -71,6 +77,30 @@ public void VerifySystemsBehaviorModel() Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo((string[])["systems behaviour/accept when/trigger", "systems behaviour/accept at/trigger", "systems behaviour/accept after/trigger"]), "only the trigger invocations, whose instantiated type needs the model library"); } + + var level = dtos.OfType().Single(feature => feature.GetType() == typeof(Feature) && feature.DeclaredName == "level"); + var limit = dtos.OfType().Single(feature => feature.GetType() == typeof(Feature) && feature.DeclaredName == "limit"); + var initialValue = dtos.OfType().Single(value => value.OwningRelatedElement == limit.Id); + var parallel = dtos.OfType().Single(state => state.DeclaredName == "Par"); + var parallelUsage = dtos.OfType().Single(state => state.DeclaredName == "pu"); + var ownedByParallel = dtos.OfType().Where(relationship => relationship.OwningRelatedElement == parallel.Id).SelectMany(relationship => relationship.OwnedRelatedElement).Select(id => dtos.Single(dto => dto.Id == id)).ToList(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(level.IsVariable, Is.True); + Assert.That(level.IsConstant, Is.False, "the referent of an assignment changes over time"); + Assert.That(dtos.OfType().Where(value => value.OwningRelatedElement == level.Id), Is.Empty, "the referent of an assignment has no initial value"); + Assert.That(limit.IsVariable, Is.True); + Assert.That(limit.IsConstant, Is.True, "a constant feature must be variable"); + Assert.That(initialValue.IsInitial, Is.True); + Assert.That(dtos.Single(dto => dto.Id == initialValue.OwnedRelatedElement[0]), Is.TypeOf().With.Property(nameof(LiteralInteger.Value)).EqualTo(0)); + Assert.That(parallel.IsParallel, Is.True); + Assert.That(ownedByParallel.Select(element => element.DeclaredName), Is.EquivalentTo((string[])["pa1", "pa2"])); + Assert.That(ownedByParallel, Has.All.TypeOf(), "the substates of a parallel state have no transitions"); + Assert.That(parallelUsage.IsParallel, Is.True); + Assert.That(dtos.OfType().Where(typing => typing.OwningRelatedElement == parallelUsage.Id).Select(typing => typing.Type), Is.EqualTo((Guid[])[parallel.Id])); + Assert.That(dtos.OfType().Single(state => state.DeclaredName == "St").IsParallel, Is.False, "the state definition with a transition is not parallel"); + } } } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs index 5edaf64ca..0707e15bc 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs @@ -17,6 +17,10 @@ namespace SySML2.NET.REST.Tests.HelpersTests.Models using NUnit.Framework; + using SysML2.NET.Core.DTO.Core.Features; + using SysML2.NET.Core.DTO.Root.Elements; + using SysML2.NET.Core.DTO.Systems.DefinitionAndUsage; + using SysML2.NET.Core.DTO.Systems.Parts; using SysML2.NET.Core.POCO.Kernel.Expressions; using SysML2.NET.Serializer.Json; @@ -65,6 +69,20 @@ public void VerifySystemsStructureModel() Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo((string[])["kernel/sum", "kernel/index", "kernel/select", "kernel/collect", "kernel/chain"]), "no structure element loses its derived values"); } + + var variation = dtos.OfType().Single(part => part.DeclaredName == "vu"); + var variant = dtos.OfType().Single(part => part.DeclaredName == "vu1"); + var ownedByVariation = dtos.OfType().Where(relationship => relationship.OwningRelatedElement == variation.Id).ToList(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(variation.IsVariation, Is.True); + Assert.That(variation.IsAbstract, Is.True, "a variation usage must be abstract"); + Assert.That(ownedByVariation, Has.Count.EqualTo(1).And.All.TypeOf(), "a variation usage owns only variant memberships"); + Assert.That(ownedByVariation[0].OwnedRelatedElement, Is.EqualTo((Guid[])[variant.Id])); + Assert.That(variant.IsVariation, Is.False); + Assert.That(dtos.OfType().Where(subsetting => subsetting.OwningRelatedElement == variant.Id).Select(subsetting => subsetting.SubsettedFeature), Is.EqualTo((Guid[])[variation.Id]), "a variant specializes its variation usage"); + } } } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs index 94ecac247..be3682434 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs @@ -85,6 +85,7 @@ public void VerifyCheckByType() var missingB = single.Check("application/json", "{\"@type\":\"B\"}"); var listMissingB = list.Check("application/json", "[{\"@type\":\"A\",\"a\":\"x\"},{\"@type\":\"B\"}]"); + var listUnknownType = list.Check("application/json", "[{\"@type\":\"B\"},{\"@type\":\"C\"}]"); using (Assert.EnterMultipleScope()) { @@ -94,6 +95,7 @@ public void VerifyCheckByType() Assert.That(missingB.Select(violation => violation.Message), Is.EqualTo((string[])["/ required: Required properties [\"b\"] are not present"])); Assert.That(list.Check("application/json", "[{\"@type\":\"A\",\"a\":\"x\"},{\"@type\":\"B\",\"b\":\"y\"}]"), Is.Empty); Assert.That(listMissingB.Select(violation => violation.Message), Is.EqualTo((string[])["/1 required: Required properties [\"b\"] are not present"])); + Assert.That(listUnknownType.Select(violation => violation.Message), Is.EqualTo((string[])["/1/@type const: \"C\" is none of the types the schema admits", "/0 required: Required properties [\"b\"] are not present"]), "an item of an unknown @type is reported first, at its place, and the other items are still checked by type"); Assert.That(single.Check("application/json", "{\"@type\":\"C\"}")[0].Message, Does.Contain("@type const"), "an unknown @type is left to the declared schema"); Assert.That(Kinds(single.Check("application/json", "5")), Is.Not.Empty.And.All.EqualTo(ContractViolationKind.SchemaMismatch), "a body that is no object is left to the declared schema"); Assert.That(list.Check("application/json", "{\"@type\":\"A\",\"a\":\"x\"}"), Is.Not.Empty, "an object where an array is declared is left to the declared schema"); diff --git a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs index 429d60ea6..5a65adbbf 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs @@ -12,6 +12,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests using System; using System.Collections.Concurrent; using System.Collections.Generic; + using System.IO; using System.Linq; using System.Net; using System.Reflection; @@ -34,6 +35,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests using SysML2.NET.Core.DTO.Root.Namespaces; using SysML2.NET.PSM; using SysML2.NET.PSM.DTO; + using SysML2.NET.PSM.Enumerations; using SysML2.NET.REST.Exceptions; using Direction = SysML2.NET.PSM.Enumerations.Direction; @@ -244,6 +246,83 @@ public async Task VerifyVerifyCommitAsync() this.client.Verify(api => api.GetChangeByProjectCommitIdAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } + [Test] + public async Task VerifyVerifyDataCommitAsync() + { + var branchId = Guid.NewGuid(); + var previousId = Guid.NewGuid(); + var commit = new Commit { Id = this.commitId, OwningProject = this.projectId, PreviousCommit = [previousId] }; + var data = new ExternalData { Id = Guid.NewGuid(), ResourceIdentifier = new Uri("https://example.org/r") }; + var usage = new ProjectUsage { Id = Guid.NewGuid(), UsedProject = Guid.NewGuid(), UsedCommit = Guid.NewGuid() }; + var package = new Package { Id = Guid.NewGuid(), DeclaredName = "P" }; + var deletedId = Guid.NewGuid(); + Guid? head = this.commitId; + var changesUnreadable = false; + + List Changes(IData dataPayload, IData usagePayload, IData deletedPayload) => + [ + new() { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = data.Id }, Payload = dataPayload }, + new() { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = usage.Id }, Payload = usagePayload }, + new() { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = package.Id }, Payload = Clone(package) }, + new() { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = deletedId }, Payload = deletedPayload } + ]; + + var changes = Changes(new ExternalData { Id = data.Id, ResourceIdentifier = new Uri("https://example.org/r") }, new ProjectUsage { Id = usage.Id, UsedProject = usage.UsedProject, UsedCommit = usage.UsedCommit }, null); + + this.client.Setup(api => api.GetCommitByProjectAndIdAsync(this.projectId, this.commitId, It.IsAny())).ReturnsAsync(() => commit); + this.client.Setup(api => api.GetCommitsByProjectAsync(this.projectId, It.IsAny(), It.IsAny())).Returns((Guid _, QueryParameters parameters, CancellationToken _) => Paged([commit], parameters)); + this.client.Setup(api => api.GetBranchesByProjectAndIdAsync(this.projectId, branchId, It.IsAny())).ReturnsAsync(() => new Branch { Id = branchId, Head = head }); + this.client.Setup(api => api.GetChangesByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny())).Returns((Guid _, Guid _, QueryParameters parameters, CancellationToken _) => changesUnreadable ? throw new InvalidOperationException("no changes") : Paged(changes, parameters)); + + List<(Guid Id, IData Payload)> expected = [(data.Id, data), (usage.Id, usage), (package.Id, package), (deletedId, null)]; + + var matching = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + changes = Changes(new ExternalData { Id = data.Id, ResourceIdentifier = new Uri("https://example.org/other") }, usage, null); + + var dataChanged = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + changes = Changes(data, new ExternalData { Id = usage.Id }, null); + + var otherKind = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + changes = Changes(data, usage, new ExternalData { Id = deletedId }); + + var notDeleted = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + changes = Changes(null, usage, null); + + var deletedInstead = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + changes = Changes(data, usage, null)[..3]; + + var changeMissing = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + changes = Changes(data, usage, null); + head = previousId; + + var headNotMoved = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + head = this.commitId; + changesUnreadable = true; + + var unreadable = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(matching, Is.Empty); + Assert.That(dataChanged.Select(result => result.Message), Has.Some.Contains($"the payload of the change of ExternalData {data.Id} differs from what was sent").And.Some.Contains("ResourceIdentifier")); + Assert.That(otherKind.Select(result => result.Message), Has.Some.Contains($"the payload of the change of ProjectUsage {usage.Id} was read back as another kind of data")); + Assert.That(notDeleted.Select(result => result.Message), Has.Some.Contains($"the change of {deletedId} deletes it")); + Assert.That(deletedInstead, Has.Count.EqualTo(1), "a server that deletes what was written fails"); + Assert.That(deletedInstead[0].Message, Does.Contain($"the payload of the change of ExternalData {data.Id} was read back as another kind of data")); + Assert.That(changeMissing.Select(result => result.Message), Has.Some.Contains("one change per data item")); + Assert.That(changeMissing, Has.Count.EqualTo(1)); + Assert.That(headNotMoved, Has.Count.EqualTo(1)); + Assert.That(unreadable.Select(result => result.Message), Is.EqualTo((string[])["GetChangesByProjectCommitAsync threw InvalidOperationException: no changes"]), "the commit record still passes"); + } + } + [Test] public async Task VerifyVerifyDiffAsync() { @@ -297,6 +376,32 @@ public async Task VerifyVerifyDiffAsync() } } + [Test] + public async Task VerifyVerifyElementIdsAsync() + { + IReadOnlyList listed = [new Package { Id = Guid.NewGuid() }, new Package { Id = Guid.NewGuid() }]; + var unreadable = false; + + Task> ReadPage(QueryParameters parameters) => unreadable ? throw new InvalidOperationException("no list") : Paged(listed, parameters); + + var expectedIds = listed.Select(element => element.Id).ToList(); + + var same = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyElementIdsAsync("the list", ReadPage, expectedIds)); + var missing = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyElementIdsAsync("the list", ReadPage, [.. expectedIds, Guid.NewGuid()])); + + unreadable = true; + + var failed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyElementIdsAsync("the list", ReadPage, expectedIds)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(same, Is.Empty); + Assert.That(missing, Has.Count.EqualTo(1)); + Assert.That(missing[0].Message, Does.StartWith(" the list")); + Assert.That(failed.Select(result => result.Message), Is.EqualTo((string[])["the list threw InvalidOperationException: no list"])); + } + } + [Test] public async Task VerifyVerifyHistoryAsync() { @@ -565,6 +670,154 @@ public async Task VerifyVerifyModelAsync() } } + [Test] + public async Task VerifyVerifyProjectUsageAsync() + { + var elementId = Guid.NewGuid(); + var openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + var usageOperation = openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements/{elementId}/projectUsage"); + var usage = new ProjectUsage { Id = Guid.NewGuid(), UsedProject = Guid.NewGuid(), UsedCommit = Guid.NewGuid() }; + ProjectUsage answered = new() { Id = usage.Id, UsedProject = usage.UsedProject, UsedCommit = usage.UsedCommit }; + Exception failure = null; + var recorded = new List(); + + this.client.Setup(api => api.GetProjectUsageByProjectCommitElementAsync(this.projectId, this.commitId, elementId, It.IsAny())) + .ReturnsAsync(() => failure != null ? throw failure : answered); + + var same = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyProjectUsageAsync(this.commitId, elementId, usage)); + + answered = new ProjectUsage { Id = usage.Id, UsedProject = usage.UsedProject, UsedCommit = Guid.NewGuid() }; + + var otherCommit = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyProjectUsageAsync(this.commitId, elementId, usage)); + + failure = new InvalidOperationException("an array"); + + var failed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyProjectUsageAsync(this.commitId, elementId, usage)); + + var recording = new ReadBackAssertions(this.client.Object, this.state, () => recorded, [KnownServerDivergences.ProjectUsageAsArray]); + this.client.Setup(api => api.GetProjectUsageByProjectCommitElementAsync(this.projectId, this.commitId, elementId, It.IsAny())) + .Returns(() => + { + recorded.Add(new EndpointCall(usageOperation, "GET /projects/p/commits/c/elements/e/projectUsage", HttpStatusCode.OK) { ResponseViolations = [new ContractViolation(ContractViolationKind.SchemaMismatch, "/ type: Value is \"array\" but should be \"object\"")] }); + throw new InvalidOperationException("an array"); + }); + + var excused = await IsolatedAssertions.RunAsync(() => recording.VerifyProjectUsageAsync(this.commitId, elementId, usage)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(same, Is.Empty); + Assert.That(otherCommit.Select(result => result.Message), Has.Some.Contains($"the project usage of {elementId} differs from what was sent")); + Assert.That(failed.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(excused.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning]), "its own breaking response excuses the read"); + } + } + + [Test] + public async Task VerifyVerifyQueryRecord() + { + var projectId = Guid.NewGuid(); + var sent = ScenarioQueries.Stored; + var sentWhere = (CompositeConstraintRequest)sent.Where; + + Query Record(Action change = null) + { + var query = new Query { Id = Guid.NewGuid(), OwningProject = projectId, Name = sent.Name, Description = sent.Description, Alias = [.. sent.Alias], Select = [.. sent.Select], Where = new CompositeConstraint { Operator = CompositeConstraintOperator.or, Constraint = sentWhere.Constraint } }; + change?.Invoke(query); + return query; + } + + Task> Verify(Query query) => IsolatedAssertions.RunAsync(() => + { + ReadBackAssertions.VerifyQueryRecord(query, sent, projectId, "the query"); + return Task.CompletedTask; + }); + + var same = await Verify(Record()); + var lost = await Verify(Record(query => { query.Name = null; query.Description = null; query.Alias = []; })); + var descriptionLost = await Verify(Record(query => query.Description = null)); + var otherProject = await Verify(Record(query => query.OwningProject = Guid.NewGuid())); + var otherSelect = await Verify(Record(query => query.Select = ["@id"])); + var otherWhere = await Verify(Record(query => query.Where = new CompositeConstraint { Operator = CompositeConstraintOperator.and, Constraint = sentWhere.Constraint })); + + using (Assert.EnterMultipleScope()) + { + Assert.That(same, Is.Empty); + Assert.That(lost.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(lost[0].Message, Does.Contain(KnownServerDivergences.QueryLosesNameAndDescription.Summary)); + Assert.That(descriptionLost.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed]), "losing the description alone is no known divergence"); + Assert.That(otherProject.Select(result => result.Message), Has.Some.Contains("the query belongs to the project")); + Assert.That(otherSelect.Select(result => result.Message), Has.Some.Contains("the query selects what was sent")); + Assert.That(otherWhere.Select(result => result.Message), Has.Some.Contains("the query has the constraint that was sent")); + } + } + + [Test] + public async Task VerifyVerifyResultsAsync() + { + var first = new Package { Id = Guid.NewGuid(), DeclaredName = "First" }; + var second = new Package { Id = Guid.NewGuid(), DeclaredName = "Second" }; + IReadOnlyList results = [Clone(first), Clone(second)]; + var unreadable = false; + + Task> ReadPage(QueryParameters parameters) => unreadable ? throw new InvalidOperationException("no results") : Paged(results, parameters); + + var same = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyResultsAsync("the results", ReadPage, [first, second])); + var extra = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyResultsAsync("the results", ReadPage, [first])); + + var renamed = (Package)Clone(second); + renamed.DeclaredName = "Renamed"; + results = [Clone(first), renamed]; + + var changed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyResultsAsync("the results", ReadPage, [first, second])); + + unreadable = true; + + var failed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyResultsAsync("the results", ReadPage, [first, second])); + + using (Assert.EnterMultipleScope()) + { + Assert.That(same, Is.Empty); + Assert.That(extra, Has.Count.EqualTo(1)); + Assert.That(changed.Select(result => result.Message), Is.EqualTo((string[])[$"Package {second.Id} in the results differs from what was sent: Element.DeclaredName"])); + Assert.That(failed.Select(result => result.Message), Is.EqualTo((string[])["the results threw InvalidOperationException: no results"])); + } + } + + [Test] + public async Task VerifyVerifyRootsAsync() + { + var elements = new RootModel().Builder.ToDtos(); + var unowned = elements.Where(element => element.OwningRelationship == null).ToList(); + IReadOnlyList roots = unowned; + var unreadable = false; + + Task> ReadPage(QueryParameters parameters) => unreadable ? throw new InvalidOperationException("no roots") : Paged(roots, parameters); + + var exact = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyRootsAsync("the roots", ReadPage, elements)); + + roots = [.. elements.Where(element => element is not IRelationship { OwningRelatedElement: not null })]; + + var divergent = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyRootsAsync("the roots", ReadPage, elements)); + + roots = elements; + + var everyElement = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyRootsAsync("the roots", ReadPage, elements)); + + unreadable = true; + + var failed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyRootsAsync("the roots", ReadPage, elements)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(exact, Is.Empty); + Assert.That(divergent.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning]), "the known divergence is reported"); + Assert.That(divergent[0].Message, Does.Contain(KnownServerDivergences.RootsIgnoreOwningRelationship.Summary)); + Assert.That(everyElement.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(failed.Select(result => result.Message), Is.EqualTo((string[])["the roots threw InvalidOperationException: no roots"])); + } + } + private static IElement Clone(IElement element) => (IElement)CloneMethod.Invoke(element, null); private static Task> Paged(IReadOnlyList records, QueryParameters parameters) diff --git a/SySML2.NET.REST.Tests/HelpersTests/ScenarioQueriesTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ScenarioQueriesTestFixture.cs new file mode 100644 index 000000000..84ed7f193 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/ScenarioQueriesTestFixture.cs @@ -0,0 +1,190 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests +{ + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + + using SysML2.NET.Core.DTO.Kernel.Expressions; + using SysML2.NET.Core.DTO.Kernel.Packages; + using SysML2.NET.Core.DTO.Root.Dependencies; + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.PSM.DTO; + using SysML2.NET.PSM.Enumerations; + + [TestFixture] + public class ScenarioQueriesTestFixture + { + [Test] + public void VerifyAtLeast42() + { + var where = (CompositeConstraintRequest)ScenarioQueries.AtLeast42.Where; + + using (Assert.EnterMultipleScope()) + { + Assert.That(where.Operator, Is.EqualTo(CompositeConstraintRequestOperator.and)); + Assert.That(Describe(where), Is.EqualTo((string[])["@type equalto False [LiteralInteger]", "value greaterthanorequalto False [42]"])); + Assert.That(ScenarioQueries.AtLeast42.Select, Is.Empty, "the results are complete elements"); + } + } + + [Test] + public void VerifyConstraintText() + { + var stored = (CompositeConstraintRequest)ScenarioQueries.Stored.Where; + var flipped = (PrimitiveConstraint)stored.Constraint[1]; + + using (Assert.EnterMultipleScope()) + { + Assert.That(ScenarioQueries.ConstraintText(stored), Is.EqualTo("or(and(@type equalto [\"LiteralInteger\"], value greaterthan [1]), @type in [\"Dependency\", \"LiteralRational\"])")); + Assert.That(ScenarioQueries.ConstraintText(new CompositeConstraint { Operator = CompositeConstraintOperator.or, Constraint = stored.Constraint }), Is.EqualTo(ScenarioQueries.ConstraintText(stored)), "a stored constraint reads as the request it came from"); + Assert.That(ScenarioQueries.ConstraintText(ScenarioQueries.Updated.Where), Does.Contain("not value lessthan [2]")); + Assert.That(ScenarioQueries.ConstraintText(ScenarioQueries.Namespaces.Where), Is.EqualTo("@type instanceOf [\"Namespace\"]")); + Assert.That(ScenarioQueries.ConstraintText(ScenarioQueries.NamedWithoutInverse("x").Where), Is.EqualTo(ScenarioQueries.ConstraintText(ScenarioQueries.Named("x").Where)), "an unset inverse reads as false"); + Assert.That(ScenarioQueries.ConstraintText(new PrimitiveConstraint { Property = flipped.Property, Operator = flipped.Operator, Inverse = true, Value = flipped.Value }), Is.Not.EqualTo(ScenarioQueries.ConstraintText(flipped))); + Assert.That(ScenarioQueries.ConstraintText(null), Is.EqualTo("none")); + Assert.That(ScenarioQueries.ConstraintText("no constraint"), Is.EqualTo("none")); + } + } + + [Test] + public void VerifyIsAtLeast42() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(ScenarioQueries.IsAtLeast42(new LiteralInteger { Value = 42 }), Is.True); + Assert.That(ScenarioQueries.IsAtLeast42(new LiteralInteger { Value = 41 }), Is.False); + Assert.That(ScenarioQueries.IsAtLeast42(new LiteralRational { Value = 50 }), Is.False); + } + } + + [Test] + public void VerifyIsNamespace() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(ScenarioQueries.IsNamespace(new Namespace()), Is.True); + Assert.That(ScenarioQueries.IsNamespace(new Package()), Is.True, "a package is a namespace"); + Assert.That(ScenarioQueries.IsNamespace(new Dependency()), Is.False); + } + } + + [Test] + public void VerifyIsStoredResult() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(ScenarioQueries.IsStoredResult(new LiteralInteger { Value = 2 }), Is.True); + Assert.That(ScenarioQueries.IsStoredResult(new LiteralInteger { Value = 1 }), Is.False); + Assert.That(ScenarioQueries.IsStoredResult(new Dependency()), Is.True); + Assert.That(ScenarioQueries.IsStoredResult(new LiteralRational { Value = 0 }), Is.True); + Assert.That(ScenarioQueries.IsStoredResult(new Package()), Is.False); + } + } + + [Test] + public void VerifyIsUpdatedResult() + { + using (Assert.EnterMultipleScope()) + { + Assert.That(ScenarioQueries.IsUpdatedResult(new LiteralInteger { Value = 2 }), Is.True); + Assert.That(ScenarioQueries.IsUpdatedResult(new LiteralInteger { Value = 42 }), Is.True); + Assert.That(ScenarioQueries.IsUpdatedResult(new LiteralInteger { Value = 1 }), Is.False); + Assert.That(ScenarioQueries.IsUpdatedResult(new LiteralInteger { Value = 43 }), Is.False); + Assert.That(ScenarioQueries.IsUpdatedResult(new LiteralRational { Value = 3 }), Is.False); + } + } + + [Test] + public void VerifyNamed() + { + var query = ScenarioQueries.Named("Systems"); + var where = (PrimitiveConstraintRequest)query.Where; + + using (Assert.EnterMultipleScope()) + { + Assert.That(query.Select, Is.EqualTo((string[])["@id", "declaredName"]), "the select leaves out @type"); + Assert.That(where.Property, Is.EqualTo("declaredName")); + Assert.That(where.Operator, Is.EqualTo(PrimitiveConstraintRequestOperator.equalto)); + Assert.That(where.Value, Is.EqualTo((ConstraintValue[])["Systems"])); + Assert.That(where.Inverse, Is.False); + } + } + + [Test] + public void VerifyNamedWithoutInverse() + { + var where = (PrimitiveConstraintRequest)ScenarioQueries.NamedWithoutInverse("Systems").Where; + + using (Assert.EnterMultipleScope()) + { + Assert.That(where.Property, Is.EqualTo("declaredName")); + Assert.That(where.Operator, Is.EqualTo(PrimitiveConstraintRequestOperator.equalto)); + Assert.That(where.Value, Is.EqualTo((ConstraintValue[])["Systems"])); + Assert.That(where.Inverse, Is.Null); + } + } + + [Test] + public void VerifyNamespaces() + { + var where = (PrimitiveConstraintRequest)ScenarioQueries.Namespaces.Where; + + using (Assert.EnterMultipleScope()) + { + Assert.That(where.Property, Is.EqualTo("@type")); + Assert.That(where.Operator, Is.EqualTo(PrimitiveConstraintRequestOperator.instanceOf)); + Assert.That(where.Value, Is.EqualTo((ConstraintValue[])["Namespace"])); + } + } + + [Test] + public void VerifyStored() + { + var query = ScenarioQueries.Stored; + var where = (CompositeConstraintRequest)query.Where; + + using (Assert.EnterMultipleScope()) + { + Assert.That(query.Name, Is.Not.Empty); + Assert.That(query.Description, Is.Not.Empty); + Assert.That(query.Alias, Is.Not.Empty); + Assert.That(where.Operator, Is.EqualTo(CompositeConstraintRequestOperator.or)); + Assert.That(where.Constraint.OfType().Select(nested => nested.Operator), Is.EqualTo((CompositeConstraintOperator[])[CompositeConstraintOperator.and]), "an and nested in the or"); + Assert.That(where.Constraint.OfType().Select(Describe), Is.EqualTo((string[][])[["@type equalto False [LiteralInteger]", "value greaterthan False [1]"]]), "the and holds the integer literals above 1"); + Assert.That(where.Constraint.OfType().Select(Describe), Is.EqualTo((string[])["@type in False [Dependency, LiteralRational]"]), "the or holds the dependencies and rational literals directly"); + Assert.That(ScenarioQueries.Stored, Is.Not.SameAs(query), "every read gives a new request"); + } + } + + [Test] + public void VerifyUpdated() + { + var where = (CompositeConstraintRequest)ScenarioQueries.Updated.Where; + + using (Assert.EnterMultipleScope()) + { + Assert.That(where.Operator, Is.EqualTo(CompositeConstraintRequestOperator.and)); + Assert.That(Describe(where), Is.EqualTo((string[])["@type equalto False [LiteralInteger]", "value lessthan True [2]", "value lessthanorequalto False [42]"]), "the lower bound is an inverted less than"); + } + } + + private static IEnumerable Describe(CompositeConstraintRequest where) => where.Constraint.OfType().Select(Describe); + + private static IEnumerable Describe(CompositeConstraint composite) => composite.Constraint.OfType().Select(Describe); + + private static string Describe(PrimitiveConstraint constraint) => $"{constraint.Property} {constraint.Operator} {constraint.Inverse} [{string.Join(", ", constraint.Value.Select(value => value.Match(() => "null", flag => flag.ToString(), number => number.ToString(CultureInfo.InvariantCulture), text => text, id => id.ToString())))}]"; + } +} diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index 3e7b17746..cb580b219 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -236,13 +236,28 @@ a step ignores itself only when the state it builds on is missing. The verdict a | 6 | **Branch, SysML structure** | **branch** `systems` from head (7, 6, 8); commits with `branchId`: definitions and usages, attributes, enumerations, occurrences, items, parts, ports (incl. conjugated), connections, interfaces, allocations, flows (31) | 15 with `branchId`; as step 2 on the branch | | 7 | **SysML behaviour and requirements** | actions (all node and loop kinds), states and transitions, calculations, constraints, requirements, concerns, cases, analysis / verification / use cases, views, viewpoints, renderings, metadata (58) | as step 6 | | 8 | **Merge** | update the same element on default and on `systems` → merge reports the conflict (`MergeConflictException`, `MergeResult.conflict`); merge again with a resolution body; then a clean merge of the remaining `systems` work; U1–U2 on SysML content after merge | 25, 24, 8 | -| 9 | **Queries** | `POST` a query with nested `CompositeConstraint` (`AND`, `OR`) and `PrimitiveConstraint`s using all 7 `Operator` literals and `inverse`; `select`, `scope`, `orderBy`; list, get, `PUT`, results three ways, at head and at the `kernel` commit; `DELETE` | 27, 26, 28, 29, 31, 32, 33, 30 | -| 10 | **Project usage** | second project `Library` with a small model; the main model commits a `ProjectUsage` of its head; `excludeUsed` on elements and roots | 2, 15, 21, 19, 22 | -| 11 | **External data** | commit `ExternalData` and `ExternalRelationship`, update both, delete both | 15, 17, 18 | +| 9 | **Queries** | `POST` a query with an `or` `CompositeConstraint` holding a nested `and` and `PrimitiveConstraint`s; across the step's queries all 7 `Operator` literals and `inverse`; `select`; list, get, `PUT`, results three ways, at the default head and at the `kernel` commit; negative cases; `DELETE` | 27, 26, 28, 29, 31, 32, 33, 30 | +| 10 | **Project usage** | second project `UsedLibrary` with a small model; **branch** `data` from the default head; a commit of a `ProjectUsage` of the library's commit; the project usage of a library element; `excludeUsed` on elements and roots | 2, 7, 15, 21, 19, 22 | +| 11 | **External data** | on `data`: commit `ExternalData` and an `ExternalRelationship` to the root package, update both, delete both | 15, 17, 18 | | 12 | **Delete model elements** | per metamodel package, delete the subjects with their owning memberships (`payload = null`), updating owners' `ownedRelationship` in the same commit; the deleted elements are gone at head and readable at the previous commit; `DiffAsync` shows `DELETED` | 15, 19, 20, 24 | -| 13 | **Tear down** | delete tag (13), branch (9), the `Library` project and the main project (5); each is unreadable afterwards; negative cases (§6.3) | 13, 9, 5, 3, 8, 12 | +| 13 | **Tear down** | delete tag (13), branch (9), the `UsedLibrary` project and the main project (5); each is unreadable afterwards; negative cases (§6.3) | 13, 9, 5, 3, 8, 12 | | 14 | **Coverage verdict** | — | asserts §7 | +Step 9's expected results are computed from the expected model with a predicate per query +(`Helpers/ScenarioQueries.cs`); every `@type` a query names is a metaclass that no other metaclass +specializes, so open question 1 does not change them. The PSM `QueryRequest` has only `select` and +`where`; `scope` and `orderBy` belong to the PIM `Query` alone. On `select` the specification +disagrees with itself: Systems Modeling API and Services, Clause 7.1.4, says `select` lists the +properties included for each `Data` object of the response, while the OpenAPI document declares +every result a complete `Data` item. The scenario follows the OpenAPI document, which Clause 2 ranks +first, so a result that keeps only the selected properties is the divergence +`QueryResultsProjected`; Flexo follows Clause 7.1.4. + +Steps 10 and 11 commit data that is no element. A client reads it back through the changes of its +commit (`VerifyDataCommitAsync`), since the element operations answer elements only. The steps +commit on their own branch `data`, so that the default branch, which steps 12 and 13 build on, +keeps a model of elements only. + Steps 6 and 7 follow the metamodel where the grammar differs from it (`ConjugatedPortTyping` has no `originalPortDefinition`). `validateSubjectMembershipOwningType` and `validateObjectiveMembershipOwningType` test the owning type with `oclIsType`, which, read @@ -324,7 +339,8 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen - `RootsIgnoreOwningRelationship`: the roots are every element without an `owningRelatedElement`, including the elements owned through their `owningRelationship` (step 2); - `UnknownResourceNotFound`, `UnknownResourceAccepted`: an unknown project answers 403 instead of - 404, and the relationships of an unknown element answer 200 (step 2); + 404, and the relationships of an unknown element answer 200 (step 2), as do the results of an + unknown query and an update of one, which creates it (step 9); - `ErrorWithoutErrorBody`: an error answer carries an empty or `text/plain` body, never an `application/json` `Error` (steps 1, 2); - `CreatedAnsweredOk`: `POST /projects` and `POST …/commits` answer 200 instead of 201 (step 2); @@ -343,7 +359,21 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen - `MergeNotImplemented`: merge answers 501 Not Implemented (step 8); - `MergeRequiresArrayBody`: merge reads its optional body as a required array, so a merge without a body answers 500 and one with a `null` body 400, before the 501 (step 8). Step 8 then sends - the resolution merge, whose body is an array, and stops at its 501. + the resolution merge, whose body is an array, and stops at its 501; +- `QueryLosesNameAndDescription`: a query is stored without its `name`, `alias` and `description` + (step 9); +- `QueryResultsProjected`: query results keep only the properties in `select`, as Clause 7.1.4 + says and the OpenAPI document does not allow, leaving out `@type`, so the client cannot read them + (step 9); +- `InstanceOfRejected`: a `PrimitiveConstraint` with the `instanceOf` operator answers 400 (step 9); +- `QueryResultsGetNotImplemented`: `GET /projects/{projectId}/query-results` answers 501 (step 9); +- `DataListedAsElements`: the elements and roots of a commit include its project usages, external + data and external relationships, so the client cannot read the list (steps 10, 11); +- `ProjectUsageAsArray`: the project usage of an element is answered as an array of every project + usage of the commit, whatever the element, so the client cannot read it (step 10). + +The conformance check reports an item of a list whose `@type` is none of the types the schema +admits at that item, so such an item cannot hide behind the errors of the other items. Not a divergence from the specification, but it sets the run time: layer1's requests to the quad store slow down during a run, from a few milliseconds to hundreds, while the quad store stays fast @@ -364,6 +394,10 @@ Client defects found so far, each red until fixed: - #429 — `MergeAsync` sends its resolution elements without the derived properties that the `Data` schema of the merge body requires (step 8). +#425 also covers the `inverse: null` of a `PrimitiveConstraintRequest` that leaves `inverse` unset; +Flexo answers such a request 400. Step 9 sets `inverse` on every query but one, the query +definition sent with `GET`, so that #425 stays visible there while the other query operations run. + SDK defects found while building the fixture, outside the client: - #426 — the generated comparers treat equal floating-point values as different, so a @@ -380,7 +414,7 @@ SDK defects found while building the fixture, outside the client: ## 9. Open questions 1. **Query by `@type` and subtypes** — Flexo matches subtypes; check whether the spec requires it. -2. **ProjectUsage / ExternalData / ExternalRelationship on Flexo** — stored generically, untested. +2. **ProjectUsage / ExternalData / ExternalRelationship on Flexo** — answered: stored and read back through the changes as sent, but listed as elements (`DataListedAsElements`, step 10). 3. **Flexo image** — decided: the `develop` build pinned by digest (§3.1). 4. **CI** — local only (recommended for now), or a separate opt-in workflow. 5. **One `[Test]` per step vs `TESTING.md` §2** — decided: in the scope of this integration test, going against the rules of `TESTING.md` is accepted. One scenario is split into one `[Test]` per step, and the order is set with `[DependsOnTest(…, AllowFailure = true)]` (§5). diff --git a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs index 660364225..e76cf1a56 100644 --- a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs +++ b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs @@ -24,6 +24,7 @@ namespace SySML2.NET.REST.Tests.IntegrationTests using SySML2.NET.REST.Tests.Helpers; using SySML2.NET.REST.Tests.Helpers.Models; + using SysML2.NET.Common; using SysML2.NET.Core.DTO.Root.Elements; using SysML2.NET.PSM; using SysML2.NET.PSM.DTO; @@ -401,6 +402,163 @@ public async Task VerifyMerge() [Test] [DependsOnTest(nameof(VerifyMerge), AllowFailure = true)] + public async Task VerifyQueries() + { + if (this.rootModel == null || this.state.HeadCommitId == null || !this.state.TagIds.ContainsKey("kernel")) + { + Assert.Ignore("the default branch has no model or no kernel tag to query"); + } + + var projectId = this.state.ProjectId!.Value; + var head = this.state.HeadCommitId.Value; + var model = this.state.ExpectedModels[head]; + var rootName = model.Single(element => element.Id == this.rootModel.Root.Id).DeclaredName; + var kernelCommit = (await this.client.GetTagByProjectAndIdAsync(projectId, this.state.TagIds["kernel"])).TaggedCommit; + var atKernel = this.state.ExpectedModels[kernelCommit]; + + using (Assert.EnterMultipleScope()) + { + var stored = ScenarioQueries.Stored; + var created = await this.client.PostQueryByProjectAsync(projectId, stored); + + Assert.That(created.Id, Is.Not.EqualTo(Guid.Empty)); + ReadBackAssertions.VerifyQueryRecord(created, stored, projectId, "the created query"); + + var read = await this.client.GetQueryByProjectAndIdAsync(projectId, created.Id); + + Assert.That(read.Id, Is.EqualTo(created.Id)); + ReadBackAssertions.VerifyQueryRecord(read, stored, projectId, "the query read by id"); + + var (queries, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetQueriesByProjectAsync(projectId, parameters)); + + Assert.That(queries.Select(query => query.Id), Is.EquivalentTo((Guid[])[created.Id])); + + await this.readBack.VerifyResultsAsync("the results of the stored query at the default head", parameters => this.client.GetQueryResultsByProjectIdQueryIdAsync(projectId, created.Id, queryParameters: parameters), [.. model.Where(ScenarioQueries.IsStoredResult)]); + await this.readBack.VerifyResultsAsync("the results of the stored query at the kernel commit", parameters => this.client.GetQueryResultsByProjectIdQueryIdAsync(projectId, created.Id, kernelCommit, parameters), [.. atKernel.Where(ScenarioQueries.IsStoredResult)]); + + var updatedRequest = ScenarioQueries.Updated; + var updated = await this.client.PutQueryByProjectAndIdAsync(projectId, created.Id, updatedRequest); + + Assert.That(updated.Id, Is.EqualTo(created.Id)); + ReadBackAssertions.VerifyQueryRecord(updated, updatedRequest, projectId, "the updated query"); + + await this.readBack.VerifyResultsAsync("the results of the updated query", parameters => this.client.GetQueryResultsByProjectIdQueryIdAsync(projectId, created.Id, head, parameters), [.. model.Where(ScenarioQueries.IsUpdatedResult)]); + await this.readBack.VerifyResultsAsync("the results of a query definition sent with POST, at the kernel commit", parameters => this.client.GetQueryResultsByProjectIdQueryPostAsync(projectId, ScenarioQueries.AtLeast42, kernelCommit, parameters), [.. atKernel.Where(ScenarioQueries.IsAtLeast42)]); + await this.readBack.VerifyResultsAsync("the results of a query definition that selects the id and name", parameters => this.client.GetQueryResultsByProjectIdQueryPostAsync(projectId, ScenarioQueries.Named(rootName), head, parameters), [.. model.Where(element => element.DeclaredName == rootName)]); + + try + { + var (namespaces, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetQueryResultsByProjectIdQueryPostAsync(projectId, ScenarioQueries.Namespaces, head, parameters)); + + Assert.That(namespaces.Select(result => result.Id), Is.EquivalentTo(model.Where(ScenarioQueries.IsNamespace).Select(element => element.Id)), "the results of instanceOf Namespace"); + } + catch (PsmApiException exception) when (exception.StatusCode == HttpStatusCode.BadRequest) + { + KnownServerDivergences.Report(KnownServerDivergences.InstanceOfRejected, "the query definition of the namespaces answered 400"); + } + + try + { + var (named, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetQueryResultsByProjectIdQueryAsync(projectId, ScenarioQueries.NamedWithoutInverse(rootName), head, parameters)); + + Assert.That(named.Select(result => result.Id), Is.EquivalentTo(model.Where(element => element.DeclaredName == rootName).Select(element => element.Id)), "the results of a query definition sent with GET"); + } + catch (PsmApiException exception) when (exception.StatusCode == HttpStatusCode.NotImplemented) + { + KnownServerDivergences.Report(KnownServerDivergences.QueryResultsGetNotImplemented, "GetQueryResultsByProjectIdQueryAsync answered 501"); + } + + var unknown = Guid.NewGuid(); + + await this.ExpectNotFoundAsync(() => this.client.GetQueryByProjectAndIdAsync(projectId, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetQueriesByProjectAsync(unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetQueryResultsByProjectIdQueryIdAsync(projectId, unknown), KnownServerDivergences.UnknownResourceAccepted); + await this.ExpectNotFoundAsync(() => this.client.PutQueryByProjectAndIdAsync(projectId, unknown, ScenarioQueries.Updated), KnownServerDivergences.UnknownResourceAccepted); + await this.ExpectNotFoundAsync(() => this.client.GetQueryResultsByProjectIdQueryPostAsync(unknown, ScenarioQueries.AtLeast42)); + + var deleted = await this.client.DeleteQueryByProjectAndIdAsync(projectId, created.Id); + + Assert.That(deleted.Id, Is.EqualTo(created.Id)); + + await this.ExpectNotFoundAsync(() => this.client.GetQueryByProjectAndIdAsync(projectId, created.Id)); + await this.ExpectNotFoundAsync(() => this.client.DeleteQueryByProjectAndIdAsync(projectId, created.Id)); + } + } + + [Test] + [DependsOnTest(nameof(VerifyQueries), AllowFailure = true)] + public async Task VerifyProjectUsage() + { + if (this.rootModel == null || this.state.HeadCommitId == null) + { + Assert.Ignore("the default branch has no commit to branch from"); + } + + var projectId = this.state.ProjectId!.Value; + var head = this.state.HeadCommitId.Value; + var own = this.state.ExpectedModels[head]; + + var library = await this.client.PostProjectAsync(new ProjectRequest { Name = "UsedLibrary", Description = "The project that the model of the scenario uses" }); + this.state.LibraryProjectId = library.Id; + + var libraryModel = new LibraryModel(); + var libraryElements = libraryModel.Builder.ToDtos(); + var libraryCommit = await this.client.PostCommitByProjectAsync(library.Id, ModelBuilder.ToCommitRequest(libraryElements, "The used library"), library.DefaultBranch); + + var branch = await this.client.PostBranchByProjectAsync(projectId, new BranchRequest { Name = "data", Description = "The project usage and external data of steps 10 and 11", Head = head }); + this.state.BranchIds["data"] = branch.Id; + this.state.BranchHeads[branch.Id] = head; + + var usage = new ProjectUsage { Id = DeterministicGuid.Create("data/usage"), UsedProject = library.Id, UsedCommit = libraryCommit.Id }; + var committed = await this.CommitDataAsync([(usage.Id, new ProjectUsageRequest { Id = usage.Id, UsedProject = usage.UsedProject, UsedCommit = usage.UsedCommit })], "A usage of the library", branch.Id); + + using (Assert.EnterMultipleScope()) + { + await this.readBack.VerifyDataCommitAsync(committed.Commit, branch.Id, committed.PreviousHead, [(usage.Id, usage)]); + await this.readBack.VerifyProjectUsageAsync(committed.Commit.Id, libraryModel.Used.Id, usage); + + await this.ExpectNotFoundAsync(() => this.client.GetProjectUsageByProjectCommitElementAsync(Guid.NewGuid(), committed.Commit.Id, libraryModel.Used.Id)); + + await this.readBack.VerifyElementIdsAsync("the elements with the used ones", parameters => this.client.GetElementsByProjectCommitAsync(projectId, committed.Commit.Id, false, parameters), [.. own.Concat(libraryElements).Select(element => element.Id)]); + await this.readBack.VerifyElementIdsAsync("the elements without the used ones", parameters => this.client.GetElementsByProjectCommitAsync(projectId, committed.Commit.Id, true, parameters), [.. own.Select(element => element.Id)]); + await this.readBack.VerifyRootsAsync("the roots without the used ones", parameters => this.client.GetRootsByProjectCommitAsync(projectId, committed.Commit.Id, true, parameters), own); + } + } + + [Test] + [DependsOnTest(nameof(VerifyProjectUsage), AllowFailure = true)] + public async Task VerifyExternalData() + { + if (this.rootModel == null || !this.state.BranchIds.ContainsKey("data")) + { + Assert.Ignore("step 10 created no branch for the external data"); + } + + var branch = this.state.BranchIds["data"]; + var data = new ExternalData { Id = DeterministicGuid.Create("data/external"), ResourceIdentifier = new Uri("https://example.org/requirements/R-1") }; + var relationship = new ExternalRelationship { Id = DeterministicGuid.Create("data/external relationship"), ElementEnd = this.rootModel.Root.Id, ExternalDataEnd = data.Id, Language = "text", Specification = "traces to R-1" }; + + var created = await this.CommitDataAsync([(data.Id, Request(data)), (relationship.Id, Request(relationship))], "External data", branch); + + var changedData = new ExternalData { Id = data.Id, ResourceIdentifier = new Uri("https://example.org/requirements/R-2") }; + var changedRelationship = new ExternalRelationship { Id = relationship.Id, ElementEnd = relationship.ElementEnd, ExternalDataEnd = data.Id, Language = "natural", Specification = "Traces to the second requirement" }; + + using (Assert.EnterMultipleScope()) + { + await this.readBack.VerifyDataCommitAsync(created.Commit, branch, created.PreviousHead, [(data.Id, data), (relationship.Id, relationship)]); + + var changed = await this.CommitDataAsync([(data.Id, Request(changedData)), (relationship.Id, Request(changedRelationship))], "Changed external data", branch); + + await this.readBack.VerifyDataCommitAsync(changed.Commit, branch, changed.PreviousHead, [(data.Id, changedData), (relationship.Id, changedRelationship)]); + + var deleted = await this.CommitDataAsync([(data.Id, null), (relationship.Id, null)], "Deleted external data", branch); + + await this.readBack.VerifyDataCommitAsync(deleted.Commit, branch, deleted.PreviousHead, [(data.Id, null), (relationship.Id, null)]); + } + } + + [Test] + [DependsOnTest(nameof(VerifyExternalData), AllowFailure = true)] public async Task VerifyCoverage() { var verdict = new CoverageVerdict(this.state.ReadBack, this.httpClientFactory.Recorder.Calls, this.openApi); @@ -432,6 +590,22 @@ private static async Task ExpectClientErrorAsync(Func call, [CallerArgumen private static IReadOnlyList Replace(IReadOnlyList model, IElement replacement) => [.. model.Select(element => element.Id == replacement.Id ? replacement : element)]; + private static ExternalDataRequest Request(ExternalData data) => new() { Id = data.Id, ResourceIdentifier = data.ResourceIdentifier }; + + private static ExternalRelationshipRequest Request(ExternalRelationship relationship) => new() { Id = relationship.Id, ElementEnd = relationship.ElementEnd, ExternalDataEnd = relationship.ExternalDataEnd, Language = relationship.Language, Specification = relationship.Specification }; + + private async Task<(Commit Commit, Guid PreviousHead)> CommitDataAsync(IReadOnlyList<(Guid Id, IDataRequest Payload)> change, string description, Guid branch) + { + var previousHead = this.state.BranchHeads[branch]; + + var commit = await this.client.PostCommitByProjectAsync(this.state.ProjectId!.Value, new CommitRequest { Description = description, Change = [.. change.Select(entry => new DataVersionRequest { Identity = new DataIdentityRequest { Id = entry.Id }, Payload = entry.Payload })] }, branch); + + this.state.BranchHeads[branch] = commit.Id; + this.state.ExpectedModels[commit.Id] = this.state.ExpectedModels[previousHead]; + + return (commit, previousHead); + } + private async Task<(Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead, Guid BranchId)> CommitElementsAsync(IReadOnlyList model, IReadOnlyList changed, string description, Guid branch) { Guid? previousHead = this.state.BranchHeads.TryGetValue(branch, out var head) ? head : null; diff --git a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md index a9288f894..825c11f68 100644 --- a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md +++ b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md @@ -28,7 +28,8 @@ SySML2.NET.REST.Tests/ │ ├── KernelModel.cs step 4: KerML Kernel │ ├── KerMLUpdateModel.cs step 5: updates U1–U4 of steps 2–4 │ ├── SystemsStructureModel.cs step 6: SysML structure, on the branch systems -│ └── SystemsBehaviorModel.cs step 7: SysML behaviour, requirements, cases and views +│ ├── SystemsBehaviorModel.cs step 7: SysML behaviour, requirements, cases and views +│ └── LibraryModel.cs step 10: the model of the project that the main model uses ├── HelpersTests/ offline: one fixture per helper, mirroring Helpers/ │ ├── FlexoJwtTestFixture.cs, ModelBuilderTestFixture.cs, … │ └── Models/ one fixture per model class @@ -100,15 +101,16 @@ Session → PsmApiClient → HttpClient | Type | Responsibility | |---|---| | `ModelBuilder` | Holds the whole model across the steps: each step starts its own scope (`BeginStep`) and creates POCOs with deterministic ids, wired with `AssignOwnership`. It converts them with the Dal's `ToDto(includeDerivedProperties: true)`, `Changed` selects the delta a commit sends, `Copy` copies a DTO for a change outside the builder, and `Find` looks an element up by its scoped name. An element whose derived values cannot be computed without the model library is converted without them and listed in `WithoutDerivedValues`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | +| `ScenarioQueries` | The queries of step 9, each with a predicate that picks its results from the expected model. | | `DeterministicGuid` | Name-based UUID v5 of `"/"`, so the elements have the same ids in every run. | -| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5), `SystemsStructureModel` (step 6), `SystemsBehaviorModel` (step 7). The base class holds the helpers the steps share: naming, ownership, features, parameters, results, literals and multiplicities. | +| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5), `SystemsStructureModel` (step 6), `SystemsBehaviorModel` (step 7), `LibraryModel` (step 10, in a second project). The base class holds the helpers the steps share: naming, ownership, features, parameters, results, literals and multiplicities. | ### 5. Checking what came back | Type | Responsibility | |---|---| -| `ScenarioState` | What the steps hand on to each other: the ids the server assigned (project, branches, commits), the head of every branch the scenario committed on, the expected model at each commit, and everything the server returned. | -| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Lists are read in pages of 100, and paging is checked on the first three pages of 10. One changed element of each metaclass is read by id, four reads at a time. Every read is guarded: a read that throws fails, or warns when its own response shows a known divergence that breaks deserialization. | +| `ScenarioState` | What the steps hand on to each other: the ids the server assigned (projects, branches, tags, commits), the head of every branch the scenario committed on, the expected model at each commit, and everything the server returned. | +| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Lists are read in pages of 100, and paging is checked on the first three pages of 10. A commit of project usages or external data is checked through its changes, the way a client reads such data back; query results and project usages have their own checks. One changed element of each metaclass is read by id, four reads at a time. Every read is guarded: a read that throws fails, or warns when its own response shows a known divergence that breaks deserialization. | | `KnownServerDivergences`, `ServerDivergence` | The named ways Flexo diverges from the specification, each with a reference: an upstream issue, or a Flexo source location at the pinned commit. A divergence can explain response violations. `Report` raises an `Assert.Warn`. `ExpectNotFoundAsync` expects a 404, tolerates one named divergence, and fails when a conforming 404 reaches the caller without its `Error`. | | `IsolatedAssertions` | Runs a check in an isolated NUnit context and returns its failures and warnings, without failing the calling test. The offline fixtures use it to prove that a check fails when it should. | @@ -143,7 +145,10 @@ Having one `[Test]` per step goes against the one-test-per-method rule in `TESTI | 6 | `VerifySystemsStructure` | implemented, on the branch `systems` | | 7 | `VerifySystemsBehavior` | implemented, on the branch `systems` | | 8 | `VerifyMerge` | implemented: a conflict, its resolution, and a clean merge into the default branch | -| 9–13 | see plan §5 | planned | +| 9 | `VerifyQueries` | implemented | +| 10 | `VerifyProjectUsage` | implemented, on the branch `data` | +| 11 | `VerifyExternalData` | implemented, on the branch `data` | +| 12–13 | see plan §5 | planned | | 14 | `VerifyCoverage` | implemented, red by design | ### Reading the outcome From f7f015b70acf053dfea81d69d1cbc395a069332f Mon Sep 17 00:00:00 2001 From: samatstarion Date: Mon, 9 Nov 2026 09:45:03 +0100 Subject: [PATCH 08/11] =?UTF-8?q?[Add]=20Flexo=20integration=20scenario=20?= =?UTF-8?q?stage=205:=20delete=20and=20teardown=20steps=2012=E2=80=9313=20?= =?UTF-8?q?(#407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Helpers/KnownServerDivergences.cs | 33 +++- SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs | 46 +++++ .../Helpers/Models/DeletionModel.cs | 105 +++++++++++ .../Helpers/ReadBackAssertions.cs | 99 +++++++++- .../KnownServerDivergencesTestFixture.cs | 8 +- .../HelpersTests/ModelBuilderTestFixture.cs | 23 +++ .../Models/DeletionModelTestFixture.cs | 52 ++++++ .../ReadBackAssertionsTestFixture.cs | 113 ++++++++++++ .../INTEGRATION_TEST_PLAN.md | 23 ++- .../FlexoModelScenarioTestFixture.cs | 169 +++++++++++++++++- .../TEST_PROJECT_STRUCTURE.md | 12 +- 11 files changed, 660 insertions(+), 23 deletions(-) create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/DeletionModel.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/DeletionModelTestFixture.cs diff --git a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs index e07f5d2b9..345cb9dea 100644 --- a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs +++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs @@ -87,7 +87,7 @@ public static class KnownServerDivergences /// Gets the divergence that a request naming an unknown resource succeeds, where the OpenAPI document declares /// 404 Not Found for it /// - public static ServerDivergence UnknownResourceAccepted { get; } = new("a request naming an unknown resource succeeds instead of answering 404 Not Found", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/RelationshipApi.kt, and QueryApi.kt, whose PUT creates a missing query"); + public static ServerDivergence UnknownResourceAccepted { get; } = new("a request naming an unknown resource succeeds instead of answering 404 Not Found", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/RelationshipApi.kt; QueryApi.kt, whose PUT creates a missing query; and the tag and branch delete routes, which delete a deleted tag or branch again"); /// /// Gets the divergence that an error answer carries an empty or plain-text body, where the OpenAPI document @@ -202,10 +202,28 @@ public static class KnownServerDivergences /// public static ServerDivergence QueryResultsGetNotImplemented { get; } = new("GET /projects/{projectId}/query-results answers 501 Not Implemented", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/QueryApi.kt"); + /// + /// Gets the divergence that deleting an element leaves what it owns in place, where its owned relationships and + /// their owned related elements are composite in KerML + /// + public static ServerDivergence DeleteDoesNotCascade { get; } = new("deleting an element leaves the elements it owns, through its owned relationships, in the model, and lists those that referenced it as changes of the commit, with the reference removed", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/CommitApi.kt, a deletion removes the listed subjects and the references to them only"); + + /// + /// Gets the divergence that deleting an unknown branch fails on the server, where the OpenAPI document declares + /// 404 Not Found + /// + public static ServerDivergence DeleteUnknownBranchFails { get; } = new("DELETE /projects/{projectId}/branches/{branchId} of an unknown branch answers 500 Internal Server Error", $"{FlexoRevision}, layer1 ServerBugException on the branch delete transaction"); + + /// + /// Gets the divergence that deleting a deleted project succeeds again, where the project no longer exists and + /// the OpenAPI document leaves the client error to its default response + /// + public static ServerDivergence DeletedProjectDeletedAgain { get; } = new("DELETE /projects/{projectId} of a deleted project succeeds instead of answering a client error", $"{FlexoRevision}, observed on DELETE /projects/{{projectId}}"); + /// /// Gets every known divergence /// - public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, MergeNotImplemented, MergeRequiresArrayBody, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri, DataListedAsElements, ProjectUsageAsArray, QueryResultsProjected, QueryLosesNameAndDescription, InstanceOfRejected, QueryResultsGetNotImplemented]; + public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, MergeNotImplemented, MergeRequiresArrayBody, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri, DataListedAsElements, ProjectUsageAsArray, QueryResultsProjected, QueryLosesNameAndDescription, InstanceOfRejected, QueryResultsGetNotImplemented, DeleteDoesNotCascade, DeleteUnknownBranchFails, DeletedProjectDeletedAgain]; /// /// Asserts that a call for an unknown resource fails with 404 Not Found, or reports the one tolerated divergence @@ -222,8 +240,8 @@ public static class KnownServerDivergences /// Gets the call that the recorded last, or null /// /// - /// The divergence the call may show, either or - /// , or null to tolerate none + /// The divergence the call may show, , + /// or , or null to tolerate none /// /// /// The description of the call in assertion messages @@ -244,7 +262,12 @@ public static async Task ExpectNotFoundAsync(Func call, Func failure = exception; } - var tolerates = tolerated == UnknownResourceAccepted ? failure == null : failure is { StatusCode: not HttpStatusCode.NotFound } && (int)failure.StatusCode is >= 400 and < 500; + var tolerates = tolerated switch + { + _ when tolerated == UnknownResourceAccepted => failure == null, + _ when tolerated == DeleteUnknownBranchFails => failure is { StatusCode: HttpStatusCode.InternalServerError }, + _ => failure is { StatusCode: not HttpStatusCode.NotFound } && (int)failure.StatusCode is >= 400 and < 500 + }; if (tolerated != null && tolerates) { diff --git a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs index 440a1f8a8..d0e9958db 100644 --- a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs +++ b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs @@ -19,6 +19,7 @@ namespace SySML2.NET.REST.Tests.Helpers using SysML2.NET.PSM.DTO; using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using DtoRelationship = SysML2.NET.Core.DTO.Root.Elements.IRelationship; using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; /// @@ -121,6 +122,51 @@ public static TElement Copy(TElement dto) where TElement : DtoElement return (TElement)Detach((DtoElement)CopyMethod.Invoke(dto, null)); } + /// + /// Finds the elements that an element owns, directly or indirectly, through its owned relationships and their + /// owned related elements, both composite in KerML + /// + /// + /// The model + /// + /// + /// The owning element + /// + /// + /// The owned elements, without the owner + /// + public static IReadOnlyList OwnedTree(IReadOnlyList model, Guid ownerId) + { + ArgumentNullException.ThrowIfNull(model); + + var byId = model.ToDictionary(element => element.Id); + var found = new List(); + var visited = new HashSet { ownerId }; + var pending = new Queue([ownerId]); + + while (pending.Count > 0) + { + if (!byId.TryGetValue(pending.Dequeue(), out var element)) + { + continue; + } + + IEnumerable owned = element is DtoRelationship relationship ? [.. element.OwnedRelationship, .. relationship.OwnedRelatedElement] : element.OwnedRelationship; + + foreach (var id in owned.Where(visited.Add)) + { + pending.Enqueue(id); + + if (byId.TryGetValue(id, out var child)) + { + found.Add(child); + } + } + } + + return found; + } + /// /// Creates the commit request that creates or replaces the given elements /// diff --git a/SySML2.NET.REST.Tests/Helpers/Models/DeletionModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/DeletionModel.cs new file mode 100644 index 000000000..b2c146715 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/DeletionModel.cs @@ -0,0 +1,105 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Core.POCO.Root.Annotations; + using SysML2.NET.Dal; + + /// + /// The model of scenario step 12: content in the root package that the step deletes again, built for its three + /// deletion cases so that no element of an earlier step loses a reference + /// + /// + /// + /// package <del> Deletions { + /// package <sgl> Single; // D1: deleted with its owning membership + /// package <emp> Emptied { package First; package Second; } // D2: its whole content deleted + /// package <cas> Cascade { // D3: deleted alone, owning the rest + /// package Inner { comment Note /* Deleted with Cascade. */ } + /// } + /// } + /// + /// + public sealed class DeletionModel : StepModel + { + /// + /// Initializes a new instance of the class and builds the model + /// + /// + /// The model of step 2, whose root package owns the content + /// + public DeletionModel(RootModel root) : base((root ?? throw new ArgumentNullException(nameof(root))).Builder, "deletion") + { + this.Package = this.CreateNamed("Deletions", "del", PackageExtensions.ToDto); + this.OwnMember(root.Root, this.Package); + + this.Single = this.CreateNamed("Single", "sgl", PackageExtensions.ToDto); + this.OwnMember(this.Package, this.Single); + + this.Emptied = this.CreateNamed("Emptied", "emp", PackageExtensions.ToDto); + this.OwnMember(this.Package, this.Emptied); + this.First = this.CreateNamed("First", "fst", PackageExtensions.ToDto); + this.OwnMember(this.Emptied, this.First); + this.Second = this.CreateNamed("Second", "snd", PackageExtensions.ToDto); + this.OwnMember(this.Emptied, this.Second); + + this.Cascade = this.CreateNamed("Cascade", "cas", PackageExtensions.ToDto); + this.OwnMember(this.Package, this.Cascade); + this.Inner = this.CreateNamed("Inner", "inr", PackageExtensions.ToDto); + this.OwnMember(this.Cascade, this.Inner); + this.Note = this.CreateNamed("Note", "nte", CommentExtensions.ToDto); + this.Note.Body = "Deleted with Cascade."; + this.OwnMember(this.Inner, this.Note); + } + + /// + /// Gets the package that holds the content to delete + /// + public Package Package { get; } + + /// + /// Gets the package that case D1 deletes with its owning membership + /// + public Package Single { get; } + + /// + /// Gets the package whose whole content case D2 deletes + /// + public Package Emptied { get; } + + /// + /// Gets the first member of + /// + public Package First { get; } + + /// + /// Gets the second member of + /// + public Package Second { get; } + + /// + /// Gets the package that case D3 deletes alone, so that the deletion must cascade to what it owns + /// + public Package Cascade { get; } + + /// + /// Gets the package that owns + /// + public Package Inner { get; } + + /// + /// Gets the comment that owns + /// + public Comment Note { get; } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs index 9c5d34a3b..053d579bd 100644 --- a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs +++ b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs @@ -161,6 +161,62 @@ public static void VerifyQueryRecord(Query query, QueryRequest sent, Guid projec Assert.That(query.Alias, Is.EqualTo(sent.Alias), $"{description} has the aliases that were sent"); } + /// + /// Verifies that deleting an element deleted what it owns: none of the owned elements is listed or readable at + /// the commit, or, as the known divergence , all of + /// them are still listed and nothing else differs + /// + /// + /// The commit that deleted the owner + /// + /// + /// The elements the deleted owner owned, directly or indirectly, that the commit did not list + /// + /// + /// The model expected at , without the owned elements + /// + /// + /// An awaitable + /// + public async Task VerifyCascadeAsync(Guid commitId, IReadOnlyList owned, IReadOnlyList expected) + { + var projectId = this.state.ProjectId!.Value; + var (listed, _) = await this.ReadAsync(() => ReadAllPagesAsync(parameters => this.client.GetElementsByProjectCommitAsync(projectId, commitId, queryParameters: parameters)), "GetElementsByProjectCommitAsync after the cascading delete"); + + if (listed == null) + { + return; + } + + var listedIds = listed.Select(element => element.Id).ToHashSet(); + var expectedIds = expected.Select(element => element.Id).ToHashSet(); + + if (owned.Count > 0 && owned.All(element => listedIds.Contains(element.Id)) && listedIds.SetEquals(expectedIds.Union(owned.Select(element => element.Id)))) + { + KnownServerDivergences.Report(KnownServerDivergences.DeleteDoesNotCascade, $"the {owned.Count} elements the deleted element owned are still listed"); + return; + } + + using (Assert.EnterMultipleScope()) + { + Assert.That(listedIds, Is.EquivalentTo(expectedIds), "deleting an element deletes what it owns"); + + foreach (var element in owned) + { + var description = $"reading {element.GetType().Name} {element.Id}, owned by the deleted element"; + + try + { + await KnownServerDivergences.ExpectNotFoundAsync(() => this.client.GetElementByProjectCommitIdAsync(projectId, commitId, element.Id), () => this.recordedCalls?.Invoke().LastOrDefault(), null, description); + } + catch (Exception exception) when (exception is not ResultStateException) + { + this.ReportFailedRead(description, exception, (this.recordedCalls?.Invoke() ?? []).TakeLast(1)); + } + } + } + } + /// /// Verifies a commit on a branch: the commit itself, its place in the history, the branch head and its changes /// @@ -247,10 +303,14 @@ public async Task VerifyCommitAsync(Commit commit, Guid branchId, Guid? previous /// /// Per data item, its id and the payload the commit sent, or null when the commit deletes it /// + /// + /// The ids of the elements that the commit deletes with their owner, which may also be listed as deleted; none + /// when null + /// /// /// An awaitable /// - public async Task VerifyDataCommitAsync(Commit commit, Guid branchId, Guid? previousCommitId, IReadOnlyList<(Guid Id, IData Payload)> expected) + public async Task VerifyDataCommitAsync(Commit commit, Guid branchId, Guid? previousCommitId, IReadOnlyList<(Guid Id, IData Payload)> expected, IReadOnlyCollection cascaded = null) { var projectId = this.state.ProjectId!.Value; @@ -265,7 +325,15 @@ public async Task VerifyDataCommitAsync(Commit commit, Guid branchId, Guid? prev return; } - Assert.That(changes.Select(change => change.Identity?.Id), Is.EquivalentTo(expected.Select(entry => (Guid?)entry.Id)), "one change per data item"); + var cascadedChanges = changes.Where(change => change.Identity != null && (cascaded ?? []).Contains(change.Identity.Id) && expected.All(entry => entry.Id != change.Identity.Id)).ToList(); + var edited = cascadedChanges.Count(change => change.Payload != null); + + if (edited > 0) + { + KnownServerDivergences.Report(KnownServerDivergences.DeleteDoesNotCascade, $"the commit also lists {edited} element(s) owned by the deleted element as changed"); + } + + Assert.That(changes.Select(change => change.Identity?.Id), Is.EquivalentTo(expected.Select(entry => (Guid?)entry.Id).Concat(cascadedChanges.Select(change => (Guid?)change.Identity.Id))), "one change per data item"); var changesById = changes.Where(change => change.Identity != null).GroupBy(change => change.Identity.Id).ToDictionary(group => group.Key, group => group.First()); @@ -296,11 +364,21 @@ public async Task VerifyDataCommitAsync(Commit commit, Guid branchId, Guid? prev /// /// The elements created or changed between the two commits /// + /// + /// The ids of the elements deleted between the two commits, none when null + /// + /// + /// The ids of the elements deleted with their deleted owner, none when null + /// /// /// An awaitable /// - public async Task VerifyDiffAsync(Guid baseCommitId, Guid compareCommitId, IReadOnlyList changed) + public async Task VerifyDiffAsync(Guid baseCommitId, Guid compareCommitId, IReadOnlyList changed, IReadOnlyCollection deleted = null, IReadOnlyCollection cascaded = null) { + static Guid? IdOf(DataDifference difference) => (difference.CompareData ?? difference.BaseData)?.Identity?.Id; + + static bool IsDeletion(DataDifference difference) => difference.BaseData != null && difference.CompareData == null; + var projectId = this.state.ProjectId!.Value; var notImplemented = false; @@ -332,9 +410,22 @@ public async Task VerifyDiffAsync(Guid baseCommitId, Guid compareCommitId, IRead var atBase = this.state.ExpectedModels[baseCommitId].Select(element => element.Id).ToHashSet(); var compared = differences.Where(difference => difference.CompareData?.Identity != null).ToList(); + var cascadedIds = (cascaded ?? []).ToHashSet(); + var cascadedDifferences = differences.Where(difference => IdOf(difference) is { } id && cascadedIds.Contains(id)).ToList(); Assert.That(differences, Has.None.Matches(difference => (difference.CompareData ?? difference.BaseData)?.Identity == null), "a difference names the data it is about"); - Assert.That(differences.Select(difference => (difference.CompareData ?? difference.BaseData)?.Identity?.Id), Is.EquivalentTo(changed.Select(element => (Guid?)element.Id))); + Assert.That(differences.Select(IdOf), Is.EquivalentTo(changed.Select(element => (Guid?)element.Id).Concat((deleted ?? []).Select(id => (Guid?)id)).Concat(cascadedDifferences.Select(IdOf)))); + Assert.That(differences.Where(difference => (deleted ?? []).Contains(IdOf(difference) ?? Guid.Empty)), Has.All.Matches(IsDeletion), "a deleted element is DELETED"); + + if (cascadedIds.Count > 0 && !cascadedDifferences.Exists(IsDeletion)) + { + KnownServerDivergences.Report(KnownServerDivergences.DeleteDoesNotCascade, $"the diff shows none of the {cascadedIds.Count} elements the deleted element owned as DELETED"); + } + else + { + Assert.That(cascadedDifferences.Where(IsDeletion).Select(IdOf), Is.EquivalentTo(cascadedIds.Select(id => (Guid?)id)), "an element deleted with its owner is DELETED"); + } + Assert.That(compared.Where(difference => atBase.Contains(difference.CompareData.Identity.Id)), Has.All.Matches(difference => difference.BaseData != null), "an element of the base commit is UPDATED"); Assert.That(compared.Where(difference => !atBase.Contains(difference.CompareData.Identity.Id)), Has.All.Matches(difference => difference.BaseData == null), "an element added since is CREATED"); } diff --git a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs index f8abb9f2a..2d3c731b3 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs @@ -36,7 +36,7 @@ public void VerifyAll() { using (Assert.EnterMultipleScope()) { - Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.DiffNotImplemented, KnownServerDivergences.MergeNotImplemented, KnownServerDivergences.MergeRequiresArrayBody, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri, KnownServerDivergences.DataListedAsElements, KnownServerDivergences.ProjectUsageAsArray, KnownServerDivergences.QueryResultsProjected, KnownServerDivergences.QueryLosesNameAndDescription, KnownServerDivergences.InstanceOfRejected, KnownServerDivergences.QueryResultsGetNotImplemented])); + Assert.That(KnownServerDivergences.All, Is.EquivalentTo((ServerDivergence[])[KnownServerDivergences.RootsIgnoreOwningRelationship, KnownServerDivergences.DiffNotImplemented, KnownServerDivergences.MergeNotImplemented, KnownServerDivergences.MergeRequiresArrayBody, KnownServerDivergences.UnknownResourceNotFound, KnownServerDivergences.UnknownResourceAccepted, KnownServerDivergences.ErrorWithoutErrorBody, KnownServerDivergences.CreatedAnsweredOk, KnownServerDivergences.RecordsWithoutRequiredProperties, KnownServerDivergences.PreviousCommitAsObject, KnownServerDivergences.ElementsWithoutDerivedProperties, KnownServerDivergences.DatatypeIdNotUri, KnownServerDivergences.DataListedAsElements, KnownServerDivergences.ProjectUsageAsArray, KnownServerDivergences.QueryResultsProjected, KnownServerDivergences.QueryLosesNameAndDescription, KnownServerDivergences.InstanceOfRejected, KnownServerDivergences.QueryResultsGetNotImplemented, KnownServerDivergences.DeleteDoesNotCascade, KnownServerDivergences.DeleteUnknownBranchFails, KnownServerDivergences.DeletedProjectDeletedAgain])); Assert.That(KnownServerDivergences.All.Select(divergence => divergence.Reference), Has.All.Contains("Open-MBEE/flexo-mms-sysmlv2@836d904d")); } } @@ -149,6 +149,7 @@ public async Task VerifyExpectNotFoundAsync() { var notFound = KnownServerDivergences.UnknownResourceNotFound; var accepted = KnownServerDivergences.UnknownResourceAccepted; + var branchFails = KnownServerDivergences.DeleteUnknownBranchFails; using (Assert.EnterMultipleScope()) { @@ -167,6 +168,11 @@ public async Task VerifyExpectNotFoundAsync() Assert.That(await Outcome(Succeed, accepted, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); Assert.That(await Outcome(Answer(HttpStatusCode.NotFound), accepted, Conforming), Is.Empty); Assert.That(await Outcome(Answer(HttpStatusCode.Forbidden), accepted, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + + Assert.That(await Outcome(Answer(HttpStatusCode.InternalServerError), branchFails, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(await Outcome(Answer(HttpStatusCode.NotFound), branchFails, Conforming), Is.Empty); + Assert.That(await Outcome(Answer(HttpStatusCode.Forbidden), branchFails, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); + Assert.That(await Outcome(Succeed, branchFails, Conforming), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); } var warning = await IsolatedAssertions.RunAsync(() => KnownServerDivergences.ExpectNotFoundAsync(Answer(HttpStatusCode.Forbidden), () => Conforming, notFound, "the call")); diff --git a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs index 1a47c379b..1db95d977 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs @@ -18,6 +18,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests using SysML2.NET.Dal; using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; @@ -184,6 +185,28 @@ public void VerifyFind() } } + [Test] + public void VerifyOwnedTree() + { + Assert.That(() => ModelBuilder.OwnedTree(null, Guid.NewGuid()), Throws.ArgumentNullException); + + var root = new RootModel(); + var deletion = new DeletionModel(root); + var model = root.Builder.ToDtos(); + var tree = ModelBuilder.OwnedTree(model, deletion.Cascade.Id); + var innerMembership = model.Single(element => element.Id == deletion.Inner.Id).OwningRelationship; + var noteMembership = model.Single(element => element.Id == deletion.Note.Id).OwningRelationship; + + using (Assert.EnterMultipleScope()) + { + Assert.That(tree.Select(element => element.Id), Is.EquivalentTo((Guid?[])[innerMembership, deletion.Inner.Id, noteMembership, deletion.Note.Id]), "both levels of the composition, relationships and related elements alike"); + Assert.That(tree.Select(element => element.Id), Does.Not.Contain(deletion.Cascade.Id).And.Not.Contain(model.Single(element => element.Id == deletion.Cascade.Id).OwningRelationship), "neither the owner nor its own owning membership"); + Assert.That(ModelBuilder.OwnedTree(model, deletion.Single.Id), Is.Empty); + Assert.That(ModelBuilder.OwnedTree(model, Guid.NewGuid()), Is.Empty); + Assert.That(ModelBuilder.OwnedTree(model, root.Root.Id), Has.Count.EqualTo(model.Count - 1), "the root owns every other element"); + } + } + [Test] public void VerifyToCommitRequest() { diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/DeletionModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/DeletionModelTestFixture.cs new file mode 100644 index 000000000..dbaefd6c7 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/DeletionModelTestFixture.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System; + using System.Linq; + + using NUnit.Framework; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + using SysML2.NET.Core.DTO.Root.Namespaces; + + [TestFixture] + public class DeletionModelTestFixture + { + [Test] + public void VerifyDeletionModel() + { + Assert.That(() => new DeletionModel(null), Throws.ArgumentNullException); + + var root = new RootModel(); + var atStep2 = root.Builder.ToDtos(); + var model = new DeletionModel(root); + var dtos = model.Builder.ToDtos(); + var changed = ModelBuilder.Changed(atStep2, dtos); + + Guid[] MembersOf(Guid ownerId) => [.. dtos.OfType().Where(membership => membership.OwningRelatedElement == ownerId).SelectMany(membership => membership.OwnedRelatedElement)]; + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(changed.Where(dto => atStep2.Any(before => before.Id == dto.Id)).Select(dto => dto.Id), Is.EqualTo((Guid[])[root.Root.Id]), "only the root package changes, to own the new package"); + Assert.That(MembersOf(root.Root.Id), Does.Contain(model.Package.Id)); + Assert.That(MembersOf(model.Package.Id), Is.EquivalentTo((Guid[])[model.Single.Id, model.Emptied.Id, model.Cascade.Id])); + Assert.That(MembersOf(model.Single.Id), Is.Empty, "D1 deletes a package without content"); + Assert.That(MembersOf(model.Emptied.Id), Is.EquivalentTo((Guid[])[model.First.Id, model.Second.Id])); + Assert.That(MembersOf(model.Cascade.Id), Is.EqualTo((Guid[])[model.Inner.Id])); + Assert.That(MembersOf(model.Inner.Id), Is.EqualTo((Guid[])[model.Note.Id]), "D3 deletes an owner whose content is two levels deep"); + Assert.That(model.Note.Body, Is.Not.Empty); + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs index 5a65adbbf..c9b53e936 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs @@ -100,6 +100,70 @@ public async Task VerifyReadAllPagesAsync() await Assert.ThatAsync(() => ReadBackAssertions.ReadAllPagesAsync(_ => Task.FromResult(new PagedResult { Records = [], Next = new Page($"cursor-{++counter}") })), Throws.InvalidOperationException.With.Message.Contains("did not end")); } + [Test] + public async Task VerifyVerifyCascadeAsync() + { + var kept = new Package { Id = Guid.NewGuid() }; + var inner = new Package { Id = Guid.NewGuid() }; + var note = new Package { Id = Guid.NewGuid() }; + IReadOnlyList listed = [kept]; + var readable = new HashSet(); + var readFailures = new Dictionary(); + var unreadable = false; + + this.client.Setup(api => api.GetElementsByProjectCommitAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Guid _, Guid _, bool? _, QueryParameters parameters, CancellationToken _) => unreadable ? throw new InvalidOperationException("no list") : Paged(listed, parameters)); + this.client.Setup(api => api.GetElementByProjectCommitIdAsync(this.projectId, this.commitId, It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync((Guid _, Guid _, Guid elementId, bool? _, CancellationToken _) => readFailures.TryGetValue(elementId, out var readFailure) ? throw readFailure : readable.Contains(elementId) ? new Package { Id = elementId } : throw new PsmApiException(HttpStatusCode.NotFound, null)); + + var cascaded = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + readable.Add(note.Id); + + var stillReadable = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + readable.Clear(); + readFailures[note.Id] = new PsmApiException(HttpStatusCode.InternalServerError, null); + + var serverError = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + readFailures[note.Id] = new InvalidOperationException("unreadable"); + + var clientError = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + readFailures.Clear(); + listed = [kept, inner, note]; + + var notCascaded = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + listed = [kept, inner]; + + var partly = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + listed = [inner, note]; + + var keptLost = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + unreadable = true; + + var failed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyCascadeAsync(this.commitId, [inner, note], [kept])); + + using (Assert.EnterMultipleScope()) + { + Assert.That(cascaded, Is.Empty); + Assert.That(stillReadable, Has.Count.EqualTo(1)); + Assert.That(stillReadable[0].Message, Does.Contain($"reading Package {note.Id}, owned by the deleted element")); + Assert.That(serverError.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed]), "a 500 fails without ending the check"); + Assert.That(serverError[0].Message, Does.Contain($"reading Package {note.Id}, owned by the deleted element")); + Assert.That(clientError.Select(result => result.Message), Is.EqualTo((string[])[$"reading Package {note.Id}, owned by the deleted element threw InvalidOperationException: unreadable"])); + Assert.That(notCascaded.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(notCascaded[0].Message, Does.Contain(KnownServerDivergences.DeleteDoesNotCascade.Summary)); + Assert.That(partly.Select(result => result.Status), Has.Some.EqualTo(AssertionStatus.Failed), "a partial cascade is no known divergence"); + Assert.That(keptLost.Select(result => result.Status), Has.Some.EqualTo(AssertionStatus.Failed), "an element that was not deleted must stay"); + Assert.That(failed.Select(result => result.Message), Is.EqualTo((string[])["GetElementsByProjectCommitAsync after the cascading delete threw InvalidOperationException: no list"])); + } + } + [Test] public async Task VerifyVerifyCommitAsync() { @@ -298,6 +362,16 @@ List Changes(IData dataPayload, IData usagePayload, IData deletedPa var changeMissing = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + var cascadedId = Guid.NewGuid(); + changes = [.. Changes(data, usage, null), new DataVersion { Id = Guid.NewGuid(), Identity = new DataIdentity { Id = cascadedId } }]; + + var cascadeDeleted = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected, [cascadedId])); + + changes[^1].Payload = new Package { Id = cascadedId }; + + var cascadeEdited = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected, [cascadedId])); + var notCascaded = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDataCommitAsync(commit, branchId, previousId, expected)); + changes = Changes(data, usage, null); head = previousId; @@ -318,6 +392,10 @@ List Changes(IData dataPayload, IData usagePayload, IData deletedPa Assert.That(deletedInstead[0].Message, Does.Contain($"the payload of the change of ExternalData {data.Id} was read back as another kind of data")); Assert.That(changeMissing.Select(result => result.Message), Has.Some.Contains("one change per data item")); Assert.That(changeMissing, Has.Count.EqualTo(1)); + Assert.That(cascadeDeleted, Is.Empty, "an element deleted with its owner may be listed as deleted"); + Assert.That(cascadeEdited.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(cascadeEdited[0].Message, Does.Contain(KnownServerDivergences.DeleteDoesNotCascade.Summary)); + Assert.That(notCascaded.Select(result => result.Message), Has.Some.Contains("one change per data item"), "a change of an element the commit does not delete"); Assert.That(headNotMoved, Has.Count.EqualTo(1)); Assert.That(unreadable.Select(result => result.Message), Is.EqualTo((string[])["GetChangesByProjectCommitAsync threw InvalidOperationException: no changes"]), "the commit record still passes"); } @@ -354,6 +432,34 @@ public async Task VerifyVerifyDiffAsync() var deletedAndUnnamed = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); + var removed = new Package { Id = Guid.NewGuid() }; + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }, new DataDifference { BaseData = Version(removed) }]; + + var deletion = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated], [removed.Id])); + + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }, new DataDifference { BaseData = Version(removed), CompareData = Version(removed) }]; + + var deletionAsUpdate = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated], [removed.Id])); + + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }]; + + var deletionMissing = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated], [removed.Id])); + + var owned = new Package { Id = Guid.NewGuid() }; + var ownedMembership = new Package { Id = Guid.NewGuid() }; + this.state.ExpectedModels[baseCommitId] = [updated, removed, owned, ownedMembership]; + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }, new DataDifference { BaseData = Version(removed) }, new DataDifference { BaseData = Version(owned) }, new DataDifference { BaseData = Version(ownedMembership) }]; + + var cascade = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated], [removed.Id], [owned.Id, ownedMembership.Id])); + + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }, new DataDifference { BaseData = Version(removed) }, new DataDifference { BaseData = Version(ownedMembership), CompareData = Version(ownedMembership) }]; + + var notCascaded = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated], [removed.Id], [owned.Id, ownedMembership.Id])); + + differences = [new DataDifference { BaseData = Version(updated), CompareData = Version(updated) }, new DataDifference { BaseData = Version(removed) }, new DataDifference { BaseData = Version(owned) }]; + + var partlyCascaded = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated], [removed.Id], [owned.Id, ownedMembership.Id])); + failure = new PsmApiException(HttpStatusCode.NotImplemented, null); var notImplemented = await IsolatedAssertions.RunAsync(() => this.assertions.VerifyDiffAsync(baseCommitId, compareCommitId, [updated, created])); @@ -369,6 +475,13 @@ public async Task VerifyVerifyDiffAsync() Assert.That(misclassified.Select(result => result.Message), Has.Some.Contains("UPDATED")); Assert.That(misclassified.Select(result => result.Message), Has.Some.Contains("CREATED")); Assert.That(deletedAndUnnamed.Select(result => result.Message), Has.Some.Contains("a difference names the data it is about")); + Assert.That(deletion, Is.Empty); + Assert.That(deletionAsUpdate.Select(result => result.Message), Has.Some.Contains("a deleted element is DELETED")); + Assert.That(deletionMissing, Has.Count.EqualTo(1)); + Assert.That(cascade, Is.Empty); + Assert.That(notCascaded.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); + Assert.That(notCascaded[0].Message, Does.Contain(KnownServerDivergences.DeleteDoesNotCascade.Summary)); + Assert.That(partlyCascaded.Select(result => result.Message), Has.Some.Contains("an element deleted with its owner is DELETED")); Assert.That(notImplemented.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Warning])); Assert.That(notImplemented[0].Message, Does.Contain(KnownServerDivergences.DiffNotImplemented.Summary)); Assert.That(rejected.Select(result => result.Status), Is.EqualTo((AssertionStatus[])[AssertionStatus.Failed])); diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index cb580b219..2c578480c 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -239,8 +239,8 @@ a step ignores itself only when the state it builds on is missing. The verdict a | 9 | **Queries** | `POST` a query with an `or` `CompositeConstraint` holding a nested `and` and `PrimitiveConstraint`s; across the step's queries all 7 `Operator` literals and `inverse`; `select`; list, get, `PUT`, results three ways, at the default head and at the `kernel` commit; negative cases; `DELETE` | 27, 26, 28, 29, 31, 32, 33, 30 | | 10 | **Project usage** | second project `UsedLibrary` with a small model; **branch** `data` from the default head; a commit of a `ProjectUsage` of the library's commit; the project usage of a library element; `excludeUsed` on elements and roots | 2, 7, 15, 21, 19, 22 | | 11 | **External data** | on `data`: commit `ExternalData` and an `ExternalRelationship` to the root package, update both, delete both | 15, 17, 18 | -| 12 | **Delete model elements** | per metamodel package, delete the subjects with their owning memberships (`payload = null`), updating owners' `ownedRelationship` in the same commit; the deleted elements are gone at head and readable at the previous commit; `DiffAsync` shows `DELETED` | 15, 19, 20, 24 | -| 13 | **Tear down** | delete tag (13), branch (9), the `UsedLibrary` project and the main project (5); each is unreadable afterwards; negative cases (§6.3) | 13, 9, 5, 3, 8, 12 | +| 12 | **Delete model elements** | commit a package `Deletions` built for the cases D1–D3 (§6.2), then one commit per case deleting elements with their owning memberships (`payload = null`) and updating the owner's `ownedRelationship` in the same commit; the deleted elements answer 404 at the new commit and are readable at the previous one; `DiffAsync` shows `DELETED` | 15, 19, 20, 24 | +| 13 | **Tear down** | delete the tag `kernel` (13), the branches `systems` and `data` (9), the `UsedLibrary` project and the main project (5); each is unreadable and unlisted afterwards; deleting a tag or branch again answers 404, a project a client error, as the OpenAPI document declares no 404 for it; negative cases (§6.3) | 13, 9, 5, 3, 8, 12, 10, 6, 1, 22 | | 14 | **Coverage verdict** | — | asserts §7 | Step 9's expected results are computed from the expected model with a predicate per query @@ -289,6 +289,9 @@ feature. A connector, flow or association is retargeted through the reference or ### 6.2 Delete scenarios +The cases delete the content of a package `Deletions` that step 12 first commits for them +(`Helpers/Models/DeletionModel.cs`), so that no element of an earlier step loses a reference. + - D1 (step 12): a subject deleted together with its owning membership, the owner updated in the same commit — keeps the model well-formed. - D2 (step 12): a whole nested package's content deleted in one commit. @@ -296,7 +299,9 @@ feature. A connector, flow or association is retargeted through the reference or own owning membership, so its parent stays well-formed); none of its owned elements is listed. At the new commit, everything in the owner's composition tree is gone: its `ownedRelationship`s, their `ownedRelatedElement`s, and so on down. Basis: both properties are composite in KerML - (`Element::ownedRelationship`, `Relationship::ownedRelatedElement`; Hypha 2026-07). Asserted on: + (`Element::ownedRelationship`, `Relationship::ownedRelatedElement`; KerML 1.0, Clauses 8.3.2.1.2 + and 8.3.2.1.3). The Systems Modeling API & Services specification does not say whether a commit + that deletes an element deletes what it owns, so this reading admits another. Asserted on: - `GetElementByProjectCommitIdAsync` → 404 for every element of the tree; - `GetElementsByProjectCommitAsync` → the tree's ids are absent, everything else is unchanged; - `DiffAsync` previous → new commit → `DELETED` for every element of the tree, not only the owner; @@ -370,7 +375,14 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen - `DataListedAsElements`: the elements and roots of a commit include its project usages, external data and external relationships, so the client cannot read the list (steps 10, 11); - `ProjectUsageAsArray`: the project usage of an element is answered as an array of every project - usage of the commit, whatever the element, so the client cannot read it (step 10). + usage of the commit, whatever the element, so the client cannot read it (step 10); +- `DeleteDoesNotCascade`: deleting an element leaves the elements it owns in the model, listed + and readable, and removes their reference to it, which the commit lists as a further change + (§6.2 D3, step 12); +- `DeleteUnknownBranchFails`: deleting an unknown branch answers 500, not 404 (step 13); deleting + a deleted tag or branch answers 200 with its record again, which `UnknownResourceAccepted` covers; +- `DeletedProjectDeletedAgain`: deleting a deleted project answers 200 again instead of a client + error (step 13). The conformance check reports an item of a list whose `@type` is none of the types the schema admits at that item, so such an item cannot hide behind the errors of the other items. @@ -382,8 +394,7 @@ store slow down during a run, from a few milliseconds to hundreds, while the qua Expected from the Flexo source, added with the step that observes them: - real values come back as single-precision floats (step 4); 2.5 and 3.5 are exact in single - precision, so this is not observed yet; -- deleting an element leaves the elements it owns in place (no cascade, §6.2 D3, step 12). + precision, so this is not observed yet. Client defects found so far, each red until fixed: diff --git a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs index e76cf1a56..ef5b2ab0d 100644 --- a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs +++ b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs @@ -559,6 +559,107 @@ public async Task VerifyExternalData() [Test] [DependsOnTest(nameof(VerifyExternalData), AllowFailure = true)] + public async Task VerifyDeletions() + { + if (this.rootModel == null || this.state.HeadCommitId == null) + { + Assert.Ignore("the default branch has no model to delete from"); + } + + var deletion = new DeletionModel(this.rootModel); + var created = await this.CommitModelAsync(deletion.Builder, "Content to delete"); + + using (Assert.EnterMultipleScope()) + { + await this.readBack.VerifyCommitAsync(created.Commit, created.BranchId, created.PreviousHead, created.Changed); + + await this.DeleteAsync([deletion.Single.Id], deletion.Package.Id, "D1, a package and its owning membership"); + await this.DeleteAsync([deletion.First.Id, deletion.Second.Id], deletion.Emptied.Id, "D2, the whole content of a package"); + + var owned = ModelBuilder.OwnedTree(this.state.ExpectedModels[this.state.HeadCommitId.Value], deletion.Cascade.Id); + + await this.DeleteAsync([deletion.Cascade.Id], deletion.Package.Id, "D3, a package alone", owned); + } + } + + [Test] + [DependsOnTest(nameof(VerifyDeletions), AllowFailure = true)] + public async Task VerifyTeardown() + { + if (this.state.ProjectId == null) + { + Assert.Ignore("there is no project to tear down"); + } + + var projectId = this.state.ProjectId.Value; + var unknown = Guid.NewGuid(); + + using (Assert.EnterMultipleScope()) + { + if (this.state.TagIds.TryGetValue("kernel", out var tagId)) + { + var deletedTag = await this.client.DeleteTagByProjectAndIdAsync(projectId, tagId); + + Assert.That(deletedTag, Is.Null.Or.Property(nameof(IData.Id)).EqualTo(tagId), "a deletion answers the deleted tag, or nothing with 204"); + + await this.ExpectNotFoundAsync(() => this.client.GetTagByProjectAndIdAsync(projectId, tagId)); + + var (tags, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetTagsByProjectAsync(projectId, parameters)); + + Assert.That(tags.Select(tag => tag.Id), Does.Not.Contain(tagId), "a deleted tag is not listed"); + + await this.ExpectNotFoundAsync(() => this.client.DeleteTagByProjectAndIdAsync(projectId, tagId), KnownServerDivergences.UnknownResourceAccepted); + } + + await this.ExpectNotFoundAsync(() => this.client.DeleteTagByProjectAndIdAsync(projectId, unknown)); + await this.ExpectNotFoundAsync(() => this.client.GetTagsByProjectAsync(unknown), KnownServerDivergences.UnknownResourceNotFound); + + foreach (var branchId in this.state.BranchIds.Values.ToList()) + { + var deletedBranch = await this.client.DeleteBranchByProjectAndIdAsync(projectId, branchId); + + Assert.That(deletedBranch, Is.Null.Or.Property(nameof(IData.Id)).EqualTo(branchId), "a deletion answers the deleted branch, or nothing with 204"); + + await this.ExpectNotFoundAsync(() => this.client.GetBranchesByProjectAndIdAsync(projectId, branchId)); + await this.ExpectNotFoundAsync(() => this.client.DeleteBranchByProjectAndIdAsync(projectId, branchId), KnownServerDivergences.UnknownResourceAccepted); + } + + var (branches, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetBranchesByProjectAsync(projectId, parameters)); + + Assert.That(branches.Select(branch => branch.Id), Is.EquivalentTo((Guid[])[this.state.DefaultBranchId!.Value]), "only the default branch is left"); + + await this.ExpectNotFoundAsync(() => this.client.DeleteBranchByProjectAndIdAsync(projectId, unknown), KnownServerDivergences.DeleteUnknownBranchFails); + + if (this.state.HeadCommitId is { } head) + { + await this.ExpectNotFoundAsync(() => this.client.GetRelationshipsByProjectCommitRelatedElementAsync(unknown, head, this.rootModel?.Root.Id ?? unknown)); + } + + if (this.state.LibraryProjectId is { } libraryId) + { + var deletedLibrary = await this.client.DeleteProjectByIdAsync(libraryId); + + Assert.That(deletedLibrary, Is.Null.Or.Property(nameof(IData.Id)).EqualTo(libraryId), "a deletion answers the deleted project, or nothing with 204"); + + await this.ExpectNotFoundAsync(() => this.client.GetProjectByIdAsync(libraryId)); + } + + var deletedProject = await this.client.DeleteProjectByIdAsync(projectId); + + Assert.That(deletedProject, Is.Null.Or.Property(nameof(IData.Id)).EqualTo(projectId), "a deletion answers the deleted project, or nothing with 204"); + + await this.ExpectNotFoundAsync(() => this.client.GetProjectByIdAsync(projectId)); + await ExpectClientErrorAsync(() => this.client.DeleteProjectByIdAsync(projectId), KnownServerDivergences.DeletedProjectDeletedAgain); + await ExpectClientErrorAsync(() => this.client.DeleteProjectByIdAsync(unknown)); + + var (projects, _) = await ReadBackAssertions.ReadAllPagesAsync(parameters => this.client.GetProjectsAsync(parameters)); + + Assert.That(projects.Select(project => project.Id), Has.None.EqualTo(projectId).And.None.EqualTo(this.state.LibraryProjectId), "the deleted projects are not listed"); + } + } + + [Test] + [DependsOnTest(nameof(VerifyTeardown), AllowFailure = true)] public async Task VerifyCoverage() { var verdict = new CoverageVerdict(this.state.ReadBack, this.httpClientFactory.Recorder.Calls, this.openApi); @@ -583,9 +684,31 @@ public async Task VerifyCoverage() } } - private static async Task ExpectClientErrorAsync(Func call, [CallerArgumentExpression(nameof(call))] string description = null) + private static async Task ExpectClientErrorAsync(Func call, ServerDivergence accepted = null, [CallerArgumentExpression(nameof(call))] string description = null) { - await Assert.ThatAsync(() => call(), Throws.InstanceOf().With.Property(nameof(PsmApiException.StatusCode)).Matches(status => (int)status is >= 400 and < 500), description); + try + { + await call(); + } + catch (PsmApiException exception) + { + Assert.That((int)exception.StatusCode, Is.InRange(400, 499), description); + return; + } + catch (Exception exception) when (exception is not ResultStateException) + { + Assert.Fail($"{description} threw {exception.GetType().Name}: {exception.Message}"); + return; + } + + if (accepted == null) + { + Assert.Fail($"{description} succeeded"); + } + else + { + KnownServerDivergences.Report(accepted, $"{description} answered a success"); + } } private static IReadOnlyList Replace(IReadOnlyList model, IElement replacement) => [.. model.Select(element => element.Id == replacement.Id ? replacement : element)]; @@ -627,6 +750,48 @@ private static async Task ExpectClientErrorAsync(Func call, [CallerArgumen return this.CommitElementsAsync(model, ModelBuilder.Changed(previous, model), description, branch); } + private async Task DeleteAsync(IReadOnlyList elementIds, Guid ownerId, string description, IReadOnlyList cascaded = null) + { + var projectId = this.state.ProjectId!.Value; + var branch = this.state.DefaultBranchId!.Value; + var previousHead = this.state.BranchHeads[branch]; + var previous = this.state.ExpectedModels[previousHead]; + + var memberships = elementIds.Select(id => previous.Single(element => element.Id == id).OwningRelationship!.Value).ToList(); + List deleted = [.. elementIds, .. memberships]; + var owner = ModelBuilder.Copy(previous.Single(element => element.Id == ownerId)); + owner.OwnedRelationship.RemoveAll(memberships.Contains); + + List cascadedIds = [.. (cascaded ?? []).Select(element => element.Id)]; + var gone = deleted.Concat(cascadedIds).ToHashSet(); + List model = [.. previous.Where(element => !gone.Contains(element.Id)).Select(element => element.Id == ownerId ? owner : element)]; + + var request = new CommitRequest { Description = description, Change = [.. deleted.Select(id => new DataVersionRequest { Identity = new DataIdentityRequest { Id = id }, Payload = null }), new DataVersionRequest { Identity = new DataIdentityRequest { Id = owner.Id }, Payload = owner }] }; + var commit = await this.client.PostCommitByProjectAsync(projectId, request, branch); + + this.state.BranchHeads[branch] = commit.Id; + this.state.ExpectedModels[commit.Id] = model; + + await this.readBack.VerifyDataCommitAsync(commit, branch, previousHead, [.. deleted.Select(id => (id, (IData)null)), (owner.Id, owner)], cascadedIds); + + foreach (var id in deleted) + { + await this.ExpectNotFoundAsync(() => this.client.GetElementByProjectCommitIdAsync(projectId, commit.Id, id), description: $"reading {id}, deleted by {description}"); + } + + if (cascaded == null) + { + await this.readBack.VerifyElementIdsAsync($"the elements after {description}", parameters => this.client.GetElementsByProjectCommitAsync(projectId, commit.Id, queryParameters: parameters), [.. model.Select(element => element.Id)]); + } + else + { + await this.readBack.VerifyCascadeAsync(commit.Id, cascaded, model); + } + + await this.readBack.VerifyHistoryAsync(previousHead, previous.Single(element => element.Id == elementIds[0])); + await this.readBack.VerifyDiffAsync(previousHead, commit.Id, [owner], deleted, cascadedIds); + } + private Task ExpectNotFoundAsync(Func call, ServerDivergence tolerated = null, [CallerArgumentExpression(nameof(call))] string description = null) { return KnownServerDivergences.ExpectNotFoundAsync(call, () => this.httpClientFactory.Recorder.LastCall, tolerated, description); diff --git a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md index 825c11f68..2921034ba 100644 --- a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md +++ b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md @@ -29,7 +29,8 @@ SySML2.NET.REST.Tests/ │ ├── KerMLUpdateModel.cs step 5: updates U1–U4 of steps 2–4 │ ├── SystemsStructureModel.cs step 6: SysML structure, on the branch systems │ ├── SystemsBehaviorModel.cs step 7: SysML behaviour, requirements, cases and views -│ └── LibraryModel.cs step 10: the model of the project that the main model uses +│ ├── LibraryModel.cs step 10: the model of the project that the main model uses +│ └── DeletionModel.cs step 12: the content that the deletion cases delete ├── HelpersTests/ offline: one fixture per helper, mirroring Helpers/ │ ├── FlexoJwtTestFixture.cs, ModelBuilderTestFixture.cs, … │ └── Models/ one fixture per model class @@ -100,17 +101,17 @@ Session → PsmApiClient → HttpClient | Type | Responsibility | |---|---| -| `ModelBuilder` | Holds the whole model across the steps: each step starts its own scope (`BeginStep`) and creates POCOs with deterministic ids, wired with `AssignOwnership`. It converts them with the Dal's `ToDto(includeDerivedProperties: true)`, `Changed` selects the delta a commit sends, `Copy` copies a DTO for a change outside the builder, and `Find` looks an element up by its scoped name. An element whose derived values cannot be computed without the model library is converted without them and listed in `WithoutDerivedValues`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | +| `ModelBuilder` | Holds the whole model across the steps: each step starts its own scope (`BeginStep`) and creates POCOs with deterministic ids, wired with `AssignOwnership`. It converts them with the Dal's `ToDto(includeDerivedProperties: true)`, `Changed` selects the delta a commit sends, `Copy` copies a DTO for a change outside the builder, `OwnedTree` finds everything an element owns, and `Find` looks an element up by its scoped name. An element whose derived values cannot be computed without the model library is converted without them and listed in `WithoutDerivedValues`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | | `ScenarioQueries` | The queries of step 9, each with a predicate that picks its results from the expected model. | | `DeterministicGuid` | Name-based UUID v5 of `"/"`, so the elements have the same ids in every run. | -| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5), `SystemsStructureModel` (step 6), `SystemsBehaviorModel` (step 7), `LibraryModel` (step 10, in a second project). The base class holds the helpers the steps share: naming, ownership, features, parameters, results, literals and multiplicities. | +| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5), `SystemsStructureModel` (step 6), `SystemsBehaviorModel` (step 7), `LibraryModel` (step 10, in a second project), `DeletionModel` (step 12). The base class holds the helpers the steps share: naming, ownership, features, parameters, results, literals and multiplicities. | ### 5. Checking what came back | Type | Responsibility | |---|---| | `ScenarioState` | What the steps hand on to each other: the ids the server assigned (projects, branches, tags, commits), the head of every branch the scenario committed on, the expected model at each commit, and everything the server returned. | -| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Lists are read in pages of 100, and paging is checked on the first three pages of 10. A commit of project usages or external data is checked through its changes, the way a client reads such data back; query results and project usages have their own checks. One changed element of each metaclass is read by id, four reads at a time. Every read is guarded: a read that throws fails, or warns when its own response shows a known divergence that breaks deserialization. | +| `ReadBackAssertions` | The checks each model step runs after a commit: the commit and its predecessor, the branch head, the changes and their payloads, the changed elements by id, every element as listed, roots (the elements without an `owner`), relationships, the member element and name of every membership, that no returned DTO holds an empty GUID, and that an earlier commit still reads as it was. Element equality uses `ComparerProvider` from `SysML2.NET.Extensions`; a difference names the properties that differ. Lists are read in pages of 100, and paging is checked on the first three pages of 10. A commit of project usages or external data is checked through its changes, the way a client reads such data back; query results and project usages have their own checks, and a deletion of an owner is checked to remove what it owns. One changed element of each metaclass is read by id, four reads at a time. Every read is guarded: a read that throws fails, or warns when its own response shows a known divergence that breaks deserialization. | | `KnownServerDivergences`, `ServerDivergence` | The named ways Flexo diverges from the specification, each with a reference: an upstream issue, or a Flexo source location at the pinned commit. A divergence can explain response violations. `Report` raises an `Assert.Warn`. `ExpectNotFoundAsync` expects a 404, tolerates one named divergence, and fails when a conforming 404 reaches the caller without its `Error`. | | `IsolatedAssertions` | Runs a check in an isolated NUnit context and returns its failures and warnings, without failing the calling test. The offline fixtures use it to prove that a check fails when it should. | @@ -148,7 +149,8 @@ Having one `[Test]` per step goes against the one-test-per-method rule in `TESTI | 9 | `VerifyQueries` | implemented | | 10 | `VerifyProjectUsage` | implemented, on the branch `data` | | 11 | `VerifyExternalData` | implemented, on the branch `data` | -| 12–13 | see plan §5 | planned | +| 12 | `VerifyDeletions` | implemented: a deletion, an emptied package, and a deletion that must cascade | +| 13 | `VerifyTeardown` | implemented: tag, branches and both projects deleted | | 14 | `VerifyCoverage` | implemented, red by design | ### Reading the outcome From e5916e66dee75b3de0008be2b090aefee0c67a08 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Mon, 9 Nov 2026 15:21:51 +0100 Subject: [PATCH 09/11] [Add] Flexo integration scenario triage: every property set and changed, SysML update and moves, fixed-value exemptions in the verdict (#407) --- .../Helpers/CoverageVerdict.cs | 28 ++ .../Helpers/KnownServerDivergences.cs | 12 +- SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs | 26 +- .../Helpers/Models/CoreModel.cs | 6 +- .../Helpers/Models/KerMLUpdateModel.cs | 9 + .../Helpers/Models/MoveModel.cs | 319 ++++++++++++++++++ .../Helpers/Models/SystemsStructureModel.cs | 84 ++++- .../Helpers/Models/SystemsUpdateModel.cs | 125 +++++++ .../CoverageVerdictTestFixture.cs | 3 + .../KnownServerDivergencesTestFixture.cs | 21 ++ .../HelpersTests/ModelBuilderTestFixture.cs | 2 + .../Models/CoreModelTestFixture.cs | 6 + .../Models/KerMLUpdateModelTestFixture.cs | 5 + .../Models/MoveModelTestFixture.cs | 115 +++++++ .../SystemsStructureModelTestFixture.cs | 18 + .../Models/SystemsUpdateModelTestFixture.cs | 127 +++++++ .../INTEGRATION_TEST_PLAN.md | 23 +- .../FlexoModelScenarioTestFixture.cs | 32 +- .../TEST_PROJECT_STRUCTURE.md | 10 +- 19 files changed, 941 insertions(+), 30 deletions(-) create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs create mode 100644 SySML2.NET.REST.Tests/Helpers/Models/SystemsUpdateModel.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs create mode 100644 SySML2.NET.REST.Tests/HelpersTests/Models/SystemsUpdateModelTestFixture.cs diff --git a/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs b/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs index 6b268fe24..f85e501ef 100644 --- a/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs +++ b/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs @@ -28,6 +28,32 @@ public sealed class CoverageVerdict /// private static readonly ConcurrentDictionary Defaults = new(); + /// + /// Gets the properties whose value a metamodel constraint fixes, with that constraint; no well-formed model sets + /// them to another value or changes them + /// + public static IReadOnlyDictionary FixedProperties { get; } = new Dictionary + { + ["CollectExpression.Operator"] = "KerML validateCollectExpressionOperator", + ["FeatureChainExpression.Operator"] = "KerML validateFeatureChainExpressionOperator", + ["IndexExpression.Operator"] = "KerML validateIndexExpressionOperator", + ["SelectExpression.Operator"] = "KerML validateSelectExpressionOperator", + ["ConnectionDefinition.IsSufficient"] = "SysML validateConnectionDefinitionIsSufficient", + ["EnumerationDefinition.IsVariation"] = "SysML validateEnumerationDefinitionIsVariation", + ["Expose.IsImportAll"] = "SysML validateExposeIsImportAll", + ["Expose.Visibility"] = "SysML validateExposeVisibility", + ["FramedConcernMembership.Kind"] = "SysML validateFramedConcernMembershipConstraintKind", + ["RequirementVerificationMembership.Kind"] = "SysML validateRequirementVerificationMembershipKind" + }; + + /// + /// Gets the properties that no well-formed update of an element changes, with the reason + /// + public static IReadOnlyDictionary UnchangeableProperties { get; } = new Dictionary + { + ["Element.ElementId"] = "KerML 8.3.2.1.2: it must not change during the lifetime of the Element" + }; + /// /// Initializes a new instance of the class /// @@ -48,6 +74,7 @@ public CoverageVerdict(IReadOnlyCollection<(Guid CommitId, IData Data)> readBack this.MissingMetaclasses = DtoMetadata.ConcreteClasses.Where(type => !seenClasses.Contains(type)).Select(type => type.Name).ToList(); this.UnsetProperties = DtoMetadata.DeclaredProperties + .Where(property => !FixedProperties.ContainsKey(property.Name)) .Where(property => !elements.Exists(entry => property.Interface.IsInstanceOfType(entry.Data) && !DtoMetadata.ValueEquals(property.ValueOf(entry.Data), property.ValueOf(DefaultOf(entry.Data.GetType()))))) .Select(property => property.Name) .ToList(); @@ -55,6 +82,7 @@ public CoverageVerdict(IReadOnlyCollection<(Guid CommitId, IData Data)> readBack var versions = elements.GroupBy(entry => entry.Data.Id).ToList(); this.UnchangedProperties = DtoMetadata.DeclaredProperties + .Where(property => !FixedProperties.ContainsKey(property.Name) && !UnchangeableProperties.ContainsKey(property.Name)) .Where(property => !versions.Exists(element => property.Interface.IsInstanceOfType(element.First().Data) && element.Select(entry => property.ValueOf(entry.Data)).Skip(1).Any(value => !DtoMetadata.ValueEquals(value, property.ValueOf(element.First().Data))))) .Select(property => property.Name) .ToList(); diff --git a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs index 345cb9dea..d47f58852 100644 --- a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs +++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs @@ -206,7 +206,17 @@ public static class KnownServerDivergences /// Gets the divergence that deleting an element leaves what it owns in place, where its owned relationships and /// their owned related elements are composite in KerML /// - public static ServerDivergence DeleteDoesNotCascade { get; } = new("deleting an element leaves the elements it owns, through its owned relationships, in the model, and lists those that referenced it as changes of the commit, with the reference removed", $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/CommitApi.kt, a deletion removes the listed subjects and the references to them only"); + /// + /// The scenario applies it to the responses of step 12 only, the step that deletes elements. + /// + public static ServerDivergence DeleteDoesNotCascade { get; } = new( + "deleting an element leaves the elements it owns, through its owned relationships, in the model, and lists those that referenced it as changes of the commit, with the reference removed", + $"{FlexoRevision} src/main/kotlin/org/openmbee/flexo/sysmlv2/apis/CommitApi.kt, a deletion removes the listed subjects and the references to them only", + (call, violation) => call.Operation?.PathTemplate.StartsWith("/projects/{projectId}/commits/{commitId}/", StringComparison.Ordinal) == true + && violation.Kind == ContractViolationKind.SchemaMismatch + && MissingNames(violation) is { } names + && names.Contains("owningRelatedElement") + && names.All(name => name == "owningRelatedElement" || DtoMetadata.DerivedPropertyNames.Contains(name))); /// /// Gets the divergence that deleting an unknown branch fails on the server, where the OpenAPI document declares diff --git a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs index d0e9958db..ff2f9f3c0 100644 --- a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs +++ b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs @@ -34,9 +34,10 @@ namespace SySML2.NET.REST.Tests.Helpers public sealed class ModelBuilder { /// - /// The settable string list properties per DTO class, which the Dal conversion shares with the POCO (#428) + /// The settable string and reference list properties per DTO class, which the Dal conversion shares with the + /// POCO (#428) and a memberwise copy shares with the DTO it copies /// - private static readonly ConcurrentDictionary StringListsByClass = new(); + private static readonly ConcurrentDictionary ListsByClass = new(); /// /// The memberwise copy of , which copies a DTO of any class @@ -103,8 +104,8 @@ public static IReadOnlyList Changed(IReadOnlyList previo } /// - /// Copies a DTO, with its own string lists, so that a change to the copy leaves the expected model it came from - /// intact + /// Copies a DTO, with its own string and reference lists, so that a change to the copy leaves the expected model + /// it came from intact /// /// /// The type of the DTO @@ -311,7 +312,7 @@ public IReadOnlyList ToDtos() } /// - /// Gives a DTO its own copy of every string list it holds + /// Gives a DTO its own copy of every string and reference list it holds /// /// /// The DTO @@ -321,16 +322,21 @@ public IReadOnlyList ToDtos() /// private static DtoElement Detach(DtoElement dto) { - var stringLists = StringListsByClass.GetOrAdd(dto.GetType(), type => type + var lists = ListsByClass.GetOrAdd(dto.GetType(), type => type .GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(property => property.PropertyType == typeof(List) && property.CanWrite && property.SetMethod is { IsPublic: true } or { IsAssembly: true }) + .Where(property => (property.PropertyType == typeof(List) || property.PropertyType == typeof(List)) && property.CanWrite && property.SetMethod is { IsPublic: true } or { IsAssembly: true }) .ToArray()); - foreach (var property in stringLists) + foreach (var property in lists) { - if (property.GetValue(dto) is List list) + switch (property.GetValue(dto)) { - property.SetValue(dto, new List(list)); + case List strings: + property.SetValue(dto, new List(strings)); + break; + case List references: + property.SetValue(dto, new List(references)); + break; } } diff --git a/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs index 5fc6e1f25..363c4ff89 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs @@ -39,7 +39,8 @@ namespace SySML2.NET.REST.Tests.Helpers.Models /// membership or an annotation own a related element, and every owned feature is also featured by its owning type. The end features e1 and e2 get the multiplicity [1] that /// KerML requires of an end feature (validateFeatureEndMultiplicity) in step 4, because /// MultiplicityRange is a Kernel metaclass. Rules that need the model library (checkTypeSpecialization - /// and the like) cannot hold without one. + /// and the like) cannot hold without one. The type featuring of f by A is marked implied, so f + /// includes its implied relationships (validateElementIsImpliedIncluded). /// public sealed class CoreModel : StepModel { @@ -70,6 +71,9 @@ public sealed class CoreModel : StepModel this.OwnFeature(this.A, this.G); this.OwnFeature(this.A, k); + f.OwnedRelationship.OfType().Single().IsImplied = true; + f.IsImpliedIncluded = true; + var h = this.CreateNamed("h", "h", FeatureExtensions.ToDto); h.Direction = FeatureDirectionKind.In; h.IsUnique = false; diff --git a/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs index 41815d13a..ed3a1a52e 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs @@ -118,6 +118,10 @@ private void ChangeAttributes(RootModel root) this.Builder.Find("core/T").IsSufficient = false; this.Builder.Find("core/g").IsDerived = false; + var f = this.Builder.Find("core/f"); + f.OwnedRelationship.OfType().Single().IsImplied = false; + f.IsImpliedIncluded = false; + var h = this.Builder.Find("core/h"); h.IsUnique = true; h.IsOrdered = false; @@ -129,6 +133,8 @@ private void ChangeAttributes(RootModel root) this.Builder.Find("kernel/D").IsSufficient = false; + this.Builder.Find("kernel/b").IsEnd = true; + var c = this.Builder.Find("kernel/c"); c.IsOrdered = false; c.IsUnique = true; @@ -137,6 +143,7 @@ private void ChangeAttributes(RootModel root) this.Builder.Find("kernel/a/value/42").Value = 43; this.Builder.Find("kernel/rational").Value = 3.5; this.Builder.Find("kernel/text").Value = "t"; + this.Builder.Find("kernel/sum").Operator = "-"; this.Builder.Find("kernel/inv").IsNegated = false; this.Builder.Find("kernel/P/body").Value = false; } @@ -224,6 +231,8 @@ private void Retarget(CoreModel core, KernelModel kernel) var dependency = this.Builder.Find("root/Uses"); dependency.Supplier.Clear(); dependency.Supplier.Add(space); + dependency.Client.Clear(); + dependency.Client.Add(library); this.Builder.Find("root/Nested/import Library").ImportedNamespace = space; this.Builder.Find("root/Space/LibAlias").MemberElement = this.Builder.Find("root/Nested"); diff --git a/SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs new file mode 100644 index 000000000..cd47597dd --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs @@ -0,0 +1,319 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using SysML2.NET.Core.POCO.Core.Classifiers; + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Core.Types; + using SysML2.NET.Core.POCO.Kernel.Packages; + using SysML2.NET.Core.POCO.Root.Namespaces; + using SysML2.NET.Core.POCO.Systems.Ports; + using SysML2.NET.Dal; + using SysML2.NET.Extensions; + + using DtoElement = SysML2.NET.Core.DTO.Root.Elements.IElement; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using PocoRelationship = SysML2.NET.Core.POCO.Root.Elements.IRelationship; + using Type = SysML2.NET.Core.POCO.Core.Types.Type; + + /// + /// The content of a package Moves for the update U5 of scenario step 12, after plan §6.1: each relationship + /// whose source end is its owner moves to a new owner, which it then has as its source end, two port definitions + /// exchange their conjugated port definitions, and two members exchange their owning memberships + /// + /// + /// + /// package Moves { + /// type G; type S1 specializes G; type S2; type C1 ~ G; type C2; type D1 disjoint from G; type D2; + /// classifier KG; classifier K1 specializes KG; classifier K2; + /// feature FG; feature FT1 : G; feature FT2; feature FS1 subsets FG; feature FS2; + /// feature FI1 inverse of FG; feature FI2; feature TF1 featured by G; feature TF2; + /// type RB { feature rg; } type RS { feature r1 redefines RB::rg; feature r2; } + /// port def PA; port def PB; // each owns its conjugated port definition + /// package X; package Y; + /// } + /// + /// The public SDK cannot take a relationship out of an ownership list (#427), so builds the + /// moved content in a model builder of its own, with the same names and so the same ids; the model builder of the + /// scenario no longer describes the server's model once the moves are committed. + /// + public sealed class MoveModel : StepModel + { + /// + /// The scope of the content of this step + /// + private const string Scope = "move"; + + /// + /// Per moved relationship: the relationship, and its owner before and after the move + /// + private readonly List<(Guid Relationship, Guid From, Guid To)> moves = []; + + /// + /// Initializes a new instance of the class and builds the content to move + /// + /// + /// The model of step 2 + /// + public MoveModel(RootModel root) : this(root, false) + { + } + + /// + /// Initializes a new instance of the class and builds the content before or after the moves + /// + /// + /// The model of step 2 + /// + /// + /// Whether to build the content as it is after the moves + /// + private MoveModel(RootModel root, bool moved) : base((root ?? throw new ArgumentNullException(nameof(root))).Builder, Scope) + { + this.Package = this.CreateNamed("Moves", "mov", PackageExtensions.ToDto); + this.OwnMember(root.Root, this.Package); + + var general = this.Member("G", TypeExtensions.ToDto); + var classifierGeneral = this.Member("KG", ClassifierExtensions.ToDto); + var featureGeneral = this.Member("FG", FeatureExtensions.ToDto); + + this.Relate(this.Member("S1", TypeExtensions.ToDto), this.Member("S2", TypeExtensions.ToDto), moved, "specialization", SpecializationExtensions.ToDto, (relationship, owner) => + { + relationship.Specific = (Type)owner; + relationship.General = general; + }); + + this.Relate(this.Member("C1", TypeExtensions.ToDto), this.Member("C2", TypeExtensions.ToDto), moved, "conjugation", ConjugationExtensions.ToDto, (relationship, owner) => + { + relationship.ConjugatedType = (Type)owner; + relationship.OriginalType = general; + }); + + this.Relate(this.Member("D1", TypeExtensions.ToDto), this.Member("D2", TypeExtensions.ToDto), moved, "disjoining", DisjoiningExtensions.ToDto, (relationship, owner) => + { + relationship.TypeDisjoined = (Type)owner; + relationship.DisjoiningType = general; + }); + + this.Relate(this.Member("K1", ClassifierExtensions.ToDto), this.Member("K2", ClassifierExtensions.ToDto), moved, "subclassification", SubclassificationExtensions.ToDto, (relationship, owner) => + { + relationship.Subclassifier = (Classifier)owner; + relationship.Superclassifier = classifierGeneral; + }); + + this.Relate(this.Member("FT1", FeatureExtensions.ToDto), this.Member("FT2", FeatureExtensions.ToDto), moved, "typing", FeatureTypingExtensions.ToDto, (relationship, owner) => + { + relationship.TypedFeature = (Feature)owner; + relationship.Type = general; + }); + + this.Relate(this.Member("FS1", FeatureExtensions.ToDto), this.Member("FS2", FeatureExtensions.ToDto), moved, "subsetting", SubsettingExtensions.ToDto, (relationship, owner) => + { + relationship.SubsettingFeature = (Feature)owner; + relationship.SubsettedFeature = featureGeneral; + }); + + this.Relate(this.Member("FI1", FeatureExtensions.ToDto), this.Member("FI2", FeatureExtensions.ToDto), moved, "inverting", FeatureInvertingExtensions.ToDto, (relationship, owner) => + { + relationship.FeatureInverted = (Feature)owner; + relationship.InvertingFeature = featureGeneral; + }); + + this.Relate(this.Member("TF1", FeatureExtensions.ToDto), this.Member("TF2", FeatureExtensions.ToDto), moved, "featuring", TypeFeaturingExtensions.ToDto, (relationship, owner) => + { + relationship.FeatureOfType = (Feature)owner; + relationship.FeaturingType = moved ? classifierGeneral : general; + }); + + var redefinedOwner = this.Member("RB", TypeExtensions.ToDto); + var redefined = this.CreateNamed("rg", "rg", FeatureExtensions.ToDto); + this.OwnFeature(redefinedOwner, redefined); + var redefiningOwner = this.Member("RS", TypeExtensions.ToDto); + var firstRedefining = this.CreateNamed("r1", "r1", FeatureExtensions.ToDto); + var secondRedefining = this.CreateNamed("r2", "r2", FeatureExtensions.ToDto); + this.OwnFeature(redefiningOwner, firstRedefining); + this.OwnFeature(redefiningOwner, secondRedefining); + this.Relate(firstRedefining, secondRedefining, moved, "redefinition", RedefinitionExtensions.ToDto, (relationship, owner) => + { + relationship.RedefiningFeature = (Feature)owner; + relationship.RedefinedFeature = redefined; + }); + + this.FirstPortDefinition = this.Member("PA", PortDefinitionExtensions.ToDto); + this.SecondPortDefinition = this.Member("PB", PortDefinitionExtensions.ToDto); + this.FirstConjugatedPortDefinition = this.Conjugated("PA", this.FirstPortDefinition, this.SecondPortDefinition, moved); + this.SecondConjugatedPortDefinition = this.Conjugated("PB", this.SecondPortDefinition, this.FirstPortDefinition, moved); + + this.First = this.CreateNamed("X", "x", PackageExtensions.ToDto); + this.Second = this.CreateNamed("Y", "y", PackageExtensions.ToDto); + this.Package.AssignOwnership(this.Builder.Create("X/membership", OwningMembershipExtensions.ToDto), moved ? this.Second : this.First); + this.Package.AssignOwnership(this.Builder.Create("Y/membership", OwningMembershipExtensions.ToDto), moved ? this.First : this.Second); + } + + /// + /// Gets the package that holds the content to move + /// + public Package Package { get; } + + /// + /// Gets the port definition PA + /// + public PortDefinition FirstPortDefinition { get; } + + /// + /// Gets the port definition PB + /// + public PortDefinition SecondPortDefinition { get; } + + /// + /// Gets the conjugated port definition that owns before the moves and + /// after them + /// + public ConjugatedPortDefinition FirstConjugatedPortDefinition { get; } + + /// + /// Gets the conjugated port definition that owns before the moves and + /// after them + /// + public ConjugatedPortDefinition SecondConjugatedPortDefinition { get; } + + /// + /// Gets the package X, which exchanges its owning membership with + /// + public Package First { get; } + + /// + /// Gets the package Y, which exchanges its owning membership with + /// + public Package Second { get; } + + /// + /// Gets the moved relationships, each with its owner before and after the move + /// + public IReadOnlyList<(Guid Relationship, Guid From, Guid To)> Moves => this.moves; + + /// + /// Gets the elements of this step that the moves change, as they are after the moves + /// + /// + /// The model that holds the content of this step before the moves, which is not changed + /// + /// + /// The DTO of every element of this step that differs from its version in + /// + public IReadOnlyList Moved(IReadOnlyList model) + { + ArgumentNullException.ThrowIfNull(model); + + var after = new MoveModel(new RootModel(), true); + var ids = after.Builder.Elements.Where(entry => entry.Name.StartsWith($"{Scope}/", StringComparison.Ordinal)).Select(entry => entry.Element.Id).ToHashSet(); + + return ModelBuilder.Changed(model, [.. after.Builder.ToDtos().Where(dto => ids.Contains(dto.Id))]); + } + + /// + /// Creates the conjugated port definition of a port definition, with its port conjugation, owned by that port + /// definition before the moves and by the other one after them + /// + /// + /// The name of the port definition, which scopes the names of what is created + /// + /// + /// The port definition that owns the conjugated port definition before the moves + /// + /// + /// The port definition that owns it after the moves + /// + /// + /// Whether to build the content as it is after the moves + /// + /// + /// The conjugated port definition + /// + private ConjugatedPortDefinition Conjugated(string name, PortDefinition from, PortDefinition to, bool moved) + { + var owner = moved ? to : from; + var conjugated = this.Builder.Create($"{name}/conjugated", ConjugatedPortDefinitionExtensions.ToDto); + var membership = this.Builder.Create($"{name}/conjugated/membership", OwningMembershipExtensions.ToDto); + owner.AssignOwnership(membership, conjugated); + + var conjugation = this.Builder.Create($"{name}/conjugated/conjugation", PortConjugationExtensions.ToDto); + conjugation.OriginalPortDefinition = owner; + conjugation.ConjugatedType = conjugated; + conjugated.AssignOwnership(conjugation); + + this.moves.Add((membership.Id, from.Id, to.Id)); + + return conjugated; + } + + /// + /// Creates a member of + /// + /// + /// The metaclass of the member + /// + /// + /// The name of the member, whose lower case is its short name + /// + /// + /// The generated ToDto extension of + /// + /// + /// The member + /// + private TPoco Member(string name, Func toDto) where TPoco : PocoElement, new() + { + var member = this.CreateNamed(name, name.ToLowerInvariant(), toDto); + this.OwnMember(this.Package, member); + + return member; + } + + /// + /// Creates a relationship whose source end is its owner, owned by one element before the moves and by another + /// after them + /// + /// + /// The metaclass of the relationship + /// + /// + /// The owner before the moves + /// + /// + /// The owner after the moves + /// + /// + /// Whether to build the content as it is after the moves + /// + /// + /// The name of the relationship within the name of its first owner + /// + /// + /// The generated ToDto extension of + /// + /// + /// Sets the ends of the relationship, its source end to the given owner + /// + private void Relate(PocoElement from, PocoElement to, bool moved, string kind, Func toDto, Action setEnds) where TRelationship : PocoRelationship, new() + { + var owner = moved ? to : from; + var relationship = this.Builder.Create($"{from.DeclaredName}/{kind}", toDto); + setEnds(relationship, owner); + owner.AssignOwnership(relationship); + + this.moves.Add((relationship.Id, from.Id, to.Id)); + } + } +} diff --git a/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs index cd6b113a7..628f6f64f 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/SystemsStructureModel.cs @@ -51,12 +51,15 @@ namespace SySML2.NET.REST.Tests.Helpers.Models /// part def P { /// attribute x : A; attribute y : A; enum ev : E; /// occurrence o1 : O; occurrence o2 : O; timeslice ts : O; snapshot sn : O; event occurrence ev1 = o1; - /// item it1 : I; item it2 : I; part sub1 : Q; part sub2 : Q; port p1 : PD; port p2 : ~PD; ref r; + /// item it1 : I; item it2 : I; part sub1 : Q; part sub2 : Q; port p1 : PD; port p2 : ~PD; port p3 : ~PD; ref r; /// connection c : CD connect sub1 to sub2; interface i : IF connect p1 to p2; /// allocation al : AD allocate sub1 to it1; binding b of x = y; succession s first o1 then o2; /// flow f : FD from it1.content to it2.content; succession flow sf from it1.content to it2.content; /// } /// definition D { usage u; } + /// individual occurrence def Ind; individual occurrence solo : Ind; + /// part def Plain; part bare; + /// port def PE; // owns ~PE through a port conjugation /// } /// /// Every end has the multiplicity [1], every directed or end usage is referential, and the rules that need @@ -111,13 +114,7 @@ public sealed class SystemsStructureModel : StepModel this.PortDefinition = this.Member("PD", PortDefinitionExtensions.ToDto); this.Owned(this.PortDefinition, "pa", AttributeUsageExtensions.ToDto, this.AttributeDefinition); - this.ConjugatedPortDefinition = this.Builder.Create("PD/conjugated", ConjugatedPortDefinitionExtensions.ToDto); - this.OwnMember(this.PortDefinition, this.ConjugatedPortDefinition); - - var conjugation = this.Builder.Create("PD/conjugated/conjugation", PortConjugationExtensions.ToDto); - conjugation.OriginalPortDefinition = this.PortDefinition; - conjugation.ConjugatedType = this.ConjugatedPortDefinition; - this.ConjugatedPortDefinition.AssignOwnership(conjugation); + this.ConjugatedPortDefinition = this.Conjugated(this.PortDefinition, "PD"); this.Part = this.Member("P", PartDefinitionExtensions.ToDto); @@ -165,6 +162,8 @@ public sealed class SystemsStructureModel : StepModel var p1 = this.Owned(this.Part, "p1", PortUsageExtensions.ToDto, this.PortDefinition); var p2 = this.Owned(this.Part, "p2", PortUsageExtensions.ToDto, null); this.ConjugatedTyping(p2); + this.SparePort = this.Owned(this.Part, "p3", PortUsageExtensions.ToDto, null); + this.ConjugatedTyping(this.SparePort); this.Owned(this.Part, "r", ReferenceUsageExtensions.ToDto, null); this.Connect("c", ConnectionUsageExtensions.ToDto, ReferenceUsageExtensions.ToDto, connection, sub1, sub2); @@ -179,6 +178,18 @@ public sealed class SystemsStructureModel : StepModel var definition = this.Member("D", DefinitionExtensions.ToDto); var usage = this.Owned(definition, "u", UsageExtensions.ToDto, null); usage.IsComposite = true; + + this.IndividualDefinition = this.Member("Ind", OccurrenceDefinitionExtensions.ToDto); + this.IndividualDefinition.IsIndividual = true; + this.IndividualUsage = this.Member("solo", OccurrenceUsageExtensions.ToDto); + this.IndividualUsage.IsIndividual = true; + this.Typed(this.IndividualUsage, this.IndividualDefinition); + + this.PlainDefinition = this.Member("Plain", PartDefinitionExtensions.ToDto); + this.PlainUsage = this.Member("bare", PartUsageExtensions.ToDto); + + var otherPort = this.Member("PE", PortDefinitionExtensions.ToDto); + this.OtherConjugatedPortDefinition = this.Conjugated(otherPort, "PE"); } /// @@ -226,6 +237,63 @@ public sealed class SystemsStructureModel : StepModel /// public ConjugatedPortDefinition ConjugatedPortDefinition { get; } + /// + /// Gets the conjugated port definition ~PE of the port definition PE, to which step 8 retargets + /// the conjugated typing of p3 + /// + public ConjugatedPortDefinition OtherConjugatedPortDefinition { get; } + + /// + /// Gets the port usage p3 of , typed by and connected + /// to nothing, whose conjugated typing step 8 retargets + /// + public PortUsage SparePort { get; } + + /// + /// Gets the individual occurrence definition Ind + /// + public OccurrenceDefinition IndividualDefinition { get; } + + /// + /// Gets the individual occurrence usage solo, typed by + /// + public OccurrenceUsage IndividualUsage { get; } + + /// + /// Gets the part definition Plain, without features, which step 8 makes a variation + /// + public PartDefinition PlainDefinition { get; } + + /// + /// Gets the part usage bare, without features, which step 8 makes a variation + /// + public PartUsage PlainUsage { get; } + + /// + /// Creates the conjugated port definition of a port definition, with its port conjugation + /// + /// + /// The port definition, which owns the conjugated port definition + /// + /// + /// The name of the port definition, which scopes the names of what is created + /// + /// + /// The conjugated port definition + /// + private ConjugatedPortDefinition Conjugated(PortDefinition portDefinition, string name) + { + var conjugated = this.Builder.Create($"{name}/conjugated", ConjugatedPortDefinitionExtensions.ToDto); + this.OwnMember(portDefinition, conjugated); + + var conjugation = this.Builder.Create($"{name}/conjugated/conjugation", PortConjugationExtensions.ToDto); + conjugation.OriginalPortDefinition = portDefinition; + conjugation.ConjugatedType = conjugated; + conjugated.AssignOwnership(conjugation); + + return conjugated; + } + /// /// Types a port usage by through a /// diff --git a/SySML2.NET.REST.Tests/Helpers/Models/SystemsUpdateModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/SystemsUpdateModel.cs new file mode 100644 index 000000000..74f0f1f87 --- /dev/null +++ b/SySML2.NET.REST.Tests/Helpers/Models/SystemsUpdateModel.cs @@ -0,0 +1,125 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.Helpers.Models +{ + using System; + using System.Linq; + + using SysML2.NET.Core.POCO.Core.Features; + using SysML2.NET.Core.POCO.Kernel.FeatureValues; + using SysML2.NET.Core.POCO.Systems.Actions; + using SysML2.NET.Core.POCO.Systems.Occurrences; + using SysML2.NET.Core.POCO.Systems.Ports; + using SysML2.NET.Core.POCO.Systems.Requirements; + using SysML2.NET.Core.POCO.Systems.States; + using SysML2.NET.Core.Systems.Actions; + using SysML2.NET.Core.Systems.Occurrences; + using SysML2.NET.Core.Systems.Requirements; + using SysML2.NET.Core.Systems.States; + + /// + /// The changes of scenario step 8 to the SysML model of steps 6 and 7, after plan §6.1: U1 renames one instance of + /// every metaclass that steps 6 and 7 created, and U2 changes the SysML attributes that a well-formed model lets + /// change, and retargets a conjugated port typing + /// + /// + /// Each change keeps the constraints it touches: a variation is abstract and owns no feature memberships + /// (validateDefinitionVariationIsAbstract, …OwnedFeatureMembership), an initial value needs a variable + /// feature (validateFeatureValueIsInitial), the subaction kinds of a state stay unique, and an accept action + /// as an effect is still an action (validateTransitionFeatureMembershipEffectAction). + /// + public sealed class SystemsUpdateModel : StepModel + { + /// + /// The scopes of the steps whose content this update changes + /// + private static readonly string[] SystemsScopes = ["systems structure/", "systems behaviour/"]; + + /// + /// Initializes a new instance of the class and changes the model of steps 6 and 7 + /// + /// + /// The model of step 6 + /// + /// + /// The model of step 7 + /// + public SystemsUpdateModel(SystemsStructureModel structure, SystemsBehaviorModel behavior) : base((behavior ?? throw new ArgumentNullException(nameof(behavior))).Builder, "systems update") + { + ArgumentNullException.ThrowIfNull(structure); + + this.Rename(); + this.ChangeStructure(structure); + this.ChangeBehavior(); + } + + /// + /// U2 on the content of step 7: a variable feature, the requirement constraint kinds, the states, a transition, + /// and the trigger of accept at made a when trigger, the kind its Boolean argument fits + /// + private void ChangeBehavior() + { + var limit = this.Builder.Find("systems behaviour/limit"); + limit.OwnedRelationship.OfType().Single().IsInitial = false; + limit.IsConstant = false; + limit.IsVariable = false; + + this.Builder.Find("systems behaviour/R/assumed/membership").Kind = RequirementConstraintKind.Requirement; + this.Builder.Find("systems behaviour/R/required/membership").Kind = RequirementConstraintKind.Assumption; + + this.Builder.Find("systems behaviour/Par").IsParallel = false; + this.Builder.Find("systems behaviour/pu").IsParallel = false; + this.Builder.Find("systems behaviour/St/entry/membership").Kind = StateSubactionKind.Exit; + this.Builder.Find("systems behaviour/St/exit/membership").Kind = StateSubactionKind.Entry; + this.Builder.Find("systems behaviour/t/Trigger/membership").Kind = TransitionFeatureKind.Effect; + + this.Builder.Find("systems behaviour/accept at/trigger").Kind = TriggerKind.When; + } + + /// + /// U2 on the content of step 6: the individual occurrences, the plain definition and usage made variations, a + /// portion kind, and the conjugated typing of the spare port retargeted + /// + /// + /// The model of step 6 + /// + private void ChangeStructure(SystemsStructureModel structure) + { + structure.IndividualDefinition.IsIndividual = false; + structure.IndividualUsage.IsIndividual = false; + + structure.PlainDefinition.IsVariation = true; + structure.PlainDefinition.IsAbstract = true; + structure.PlainUsage.IsVariation = true; + structure.PlainUsage.IsAbstract = true; + + this.Builder.Find("systems structure/ts").PortionKind = PortionKind.Snapshot; + + structure.SparePort.OwnedRelationship.OfType().Single().ConjugatedPortDefinition = structure.OtherConjugatedPortDefinition; + } + + /// + /// U1: renames the first instance of every metaclass that steps 6 and 7 created + /// + private void Rename() + { + var firstInstances = this.Builder.Elements + .Where(entry => SystemsScopes.Any(scope => entry.Name.StartsWith(scope, StringComparison.Ordinal))) + .GroupBy(entry => entry.Element.GetType()) + .Select(group => group.First().Element); + + foreach (var element in firstInstances) + { + element.DeclaredName = $"{element.DeclaredName ?? element.GetType().Name} renamed"; + element.DeclaredShortName = $"{element.DeclaredShortName ?? element.GetType().Name.ToLowerInvariant()}2"; + } + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs index c8003d879..69670e266 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/CoverageVerdictTestFixture.cs @@ -70,6 +70,9 @@ public void VerifyCoverageVerdict() Assert.That(verdict.MissingMetaclasses, Does.Contain(nameof(OwningMembership)).And.Not.Contain(nameof(Package))); Assert.That(verdict.UnsetProperties, Does.Not.Contain("Element.DeclaredName").And.Contain("Element.DeclaredShortName")); Assert.That(verdict.UnchangedProperties, Does.Not.Contain("Element.DeclaredName").And.Contain("Element.DeclaredShortName")); + Assert.That(verdict.UnsetProperties, Does.Contain("Element.ElementId").And.Not.Contain("Expose.Visibility"), "a fixed value is never unset, an unchangeable one may be"); + Assert.That(verdict.UnchangedProperties, Does.Not.Contain("Element.ElementId").And.Not.Contain("Expose.Visibility")); + Assert.That(CoverageVerdict.FixedProperties.Keys.Concat(CoverageVerdict.UnchangeableProperties.Keys), Is.SubsetOf(DtoMetadata.DeclaredProperties.Select(property => property.Name)), "every exemption names a declared property"); Assert.That(verdict.MissingLiterals, Does.Contain("VisibilityKind.Private")); Assert.That(verdict.MissingLiterals, Has.None.StartsWith("ClassKind.")); Assert.That(verdict.UncoveredOperations, Has.None.StartsWith("GET /projects (")); diff --git a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs index 2d3c731b3..c2a05cf0c 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/KnownServerDivergencesTestFixture.cs @@ -110,6 +110,27 @@ public void VerifyDatatypeIdNotUri() } } + [Test] + public void VerifyDeleteDoesNotCascade() + { + var openApi = OpenApiDocument.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "Resources", "ptc-25-02-30.json")); + var getChanges = new EndpointCall(openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/changes"), "GET /projects/p/commits/c/changes", HttpStatusCode.OK); + var getProject = new EndpointCall(openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}"), "GET /projects/p", HttpStatusCode.OK); + var getElement = new EndpointCall(openApi.Operations.Single(operation => operation.ToString() == "GET /projects/{projectId}/commits/{commitId}/elements/{elementId}"), "GET /projects/p/commits/c/elements/e", HttpStatusCode.OK); + var explains = KnownServerDivergences.DeleteDoesNotCascade.Explains; + + using (Assert.EnterMultipleScope()) + { + Assert.That(explains(getChanges, Missing("/*/payload", "\"owner\",\"owningRelatedElement\"")), Is.True, "the reference to the deleted owner is gone"); + Assert.That(explains(getChanges, Missing("/*/payload", "\"owner\"")), Is.False, "derived properties alone are another divergence"); + Assert.That(explains(getChanges, Missing("/*/payload", "\"owningRelatedElement\",\"ownedRelatedElement\"")), Is.False, "a missing non-derived property other than the owner"); + Assert.That(explains(getProject, Missing("", "\"owningRelatedElement\"")), Is.False, "only a read at a commit"); + Assert.That(explains(getElement, Missing("", "\"owningRelatedElement\"")), Is.True, "an element read at a later commit"); + Assert.That(explains(new EndpointCall(null, "GET /unknown", HttpStatusCode.OK), Missing("", "\"owningRelatedElement\"")), Is.False, "a request that addresses no operation"); + Assert.That(explains(getChanges, new ContractViolation(ContractViolationKind.InvalidJson, "/*/payload required: Required properties [\"owningRelatedElement\"] are not present")), Is.False); + } + } + [Test] public void VerifyElementsWithoutDerivedProperties() { diff --git a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs index 1db95d977..668d11811 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ModelBuilderTestFixture.cs @@ -85,6 +85,7 @@ public void VerifyCopy() var copy = ModelBuilder.Copy(dto); copy.DeclaredName = "Copy"; copy.AliasIds.Add("second"); + copy.OwnedRelationship.Add(Guid.NewGuid()); using (Assert.EnterMultipleScope()) { @@ -93,6 +94,7 @@ public void VerifyCopy() Assert.That(copy.Id, Is.EqualTo(dto.Id)); Assert.That(dto.DeclaredName, Is.EqualTo("Original")); Assert.That(dto.AliasIds, Is.EqualTo((string[])["first"])); + Assert.That(dto.OwnedRelationship, Is.Empty, "a reference list of the copy is its own"); } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs index e12b3a22e..a07259b0c 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/CoreModelTestFixture.cs @@ -9,6 +9,7 @@ namespace SySML2.NET.REST.Tests.HelpersTests.Models { + using System; using System.IO; using System.Linq; using System.Text; @@ -16,11 +17,14 @@ namespace SySML2.NET.REST.Tests.HelpersTests.Models using NUnit.Framework; + using SysML2.NET.Core.DTO.Root.Elements; using SysML2.NET.Serializer.Json; using SySML2.NET.REST.Tests.Helpers; using SySML2.NET.REST.Tests.Helpers.Models; + using PocoFeature = SysML2.NET.Core.POCO.Core.Features.Feature; + [TestFixture] public class CoreModelTestFixture { @@ -57,6 +61,8 @@ public void VerifyCoreModel() Assert.That(json, Does.Not.Contain("00000000-0000-0000-0000-000000000000")); Assert.That(model.Builder.WithoutDerivedValues, Is.Empty); Assert.That(model.FirstEnd.IsEnd && model.SecondEnd.IsEnd, Is.True); + Assert.That(dtos.OfType().Where(relationship => relationship.IsImplied).Select(relationship => relationship.OwningRelatedElement), Is.EqualTo((Guid?[])[model.Builder.Find("core/f").Id]), "one implied relationship, owned by f"); + Assert.That(dtos.Where(dto => dto.IsImpliedIncluded).Select(dto => dto.DeclaredName), Is.EqualTo((string[])["f"]), "the owner of an implied relationship includes its implied relationships"); } Assert.That(new CoreModel(new RootModel()).Builder.ToDtos().Select(dto => dto.Id), Is.EqualTo(dtos.Select(dto => dto.Id))); diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs index 5aa26dc15..8543bb32b 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/KerMLUpdateModelTestFixture.cs @@ -34,6 +34,7 @@ private static readonly (string Metaclass, string Element, string Property)[] Re [ ("Annotation", "root/Note/about Nested", "Annotation.AnnotatedElement"), ("Dependency", "root/Uses", "Dependency.Supplier"), + ("Dependency", "root/Uses", "Dependency.Client"), ("NamespaceImport", "root/Nested/import Library", "NamespaceImport.ImportedNamespace"), ("MembershipImport", "root/Nested/import LibAlias", "MembershipImport.ImportedMembership"), ("Membership", "root/Space/LibAlias", "Membership.MemberElement"), @@ -115,6 +116,10 @@ public void VerifyKerMLUpdateModel() Assert.That(Value(byId, Element(model.Builder, "root/Nested/import Library").Id, "NamespaceImport.ImportedNamespace"), Is.EqualTo(Element(model.Builder, "root/Space").Id)); Assert.That(Value(byId, Element(model.Builder, "kernel/a/value/42").Id, "LiteralInteger.Value"), Is.EqualTo(43)); Assert.That(Value(byId, Element(model.Builder, "kernel/inv").Id, "Invariant.IsNegated"), Is.False); + Assert.That(Value(byId, Element(model.Builder, "kernel/sum").Id, "OperatorExpression.Operator"), Is.EqualTo("-")); + Assert.That(Value(byId, Element(model.Builder, "kernel/b").Id, "Feature.IsEnd"), Is.True, "a feature with multiplicity [1] and no direction becomes an end feature"); + Assert.That(Differs(before, byId, Element(model.Builder, "core/f").Id, "Element.IsImpliedIncluded"), Is.True, "the implied type featuring of f is no longer included"); + Assert.That(dtos.OfType().Where(relationship => relationship.IsImplied), Is.Empty); Assert.That(corePackage.OwnedRelationship, Is.EqualTo((Guid[])[.. corePackageBefore.OwnedRelationship, chain.OwningRelationship.Id, model.Added.OwningRelationship.Id]), "U4: Core is extended"); Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo((string[])["kernel/sum", "kernel/index", "kernel/select", "kernel/collect", "kernel/chain"])); } diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs new file mode 100644 index 000000000..13a5a6d1d --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs @@ -0,0 +1,115 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using NUnit.Framework; + + using SysML2.NET.Core.DTO.Root.Elements; + using SysML2.NET.Core.DTO.Root.Namespaces; + using SysML2.NET.Core.DTO.Systems.Ports; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + using PocoLiteralRational = SysML2.NET.Core.POCO.Kernel.Expressions.LiteralRational; + + [TestFixture] + public class MoveModelTestFixture + { + private static readonly string[] MovedProperties = + [ + "Specialization.Specific", "Conjugation.ConjugatedType", "Disjoining.TypeDisjoined", "Subclassification.Subclassifier", + "FeatureTyping.TypedFeature", "Subsetting.SubsettingFeature", "Redefinition.RedefiningFeature", "FeatureInverting.FeatureInverted", + "TypeFeaturing.FeatureOfType", "TypeFeaturing.FeaturingType", "PortConjugation.OriginalPortDefinition", "Relationship.Source", + "Relationship.OwningRelatedElement", "Relationship.OwnedRelatedElement", "Element.OwningRelationship" + ]; + + [Test] + public void VerifyMoveModel() + { + Assert.That(() => new MoveModel(null), Throws.ArgumentNullException); + + var root = new RootModel(); + var atStep2 = root.Builder.ToDtos(); + var model = new MoveModel(root); + var dtos = model.Builder.ToDtos(); + var changed = ModelBuilder.Changed(atStep2, dtos); + var before = dtos.ToDictionary(dto => dto.Id); + var listsBefore = dtos.ToDictionary(dto => dto.Id, dto => (Guid[])[.. dto.OwnedRelationship]); + var moveScope = model.Builder.Elements.Where(entry => entry.Name.StartsWith("move/", StringComparison.Ordinal)).Select(entry => entry.Element.Id).ToHashSet(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(() => model.Moved(null), Throws.ArgumentNullException); + Assert.That(dtos.Select(dto => dto.Id), Is.Unique); + Assert.That(changed.Where(dto => atStep2.Any(earlier => earlier.Id == dto.Id)).Select(dto => dto.Id), Is.EqualTo((Guid[])[root.Root.Id]), "only the root package changes, to own the new package"); + Assert.That(model.Moves.Select(move => before[move.Relationship].GetType().Name), Is.EquivalentTo((string[])["Specialization", "Conjugation", "Disjoining", "Subclassification", "FeatureTyping", "Subsetting", "FeatureInverting", "TypeFeaturing", "Redefinition", "OwningMembership", "OwningMembership"])); + Assert.That(model.Moves.Where(move => ((IRelationship)before[move.Relationship]).OwningRelatedElement != move.From), Is.Empty, "each relationship starts out owned by its first owner"); + Assert.That(ConjugatedPortDefinitionsOf(before, model.FirstPortDefinition.Id), Is.EqualTo((Guid[])[model.FirstConjugatedPortDefinition.Id]), "a port definition owns exactly one conjugated port definition"); + Assert.That(ConjugatedPortDefinitionsOf(before, model.SecondPortDefinition.Id), Is.EqualTo((Guid[])[model.SecondConjugatedPortDefinition.Id])); + } + + var moved = model.Moved(dtos); + var movedById = moved.ToDictionary(dto => dto.Id); + var after = dtos.Select(dto => movedById.GetValueOrDefault(dto.Id, dto)).ToDictionary(dto => dto.Id); + var unmoved = MovedProperties.Where(name => + { + var property = DtoMetadata.DeclaredProperties.Single(candidate => candidate.Name == name); + return !moved.Any(dto => property.Interface.IsInstanceOfType(dto) && !DtoMetadata.ValueEquals(property.ValueOf(dto), property.ValueOf(before[dto.Id]))); + }); + + var ownedButNotOwning = after.Values.SelectMany(owner => owner.OwnedRelationship.Where(id => ((IRelationship)after[id]).OwningRelatedElement != owner.Id).Select(id => $"{owner.Id} owns {id}")); + var owningButNotOwned = after.Values.OfType().SelectMany(relationship => relationship.OwnedRelatedElement.Where(id => after[id].OwningRelationship != relationship.Id).Select(id => $"{relationship.Id} owns {id}")); + + using (Assert.EnterMultipleScope()) + { + Assert.That(moved.Select(dto => dto.Id), Is.SubsetOf(moveScope), "only the content of the step moves"); + Assert.That(unmoved, Is.Empty, "U5: each listed property changes"); + Assert.That(model.Moves.Where(move => !after[move.To].OwnedRelationship.Contains(move.Relationship) || after[move.From].OwnedRelationship.Contains(move.Relationship)), Is.Empty, "each relationship leaves its first owner for its second"); + Assert.That(model.Moves.Where(move => ((IRelationship)after[move.Relationship]).OwningRelatedElement != move.To), Is.Empty); + Assert.That(model.Moves.Where(move => !((IRelationship)after[move.Relationship]).Source.SequenceEqual([move.To])), Is.Empty, "the source end of each moved relationship is its new owner"); + Assert.That(ownedButNotOwning, Is.Empty, "every owned relationship has its owner as owning related element"); + Assert.That(owningButNotOwned, Is.Empty, "every owned related element has its owning relationship"); + Assert.That(after.Values.OfType().Where(membership => ((IMembership)membership).MemberElement != membership.OwnedRelatedElement.Single()), Is.Empty, "the member element of an owning membership is its owned member element"); + Assert.That(ConjugatedPortDefinitionsOf(after, model.FirstPortDefinition.Id), Is.EqualTo((Guid[])[model.SecondConjugatedPortDefinition.Id]), "after the moves, each port definition still owns exactly one conjugated port definition"); + Assert.That(ConjugatedPortDefinitionsOf(after, model.SecondPortDefinition.Id), Is.EqualTo((Guid[])[model.FirstConjugatedPortDefinition.Id])); + Assert.That(after.Values.OfType().Where(conjugation => after[after[conjugation.ConjugatedType].OwningRelationship!.Value] is not IRelationship { OwningRelatedElement: { } owner } || owner != conjugation.OriginalPortDefinition), Is.Empty, "a conjugated port definition conjugates the port definition that owns it"); + Assert.That(after[model.First.Id].OwningRelationship, Is.EqualTo(before[model.Second.Id].OwningRelationship)); + Assert.That(after[model.Second.Id].OwningRelationship, Is.EqualTo(before[model.First.Id].OwningRelationship)); + Assert.That(dtos.Where(dto => !dto.OwnedRelationship.SequenceEqual(listsBefore[dto.Id])), Is.Empty, "the model passed in is not changed"); + } + + var fullRoot = new RootModel(); + var core = new CoreModel(fullRoot); + var kernel = new KernelModel(fullRoot, core); + _ = new KerMLUpdateModel(fullRoot, core, kernel); + var atStep11 = fullRoot.Builder.ToDtos(); + var inScenario = new MoveModel(fullRoot); + _ = new DeletionModel(fullRoot); + var scenarioDtos = inScenario.Builder.ToDtos(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(scenarioDtos.Select(dto => dto.Id), Is.Unique, "the content of step 12 shares the builder with steps 2 to 5"); + Assert.That(ModelBuilder.Changed(atStep11, scenarioDtos).Where(dto => atStep11.Any(earlier => earlier.Id == dto.Id)).Select(dto => dto.Id), Is.EquivalentTo((Guid[])[fullRoot.Root.Id, fullRoot.Builder.Find("kernel/rational").Id]), "only the root package, and the rational literal that its comparer reports as changed (#426)"); + Assert.That(inScenario.Moved(scenarioDtos).Select(dto => dto.Id), Is.EquivalentTo(moved.Select(dto => dto.Id)), "the moves are the same in the scenario"); + } + } + + private static Guid[] ConjugatedPortDefinitionsOf(IReadOnlyDictionary model, Guid portDefinitionId) + { + return [.. model[portDefinitionId].OwnedRelationship.Select(id => model[id]).OfType().SelectMany(membership => membership.OwnedRelatedElement).Where(id => model[id] is ConjugatedPortDefinition)]; + } + } +} diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs index 0707e15bc..29d6a6f59 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsStructureModelTestFixture.cs @@ -20,7 +20,9 @@ namespace SySML2.NET.REST.Tests.HelpersTests.Models using SysML2.NET.Core.DTO.Core.Features; using SysML2.NET.Core.DTO.Root.Elements; using SysML2.NET.Core.DTO.Systems.DefinitionAndUsage; + using SysML2.NET.Core.DTO.Systems.Occurrences; using SysML2.NET.Core.DTO.Systems.Parts; + using SysML2.NET.Core.DTO.Systems.Ports; using SysML2.NET.Core.POCO.Kernel.Expressions; using SysML2.NET.Serializer.Json; @@ -83,6 +85,22 @@ public void VerifySystemsStructureModel() Assert.That(variant.IsVariation, Is.False); Assert.That(dtos.OfType().Where(subsetting => subsetting.OwningRelatedElement == variant.Id).Select(subsetting => subsetting.SubsettedFeature), Is.EqualTo((Guid[])[variation.Id]), "a variant specializes its variation usage"); } + + var byId = dtos.ToDictionary(dto => dto.Id); + var individualUsage = (OccurrenceUsage)byId[model.IndividualUsage.Id]; + var spareTyping = dtos.OfType().Single(typing => typing.OwningRelatedElement == model.SparePort.Id); + var otherConjugation = dtos.OfType().Single(conjugation => conjugation.OwningRelatedElement == model.OtherConjugatedPortDefinition.Id); + + using (Assert.EnterMultipleScope()) + { + Assert.That(((OccurrenceDefinition)byId[model.IndividualDefinition.Id]).IsIndividual, Is.True); + Assert.That(individualUsage.IsIndividual, Is.True); + Assert.That(dtos.OfType().Where(typing => typing.OwningRelatedElement == individualUsage.Id).Select(typing => typing.Type), Is.EqualTo((Guid[])[model.IndividualDefinition.Id]), "an individual usage is typed by an individual definition"); + Assert.That(byId[model.PlainDefinition.Id].OwnedRelationship, Is.Empty, "a definition that may become a variation owns no feature membership"); + Assert.That(byId[model.PlainUsage.Id].OwnedRelationship, Is.Empty, "a usage that may become a variation owns no feature membership"); + Assert.That(spareTyping.ConjugatedPortDefinition, Is.EqualTo(model.ConjugatedPortDefinition.Id)); + Assert.That(otherConjugation.OriginalPortDefinition, Is.EqualTo(byId[model.OtherConjugatedPortDefinition.Id].OwningRelationship is { } membership ? ((IRelationship)byId[membership]).OwningRelatedElement : null), "a conjugated port definition conjugates the port definition that owns it"); + } } } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsUpdateModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsUpdateModelTestFixture.cs new file mode 100644 index 000000000..2e834e6c8 --- /dev/null +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/SystemsUpdateModelTestFixture.cs @@ -0,0 +1,127 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST.Tests.HelpersTests.Models +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using NUnit.Framework; + + using SysML2.NET.Core.DTO.Root.Elements; + + using SySML2.NET.REST.Tests.Helpers; + using SySML2.NET.REST.Tests.Helpers.Models; + + using PocoConjugatedPortTyping = SysML2.NET.Core.POCO.Systems.Ports.ConjugatedPortTyping; + using PocoElement = SysML2.NET.Core.POCO.Root.Elements.IElement; + using PocoFeatureValue = SysML2.NET.Core.POCO.Kernel.FeatureValues.FeatureValue; + + [TestFixture] + public class SystemsUpdateModelTestFixture + { + private static readonly (string Element, string Property)[] Changes = + [ + ("systems structure/Ind", "OccurrenceDefinition.IsIndividual"), + ("systems structure/solo", "OccurrenceUsage.IsIndividual"), + ("systems structure/Plain", "Definition.IsVariation"), + ("systems structure/bare", "Usage.IsVariation"), + ("systems structure/ts", "OccurrenceUsage.PortionKind"), + ("systems behaviour/limit", "Feature.IsConstant"), + ("systems behaviour/limit", "Feature.IsVariable"), + ("systems behaviour/R/assumed/membership", "RequirementConstraintMembership.Kind"), + ("systems behaviour/R/required/membership", "RequirementConstraintMembership.Kind"), + ("systems behaviour/Par", "StateDefinition.IsParallel"), + ("systems behaviour/pu", "StateUsage.IsParallel"), + ("systems behaviour/St/entry/membership", "StateSubactionMembership.Kind"), + ("systems behaviour/St/exit/membership", "StateSubactionMembership.Kind"), + ("systems behaviour/t/Trigger/membership", "TransitionFeatureMembership.Kind"), + ("systems behaviour/accept at/trigger", "TriggerInvocationExpression.Kind") + ]; + + [Test] + public void VerifySystemsUpdateModel() + { + var (structure, behavior) = BuildToStep7(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(() => new SystemsUpdateModel(null, behavior), Throws.ArgumentNullException); + Assert.That(() => new SystemsUpdateModel(structure, null), Throws.ArgumentNullException); + } + + (structure, behavior) = BuildToStep7(); + + var atStep7 = behavior.Builder.ToDtos(); + var before = atStep7.ToDictionary(dto => dto.Id); + List withoutDerivedValues = [.. behavior.Builder.WithoutDerivedValues]; + var systemsMetaclasses = behavior.Builder.Elements + .Where(entry => entry.Name.StartsWith("systems ", StringComparison.Ordinal)) + .Select(entry => entry.Element.GetType().Name) + .Distinct() + .ToList(); + + var model = new SystemsUpdateModel(structure, behavior); + var dtos = model.Builder.ToDtos(); + var after = dtos.ToDictionary(dto => dto.Id); + var changed = ModelBuilder.Changed(atStep7, dtos); + + var limit = model.Builder.Find("systems behaviour/limit"); + var initialValue = limit.OwnedRelationship.OfType().Single(); + var spareTyping = structure.SparePort.OwnedRelationship.OfType().Single(); + var namesById = model.Builder.Elements.ToDictionary(entry => entry.Element.Id, entry => entry.Name); + var rational = model.Builder.Find("kernel/rational").Id; + var renamed = changed.Where(dto => dto.Id != rational && dto.DeclaredName?.EndsWith(" renamed") == true).ToList(); + var unchanged = Changes.Where(change => !Differs(before, after, model.Builder.Find(change.Element).Id, change.Property)).Select(change => $"{change.Element} {change.Property}"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(dtos, Has.Count.EqualTo(atStep7.Count), "the update creates nothing"); + Assert.That(systemsMetaclasses.Where(metaclass => !changed.Any(dto => dto.GetType().Name == metaclass && dto.DeclaredName?.EndsWith(" renamed") == true)), Is.Empty, "U1: every metaclass of steps 6 and 7 has a renamed instance"); + Assert.That(renamed.Where(dto => dto.DeclaredShortName == before[dto.Id].DeclaredShortName || dto.DeclaredShortName?.EndsWith('2') != true), Is.Empty, "U1 also changes the short name"); + Assert.That(changed.Where(dto => !namesById[dto.Id].StartsWith("systems structure/", StringComparison.Ordinal) && !namesById[dto.Id].StartsWith("systems behaviour/", StringComparison.Ordinal)).Select(dto => dto.Id), Is.EqualTo((Guid[])[rational]), "only the content of steps 6 and 7, and the rational literal that its comparer reports as changed (#426)"); + Assert.That(unchanged, Is.Empty, "U2: each listed attribute changed"); + Assert.That(Differs(before, after, initialValue.Id, "FeatureValue.IsInitial"), Is.True); + Assert.That(Value(after, spareTyping.Id, "ConjugatedPortTyping.ConjugatedPortDefinition"), Is.EqualTo(structure.OtherConjugatedPortDefinition.Id)); + Assert.That(Value(after, structure.PlainDefinition.Id, "Type.IsAbstract"), Is.True, "a variation is abstract"); + Assert.That(Value(after, structure.PlainUsage.Id, "Type.IsAbstract"), Is.True, "a variation is abstract"); + Assert.That(Value(after, limit.Id, "Feature.IsVariable"), Is.False); + Assert.That(Value(after, initialValue.Id, "FeatureValue.IsInitial"), Is.False, "an initial value needs a variable feature"); + Assert.That(model.Builder.WithoutDerivedValues, Is.EquivalentTo(withoutDerivedValues), "no changed element loses its derived values"); + } + } + + private static (SystemsStructureModel Structure, SystemsBehaviorModel Behavior) BuildToStep7() + { + var root = new RootModel(); + var core = new CoreModel(root); + var kernel = new KernelModel(root, core); + _ = new KerMLUpdateModel(root, core, kernel); + var structure = new SystemsStructureModel(root); + + return (structure, new SystemsBehaviorModel(root, structure)); + } + + private static bool Differs(IReadOnlyDictionary before, IReadOnlyDictionary after, Guid id, string property) + { + return !DtoMetadata.ValueEquals(Value(before, id, property), Value(after, id, property)); + } + + private static object Value(IReadOnlyDictionary dtos, Guid id, string property) + { + var dto = dtos[id]; + + var metamodelProperty = DtoMetadata.PropertiesOf(dto.GetType()).SingleOrDefault(candidate => candidate.Name == property) + ?? throw new ArgumentException($"{dto.GetType().Name} has no non-derived property {property}", nameof(property)); + + return metamodelProperty.ValueOf(dto); + } + } +} diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index 2c578480c..bddf0d7c6 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -235,11 +235,11 @@ a step ignores itself only when the state it builds on is missing. The verdict a | 5 | **Update the KerML model** | U1–U4 (§6.1) on step 2–4 content | 15, 17, 20; `DiffAsync` `kernel` → head shows `UPDATED` (24) | | 6 | **Branch, SysML structure** | **branch** `systems` from head (7, 6, 8); commits with `branchId`: definitions and usages, attributes, enumerations, occurrences, items, parts, ports (incl. conjugated), connections, interfaces, allocations, flows (31) | 15 with `branchId`; as step 2 on the branch | | 7 | **SysML behaviour and requirements** | actions (all node and loop kinds), states and transitions, calculations, constraints, requirements, concerns, cases, analysis / verification / use cases, views, viewpoints, renderings, metadata (58) | as step 6 | -| 8 | **Merge** | update the same element on default and on `systems` → merge reports the conflict (`MergeConflictException`, `MergeResult.conflict`); merge again with a resolution body; then a clean merge of the remaining `systems` work; U1–U2 on SysML content after merge | 25, 24, 8 | +| 8 | **Merge** | update the same element on default and on `systems` → merge reports the conflict (`MergeConflictException`, `MergeResult.conflict`); merge again with a resolution body; then a clean merge of the remaining `systems` work; U1–U2 on SysML content, committed on `systems` before the merges so that they do not depend on a working merge | 25, 24, 8 | | 9 | **Queries** | `POST` a query with an `or` `CompositeConstraint` holding a nested `and` and `PrimitiveConstraint`s; across the step's queries all 7 `Operator` literals and `inverse`; `select`; list, get, `PUT`, results three ways, at the default head and at the `kernel` commit; negative cases; `DELETE` | 27, 26, 28, 29, 31, 32, 33, 30 | | 10 | **Project usage** | second project `UsedLibrary` with a small model; **branch** `data` from the default head; a commit of a `ProjectUsage` of the library's commit; the project usage of a library element; `excludeUsed` on elements and roots | 2, 7, 15, 21, 19, 22 | | 11 | **External data** | on `data`: commit `ExternalData` and an `ExternalRelationship` to the root package, update both, delete both | 15, 17, 18 | -| 12 | **Delete model elements** | commit a package `Deletions` built for the cases D1–D3 (§6.2), then one commit per case deleting elements with their owning memberships (`payload = null`) and updating the owner's `ownedRelationship` in the same commit; the deleted elements answer 404 at the new commit and are readable at the previous one; `DiffAsync` shows `DELETED` | 15, 19, 20, 24 | +| 12 | **Move and delete model elements** | commit a package `Moves` for U5 (§6.1) and a package `Deletions` built for the cases D1–D3 (§6.2); one commit moves relationships to new owners; then one commit per case deleting elements with their owning memberships (`payload = null`) and updating the owner's `ownedRelationship` in the same commit; the deleted elements answer 404 at the new commit and are readable at the previous one; `DiffAsync` shows `DELETED` | 15, 19, 20, 24 | | 13 | **Tear down** | delete the tag `kernel` (13), the branches `systems` and `data` (9), the `UsedLibrary` project and the main project (5); each is unreadable and unlisted afterwards; deleting a tag or branch again answers 404, a project a client error, as the OpenAPI document declares no 404 for it; negative cases (§6.3) | 13, 9, 5, 3, 8, 12, 10, 6, 1, 22 | | 14 | **Coverage verdict** | — | asserts §7 | @@ -286,6 +286,15 @@ feature. A connector, flow or association is retargeted through the reference or | U2 | the carried non-derived attribute changed (flip a boolean, another literal value, another enum literal) | every row of A.3 / A.4 | | U3 | a relationship end retargeted (`FeatureTyping.type`, `Redefinition.redefinedFeature`, …) | the 62 concrete `Relationship` subclasses | | U4 | an ordered collection reordered, extended and shrunk (`ownedRelationship` of a `Namespace`) | one per metamodel package — ordering survives the round trip; only *extended* for now: the public SDK cannot reorder or shrink an ownership list (#427) | +| U5 | a relationship moved to a new owner, which becomes its source end (`Specialization.specific`, `FeatureTyping.typedFeature`, …); two port definitions exchanging their conjugated port definitions, so each still owns exactly one (`validatePortDefinitionConjugatedPortDefinition`); two members exchanging their owning memberships | every relationship whose source end is its owner, in step 12 (`Helpers/Models/MoveModel.cs`): the public SDK cannot take a relationship out of an ownership list (#427), so the moved content is built in a model builder of its own, with the same names and ids and correct derived values, and the moves come after the last commit built from the scenario's model builder | + +KerML lets a relationship's source end differ from its owner, but the owner's derived sets +(`ownedSpecialization`, `ownedTypeFeaturing`, …) select by source end, so a moved relationship +changes both. The SysML part of U2 (step 8) keeps the constraints it touches: a variation is +abstract and owns no feature memberships, an initial value needs a variable feature, the subaction +kinds of a state stay unique, an accept action stays an action as an effect, and the trigger of +`accept at` becomes a `when` trigger, the kind its Boolean argument fits. Step 5 makes the feature +`b`, with multiplicity `[1]` and no direction, an end feature. ### 6.2 Delete scenarios @@ -322,6 +331,13 @@ Computed from what the **server returned**, not from what was sent: verdict until a step creates it). - **Attributes**: for every non-derived property (`[Property(isDerived: false)]` on the generated DTO interfaces), some element read back carried a non-default value, and some update changed it. + Exempt, each with its reason in `CoverageVerdict`: + - from both, a property whose value a constraint fixes: the operators of collect, feature chain, + index and select expressions, `ConnectionDefinition.isSufficient`, + `EnumerationDefinition.isVariation`, `Expose.isImportAll` and `visibility`, and the `kind` of a + framed concern or requirement verification membership; + - from "changed": `Element.elementId`, which "must not change during the lifetime of the + Element" (KerML 1.0, Clause 8.3.2.1.2). - **Literals**: every enumeration literal was read back at least once. - **Endpoints**: `EndpointRecorder` saw every `(method, path template)` of `Resources/ptc-25-02-30.json` (35) with a success status, and with a client error status where @@ -377,7 +393,8 @@ Known divergences of the pinned build. Observed, in `Helpers/KnownServerDivergen - `ProjectUsageAsArray`: the project usage of an element is answered as an array of every project usage of the commit, whatever the element, so the client cannot read it (step 10); - `DeleteDoesNotCascade`: deleting an element leaves the elements it owns in the model, listed - and readable, and removes their reference to it, which the commit lists as a further change + and readable, and removes their reference to it, which the commit lists as a further change; a + read at a later commit returns such an element without the required `owningRelatedElement` (§6.2 D3, step 12); - `DeleteUnknownBranchFails`: deleting an unknown branch answers 500, not 404 (step 13); deleting a deleted tag or branch answers 200 with its record again, which `UnknownResourceAccepted` covers; diff --git a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs index ef5b2ab0d..b0f033116 100644 --- a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs +++ b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs @@ -114,7 +114,11 @@ public void TearDown() var unverified = calls[this.verifiedCalls..]; this.verifiedCalls = calls.Count; - OpenApiConformance.Verify(unverified, KnownServerDivergences.All); + var divergences = TestContext.CurrentContext.Test.MethodName == nameof(this.VerifyDeletions) + ? KnownServerDivergences.All + : [.. KnownServerDivergences.All.Where(divergence => divergence != KnownServerDivergences.DeleteDoesNotCascade)]; + + OpenApiConformance.Verify(unverified, divergences); } [Test] @@ -324,6 +328,11 @@ public async Task VerifyMerge() { var systems = this.state.BranchIds["systems"]; + var update = new SystemsUpdateModel(this.structureModel, this.behaviorModel); + var updated = await this.CommitModelAsync(update.Builder, "SysML update", systems); + + await this.VerifyCommittedModelAsync(updated, this.structureModel.Part.Id); + var projectId = this.state.ProjectId!.Value; var defaultBranch = this.state.DefaultBranchId!.Value; var defaultModel = this.state.ExpectedModels[this.state.HeadCommitId.Value]; @@ -566,12 +575,15 @@ public async Task VerifyDeletions() Assert.Ignore("the default branch has no model to delete from"); } + var moves = new MoveModel(this.rootModel); var deletion = new DeletionModel(this.rootModel); - var created = await this.CommitModelAsync(deletion.Builder, "Content to delete"); + var created = await this.CommitModelAsync(deletion.Builder, "Content to move and delete"); using (Assert.EnterMultipleScope()) { - await this.readBack.VerifyCommitAsync(created.Commit, created.BranchId, created.PreviousHead, created.Changed); + await this.VerifyCommittedModelAsync(created, moves.Moves[0].From); + + await this.MoveAsync(moves); await this.DeleteAsync([deletion.Single.Id], deletion.Package.Id, "D1, a package and its owning membership"); await this.DeleteAsync([deletion.First.Id, deletion.Second.Id], deletion.Emptied.Id, "D2, the whole content of a package"); @@ -797,6 +809,20 @@ private Task ExpectNotFoundAsync(Func call, ServerDivergence tolerated = n return KnownServerDivergences.ExpectNotFoundAsync(call, () => this.httpClientFactory.Recorder.LastCall, tolerated, description); } + private async Task MoveAsync(MoveModel moves) + { + var branch = this.state.DefaultBranchId!.Value; + var previous = this.state.ExpectedModels[this.state.BranchHeads[branch]]; + var moved = moves.Moved(previous); + var movedById = moved.ToDictionary(element => element.Id); + List model = [.. previous.Select(element => movedById.GetValueOrDefault(element.Id, element))]; + + var committed = await this.CommitElementsAsync(model, moved, "U5, relationships moved to new owners", branch); + + await this.VerifyCommittedModelAsync(committed, moves.Moves[0].To); + await this.readBack.VerifyDiffAsync(committed.PreviousHead!.Value, committed.Commit.Id, moved); + } + private async Task VerifyCommittedModelAsync((Commit Commit, IReadOnlyList Model, IReadOnlyList Changed, Guid? PreviousHead, Guid BranchId) committed, Guid relationshipSubjectId) { using (Assert.EnterMultipleScope()) diff --git a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md index 2921034ba..815d2d509 100644 --- a/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md +++ b/SySML2.NET.REST.Tests/TEST_PROJECT_STRUCTURE.md @@ -29,7 +29,9 @@ SySML2.NET.REST.Tests/ │ ├── KerMLUpdateModel.cs step 5: updates U1–U4 of steps 2–4 │ ├── SystemsStructureModel.cs step 6: SysML structure, on the branch systems │ ├── SystemsBehaviorModel.cs step 7: SysML behaviour, requirements, cases and views +│ ├── SystemsUpdateModel.cs step 8: updates U1–U2 of steps 6–7 │ ├── LibraryModel.cs step 10: the model of the project that the main model uses +│ ├── MoveModel.cs step 12: the content that update U5 moves │ └── DeletionModel.cs step 12: the content that the deletion cases delete ├── HelpersTests/ offline: one fixture per helper, mirroring Helpers/ │ ├── FlexoJwtTestFixture.cs, ModelBuilderTestFixture.cs, … @@ -104,7 +106,7 @@ Session → PsmApiClient → HttpClient | `ModelBuilder` | Holds the whole model across the steps: each step starts its own scope (`BeginStep`) and creates POCOs with deterministic ids, wired with `AssignOwnership`. It converts them with the Dal's `ToDto(includeDerivedProperties: true)`, `Changed` selects the delta a commit sends, `Copy` copies a DTO for a change outside the builder, `OwnedTree` finds everything an element owns, and `Find` looks an element up by its scoped name. An element whose derived values cannot be computed without the model library is converted without them and listed in `WithoutDerivedValues`. POCOs are used because a hand-built DTO cannot set members that a derived property redefines. | | `ScenarioQueries` | The queries of step 9, each with a predicate that picks its results from the expected model. | | `DeterministicGuid` | Name-based UUID v5 of `"/"`, so the elements have the same ids in every run. | -| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5), `SystemsStructureModel` (step 6), `SystemsBehaviorModel` (step 7), `LibraryModel` (step 10, in a second project), `DeletionModel` (step 12). The base class holds the helpers the steps share: naming, ownership, features, parameters, results, literals and multiplicities. | +| `Models/*` | One class per step, deriving from `StepModel`, describing what that step adds to or changes in the model: `RootModel` (step 2), `CoreModel` (step 3), `KernelModel` (step 4), `KerMLUpdateModel` (step 5), `SystemsStructureModel` (step 6), `SystemsBehaviorModel` (step 7), `SystemsUpdateModel` (step 8), `LibraryModel` (step 10, in a second project), `MoveModel` and `DeletionModel` (step 12). The base class holds the helpers the steps share: naming, ownership, features, parameters, results, literals and multiplicities. | ### 5. Checking what came back @@ -119,7 +121,7 @@ Session → PsmApiClient → HttpClient | Type | Responsibility | |---|---| -| `CoverageVerdict` | Lists what the scenario has not yet exercised: concrete metaclasses never sent; non-derived properties never set to a non-default value, or never changed; enumeration literals never used; OpenAPI operations never answered with a 2xx and with a 4xx. A 5xx answer does not count as coverage. | +| `CoverageVerdict` | Lists what the scenario has not yet exercised: concrete metaclasses never sent; non-derived properties never set to a non-default value, or never changed; enumeration literals never used; OpenAPI operations never answered with a 2xx and with a 4xx. A 5xx answer does not count as coverage. Properties whose value a constraint fixes, or that no update may change, are exempt, each with its reason. | | `DtoMetadata`, `MetamodelProperty` | Read the metaclasses and properties from the `[Class]`/`[Property]` decorators on the generated DTOs, so the lists keep up with the generator. | ## The scenario @@ -145,11 +147,11 @@ Having one `[Test]` per step goes against the one-test-per-method rule in `TESTI | 5 | `VerifyKerMLUpdate` | implemented, with the diff from the tag `kernel` | | 6 | `VerifySystemsStructure` | implemented, on the branch `systems` | | 7 | `VerifySystemsBehavior` | implemented, on the branch `systems` | -| 8 | `VerifyMerge` | implemented: a conflict, its resolution, and a clean merge into the default branch | +| 8 | `VerifyMerge` | implemented: the SysML update on `systems`, a conflict, its resolution, and a clean merge into the default branch | | 9 | `VerifyQueries` | implemented | | 10 | `VerifyProjectUsage` | implemented, on the branch `data` | | 11 | `VerifyExternalData` | implemented, on the branch `data` | -| 12 | `VerifyDeletions` | implemented: a deletion, an emptied package, and a deletion that must cascade | +| 12 | `VerifyDeletions` | implemented: relationships moved to new owners, a deletion, an emptied package, and a deletion that must cascade | | 13 | `VerifyTeardown` | implemented: tag, branches and both projects deleted | | 14 | `VerifyCoverage` | implemented, red by design | From ab59ac894eff4ad8cd67c129867f1ba0eed51fb9 Mon Sep 17 00:00:00 2001 From: samatstarion Date: Mon, 9 Nov 2026 16:02:23 +0100 Subject: [PATCH 10/11] [Update] Flexo integration scenario: drop the #428 workaround in ModelBuilder, list #425 and #428 as fixed (#407) --- SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs | 12 ++++-------- SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md | 16 ++++++++-------- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs index ff2f9f3c0..080de5d77 100644 --- a/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs +++ b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs @@ -34,8 +34,8 @@ namespace SySML2.NET.REST.Tests.Helpers public sealed class ModelBuilder { /// - /// The settable string and reference list properties per DTO class, which the Dal conversion shares with the - /// POCO (#428) and a memberwise copy shares with the DTO it copies + /// The settable string and reference list properties per DTO class, which a memberwise copy shares with the + /// DTO it copies /// private static readonly ConcurrentDictionary ListsByClass = new(); @@ -271,10 +271,6 @@ public TPoco Find(string scopedName) where TPoco : PocoElement /// computed, such as an operator expression without the model library, is converted without them and listed /// in /// - /// - /// Every DTO gets its own copy of the string lists that the Dal conversion shares with the POCO (#428), so that - /// a DTO stays the snapshot of the model at its commit when a later step changes the POCO. - /// /// /// The DTOs, in creation order /// @@ -289,7 +285,7 @@ public IReadOnlyList ToDtos() { try { - return Detach(entry.Convert(true)); + return entry.Convert(true); } catch (Exception) { @@ -298,7 +294,7 @@ public IReadOnlyList ToDtos() try { - return Detach(entry.Convert(false)); + return entry.Convert(false); } catch (Exception exception) { diff --git a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md index bddf0d7c6..7b5da9a24 100644 --- a/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md +++ b/SySML2.NET.REST.Tests/INTEGRATION_TEST_PLAN.md @@ -417,14 +417,11 @@ Client defects found so far, each red until fixed: - #424 — the JSON round trip loses non-derived members that a derived property redefines (`memberElement`, `memberName`, `source`, `target`); -- #425 — the PSM JSON serializers write `null` for optional references that the OpenAPI document - does not make nullable (`ProjectRequest.defaultBranch`, …); - #429 — `MergeAsync` sends its resolution elements without the derived properties that the `Data` schema of the merge body requires (step 8). -#425 also covers the `inverse: null` of a `PrimitiveConstraintRequest` that leaves `inverse` unset; -Flexo answers such a request 400. Step 9 sets `inverse` on every query but one, the query -definition sent with `GET`, so that #425 stays visible there while the other query operations run. +Step 9 sets `inverse` on every query but one, the query definition sent with `GET`, which checks +that an unset `inverse` is left out of the request. SDK defects found while building the fixture, outside the client: @@ -435,9 +432,12 @@ SDK defects found while building the fixture, outside the client: public API cannot reorder or shrink an ownership list or let any relationship other than an owning membership or an annotation own a related element. Step 3 therefore makes the feature chain of its `CrossSubsetting` a member of the package, and step 5 only extends (U4). -- #428 — the Dal conversions share value lists (`aliasIds`, `text`) between a POCO and its DTO, so a - later change to the POCO rewrites the expected model of an earlier commit; `ModelBuilder` gives - every DTO its own copy. + +Fixed defects, whose checks the scenario keeps: + +- #425 — the PSM JSON serializers wrote `null` for optional references that the OpenAPI document + does not make nullable (`ProjectRequest.defaultBranch`, `PrimitiveConstraintRequest.inverse`, …); +- #428 — the Dal conversions shared value lists (`aliasIds`, `text`) between a POCO and its DTO. ## 9. Open questions From 9108fa20cef7980946e6436342b6073de4f827cf Mon Sep 17 00:00:00 2001 From: samatstarion Date: Tue, 10 Nov 2026 17:57:12 +0100 Subject: [PATCH 11/11] [Update] Flexo integration scenario: resolve SonarQube findings in the REST test helpers (#407) --- .../Helpers/KnownServerDivergences.cs | 48 ++++++++++--------- .../Helpers/Models/KerMLUpdateModel.cs | 32 ++++++------- .../Helpers/Models/KernelModel.cs | 4 +- .../Helpers/Models/MoveModel.cs | 2 +- .../Helpers/Models/SystemsBehaviorModel.cs | 4 +- .../Helpers/OpenApiConformance.cs | 5 +- .../Helpers/OpenApiDocument.cs | 2 +- .../Helpers/OpenApiParameter.cs | 2 +- .../Helpers/ReadBackAssertions.cs | 2 +- .../Models/MoveModelTestFixture.cs | 8 ++-- .../HelpersTests/OpenApiContentTestFixture.cs | 2 +- .../OpenApiOperationTestFixture.cs | 2 +- .../ReadBackAssertionsTestFixture.cs | 2 +- .../FlexoModelScenarioTestFixture.cs | 2 +- 14 files changed, 61 insertions(+), 56 deletions(-) diff --git a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs index d47f58852..597c0a27d 100644 --- a/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs +++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs @@ -29,7 +29,7 @@ namespace SySML2.NET.REST.Tests.Helpers /// /// The expectations of the scenario stay those of the specification; only the outcome is reported differently. /// - public static class KnownServerDivergences + public static partial class KnownServerDivergences { /// /// The source revision of Flexo that the divergences were found in @@ -41,26 +41,6 @@ public static class KnownServerDivergences /// private static readonly HashSet OmittedRecordProperties = ["alias", "name", "description", "deleted"]; - /// - /// Matches a schema error that lists missing required properties, capturing their quoted names - /// - private static readonly Regex MissingRequired = new(@"^\S* required: Required properties \[(?[^\]]*)\] are not present$", RegexOptions.Compiled); - - /// - /// Matches a schema error on a list property sent as null - /// - private static readonly Regex NullList = new(@"^\S* type: Value is ""null"" but should be ""array""$", RegexOptions.Compiled); - - /// - /// Matches a schema error on a previousCommit sent as one object - /// - private static readonly Regex PreviousCommitObject = new(@"^\S*/previousCommit type: Value is ""object"" but should be ""array""$", RegexOptions.Compiled); - - /// - /// Matches the schema error on an item of an element list whose @type is a kind of data that is no element - /// - private static readonly Regex DataItemInElementList = new(@"^/\d+/@type const: ""(ExternalData|ExternalRelationship|ProjectUsage)"" is none of the types the schema admits$", RegexOptions.Compiled); - /// /// The path templates of the operations that list elements /// @@ -235,6 +215,30 @@ public static class KnownServerDivergences /// public static IReadOnlyList All { get; } = [RootsIgnoreOwningRelationship, DiffNotImplemented, MergeNotImplemented, MergeRequiresArrayBody, UnknownResourceNotFound, UnknownResourceAccepted, ErrorWithoutErrorBody, CreatedAnsweredOk, RecordsWithoutRequiredProperties, PreviousCommitAsObject, ElementsWithoutDerivedProperties, DatatypeIdNotUri, DataListedAsElements, ProjectUsageAsArray, QueryResultsProjected, QueryLosesNameAndDescription, InstanceOfRejected, QueryResultsGetNotImplemented, DeleteDoesNotCascade, DeleteUnknownBranchFails, DeletedProjectDeletedAgain]; + /// + /// Matches a schema error that lists missing required properties, capturing their quoted names + /// + [GeneratedRegex(@"^\S* required: Required properties \[(?[^\]]*)\] are not present$")] + private static partial Regex MissingRequired { get; } + + /// + /// Matches a schema error on a list property sent as null + /// + [GeneratedRegex(@"^\S* type: Value is ""null"" but should be ""array""$")] + private static partial Regex NullList { get; } + + /// + /// Matches a schema error on a previousCommit sent as one object + /// + [GeneratedRegex(@"^\S*/previousCommit type: Value is ""object"" but should be ""array""$")] + private static partial Regex PreviousCommitObject { get; } + + /// + /// Matches the schema error on an item of an element list whose @type is a kind of data that is no element + /// + [GeneratedRegex(@"^/\d+/@type const: ""(ExternalData|ExternalRelationship|ProjectUsage)"" is none of the types the schema admits$")] + private static partial Regex DataItemInElementList { get; } + /// /// Asserts that a call for an unknown resource fails with 404 Not Found, or reports the one tolerated divergence /// when the server answers the way it describes @@ -316,7 +320,7 @@ public static void Report(ServerDivergence divergence, string detail) /// /// The names, or null when the violation is about something else /// - private static IReadOnlyList MissingNames(ContractViolation violation) + private static List MissingNames(ContractViolation violation) { var match = MissingRequired.Match(violation.Message); diff --git a/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs index ed3a1a52e..b0c9ed856 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs @@ -64,7 +64,7 @@ public sealed class KerMLUpdateModel : StepModel var firstInstances = this.Builder.Elements.GroupBy(entry => entry.Element.GetType()).Select(group => group.First().Element).ToList(); - this.Rename(firstInstances); + Rename(firstInstances); this.ChangeAttributes(root); this.Retarget(core, kernel); this.Complete(firstInstances); @@ -76,6 +76,21 @@ public sealed class KerMLUpdateModel : StepModel /// public Classifier Added { get; private set; } + /// + /// U1: renames the first instance of every metaclass that steps 2 to 4 created + /// + /// + /// The first instance of every metaclass that steps 2 to 4 created + /// + private static void Rename(IReadOnlyList firstInstances) + { + foreach (var element in firstInstances) + { + element.DeclaredName = $"{element.DeclaredName ?? element.GetType().Name} renamed"; + element.DeclaredShortName = $"{element.DeclaredShortName ?? element.GetType().Name.ToLowerInvariant()}2"; + } + } + /// /// U2: changes every non-derived attribute that steps 2 to 4 set, to another legal value /// @@ -193,21 +208,6 @@ private void Complete(IReadOnlyList firstInstances) } } - /// - /// U1: renames the first instance of every metaclass that steps 2 to 4 created - /// - /// - /// The first instance of every metaclass that steps 2 to 4 created - /// - private void Rename(IReadOnlyList firstInstances) - { - foreach (var element in firstInstances) - { - element.DeclaredName = $"{element.DeclaredName ?? element.GetType().Name} renamed"; - element.DeclaredShortName = $"{element.DeclaredShortName ?? element.GetType().Name.ToLowerInvariant()}2"; - } - } - /// /// U3: retargets an end of every kind of KerML relationship that steps 2 to 4 created, keeping the model /// well-formed; a connector, flow or association is retargeted through the reference or typing of an end diff --git a/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs index d6d441d0e..2a4d4586c 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs @@ -220,7 +220,7 @@ public sealed class KernelModel : StepModel /// /// The argument feature /// - private IFeature Argument(IExpression expression, string name, IExpression value) + private Feature Argument(IExpression expression, string name, IExpression value) { var argument = this.Parameter(expression, name, FeatureDirectionKind.In, ParameterMembershipExtensions.ToDto); var argumentValue = this.Builder.Create($"{argument.ElementId}/value", FeatureValueExtensions.ToDto); @@ -546,7 +546,7 @@ private void Reference(IExpression expression, PocoElement element) /// /// The feature /// - private IFeature TypedFeature(IType owner, string name, IType type) => this.TypedFeature(owner, name, type, FeatureExtensions.ToDto); + private Feature TypedFeature(IType owner, string name, IType type) => this.TypedFeature(owner, name, type, FeatureExtensions.ToDto); /// /// Creates a feature of a given metaclass that a type owns, typed by another type diff --git a/SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs index cd47597dd..9d9caa010 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/MoveModel.cs @@ -212,7 +212,7 @@ public MoveModel(RootModel root) : this(root, false) /// /// The DTO of every element of this step that differs from its version in /// - public IReadOnlyList Moved(IReadOnlyList model) + public static IReadOnlyList Moved(IReadOnlyList model) { ArgumentNullException.ThrowIfNull(model); diff --git a/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs index 52ddc9c82..494607a51 100644 --- a/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs +++ b/SySML2.NET.REST.Tests/Helpers/Models/SystemsBehaviorModel.cs @@ -415,7 +415,7 @@ private TUsage Param(IType owner, string name, Func /// The redefined feature /// - private void Redefine(IFeature feature, IFeature redefined) + private void Redefine(ReferenceUsage feature, IFeature redefined) { var redefinition = this.Builder.Create($"{feature.ElementId}/redefinition", RedefinitionExtensions.ToDto); redefinition.RedefiningFeature = feature; @@ -643,7 +643,7 @@ private void Subset(IFeature feature, IFeature referenced) /// /// The value expression /// - private void Value(IFeature feature, IExpression value) + private void Value(ReferenceUsage feature, IExpression value) { feature.AssignOwnership(this.Builder.Create($"{feature.ElementId}/value", FeatureValueExtensions.ToDto), value); } diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs index 51fe5fd29..c77636675 100644 --- a/SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiConformance.cs @@ -23,12 +23,13 @@ namespace SySML2.NET.REST.Tests.Helpers /// Violations are grouped by operation, status, kind and message, with array indices folded, so that one shape of /// violation is reported once with its count and an example request. /// - public static class OpenApiConformance + public static partial class OpenApiConformance { /// /// Matches an array index in an instance location, e.g. the /3 of /3/identity /// - private static readonly Regex ArrayIndex = new(@"/\d+(?=[/ ])", RegexOptions.Compiled); + [GeneratedRegex(@"/\d+(?=[/ ])")] + private static partial Regex ArrayIndex { get; } /// /// Verifies that recorded calls conform to the OpenAPI document, and writes every violation to the test output diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs index 8c9184007..9ff904de4 100644 --- a/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiDocument.cs @@ -373,7 +373,7 @@ public JsonSchema Build(JsonNode schema, Uri baseUri = null) /// /// The built member for each @type /// - public IReadOnlyDictionary UnionMembers(JsonNode schema) + public Dictionary UnionMembers(JsonNode schema) { var byType = new Dictionary(StringComparer.Ordinal); var ambiguous = new HashSet(StringComparer.Ordinal); diff --git a/SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs b/SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs index 49e30a8fa..c9f58bd50 100644 --- a/SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs +++ b/SySML2.NET.REST.Tests/Helpers/OpenApiParameter.cs @@ -115,7 +115,7 @@ private JsonNode ToNode(string value) { "integer" when long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var integer) => JsonValue.Create(integer), "number" when double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) => JsonValue.Create(number), - "boolean" when bool.TryParse(value, out var boolean) && value == value.ToLowerInvariant() => JsonValue.Create(boolean), + "boolean" when bool.TryParse(value, out var boolean) && !value.Any(char.IsUpper) => JsonValue.Create(boolean), "array" => new JsonArray([.. value.Split(',').Select(item => (JsonNode)JsonValue.Create(item))]), _ => JsonValue.Create(value) }; diff --git a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs index 053d579bd..dba53255d 100644 --- a/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs +++ b/SySML2.NET.REST.Tests/Helpers/ReadBackAssertions.cs @@ -711,7 +711,7 @@ public async Task VerifyRootsAsync(string description, Func /// The elements read back, by id /// - private static void VerifyMemberships(IReadOnlyList expected, IReadOnlyDictionary readById) + private static void VerifyMemberships(IReadOnlyList expected, Dictionary readById) { foreach (var membership in expected.OfType()) { diff --git a/SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs index 13a5a6d1d..2ad9c66bd 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/Models/MoveModelTestFixture.cs @@ -51,7 +51,7 @@ public void VerifyMoveModel() using (Assert.EnterMultipleScope()) { - Assert.That(() => model.Moved(null), Throws.ArgumentNullException); + Assert.That(() => MoveModel.Moved(null), Throws.ArgumentNullException); Assert.That(dtos.Select(dto => dto.Id), Is.Unique); Assert.That(changed.Where(dto => atStep2.Any(earlier => earlier.Id == dto.Id)).Select(dto => dto.Id), Is.EqualTo((Guid[])[root.Root.Id]), "only the root package changes, to own the new package"); Assert.That(model.Moves.Select(move => before[move.Relationship].GetType().Name), Is.EquivalentTo((string[])["Specialization", "Conjugation", "Disjoining", "Subclassification", "FeatureTyping", "Subsetting", "FeatureInverting", "TypeFeaturing", "Redefinition", "OwningMembership", "OwningMembership"])); @@ -60,7 +60,7 @@ public void VerifyMoveModel() Assert.That(ConjugatedPortDefinitionsOf(before, model.SecondPortDefinition.Id), Is.EqualTo((Guid[])[model.SecondConjugatedPortDefinition.Id])); } - var moved = model.Moved(dtos); + var moved = MoveModel.Moved(dtos); var movedById = moved.ToDictionary(dto => dto.Id); var after = dtos.Select(dto => movedById.GetValueOrDefault(dto.Id, dto)).ToDictionary(dto => dto.Id); var unmoved = MovedProperties.Where(name => @@ -103,11 +103,11 @@ public void VerifyMoveModel() { Assert.That(scenarioDtos.Select(dto => dto.Id), Is.Unique, "the content of step 12 shares the builder with steps 2 to 5"); Assert.That(ModelBuilder.Changed(atStep11, scenarioDtos).Where(dto => atStep11.Any(earlier => earlier.Id == dto.Id)).Select(dto => dto.Id), Is.EquivalentTo((Guid[])[fullRoot.Root.Id, fullRoot.Builder.Find("kernel/rational").Id]), "only the root package, and the rational literal that its comparer reports as changed (#426)"); - Assert.That(inScenario.Moved(scenarioDtos).Select(dto => dto.Id), Is.EquivalentTo(moved.Select(dto => dto.Id)), "the moves are the same in the scenario"); + Assert.That(MoveModel.Moved(scenarioDtos).Select(dto => dto.Id), Is.EquivalentTo(moved.Select(dto => dto.Id)), "the moves are the same in the scenario"); } } - private static Guid[] ConjugatedPortDefinitionsOf(IReadOnlyDictionary model, Guid portDefinitionId) + private static Guid[] ConjugatedPortDefinitionsOf(Dictionary model, Guid portDefinitionId) { return [.. model[portDefinitionId].OwnedRelationship.Select(id => model[id]).OfType().SelectMany(membership => membership.OwnedRelatedElement).Where(id => model[id] is ConjugatedPortDefinition)]; } diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs index be3682434..aa23e41ba 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiContentTestFixture.cs @@ -102,6 +102,6 @@ public void VerifyCheckByType() } } - private static IReadOnlyList Kinds(IReadOnlyList violations) => violations.Select(violation => violation.Kind).ToList(); + private static List Kinds(IReadOnlyList violations) => violations.Select(violation => violation.Kind).ToList(); } } diff --git a/SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs index ea3f69d77..4d94c5422 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/OpenApiOperationTestFixture.cs @@ -130,7 +130,7 @@ public void VerifyOpenApiOperation() } } - private static IReadOnlyList Kinds(IReadOnlyList violations) => violations.Select(violation => violation.Kind).ToList(); + private static List Kinds(IReadOnlyList violations) => violations.Select(violation => violation.Kind).ToList(); private string Example(string name) { diff --git a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs index c9b53e936..bdcabb441 100644 --- a/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs +++ b/SySML2.NET.REST.Tests/HelpersTests/ReadBackAssertionsTestFixture.cs @@ -575,7 +575,7 @@ public async Task VerifyVerifyModelAsync() { var now = Interlocked.Increment(ref inFlight); Interlocked.Exchange(ref maximumInFlight, Math.Max(Interlocked.CompareExchange(ref maximumInFlight, 0, 0), now)); - await Task.Delay(5); + await Task.Delay(5, CancellationToken.None); recordedReads.Enqueue(new EndpointCall(null, $"GET /elements/{elementId}", HttpStatusCode.OK) { ResponseViolations = breakingFor.Contains(elementId) ? [breaking] : [] }); Interlocked.Decrement(ref inFlight); diff --git a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs index b0f033116..f6fc6deb2 100644 --- a/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs +++ b/SySML2.NET.REST.Tests/IntegrationTests/FlexoModelScenarioTestFixture.cs @@ -813,7 +813,7 @@ private async Task MoveAsync(MoveModel moves) { var branch = this.state.DefaultBranchId!.Value; var previous = this.state.ExpectedModels[this.state.BranchHeads[branch]]; - var moved = moves.Moved(previous); + var moved = MoveModel.Moved(previous); var movedById = moved.ToDictionary(element => element.Id); List model = [.. previous.Select(element => movedById.GetValueOrDefault(element.Id, element))];