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..f85e501ef
--- /dev/null
+++ b/SySML2.NET.REST.Tests/Helpers/CoverageVerdict.cs
@@ -0,0 +1,192 @@
+// ------------------------------------------------------------------------------------------------
+//
+//
+// 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();
+
+ ///
+ /// 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
+ ///
+ ///
+ /// 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 => !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();
+
+ 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();
+
+ 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..7e3314187
--- /dev/null
+++ b/SySML2.NET.REST.Tests/Helpers/EndpointRecorder.cs
@@ -0,0 +1,148 @@
+// ------------------------------------------------------------------------------------------------
+//
+//
+// 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.Diagnostics;
+ 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();
+
+ ///
+ /// 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
+ ///
+ ///
+ /// 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; }
+
+ ///
+ /// 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
+ ///
+ ///
+ /// 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 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)
+ {
+ RequestViolations = operation?.CheckRequest(request.RequestUri?.Query, request.Content?.Headers.ContentType?.MediaType, requestBody) ?? [],
+ 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;
+
+ 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..597c0a27d
--- /dev/null
+++ b/SySML2.NET.REST.Tests/Helpers/KnownServerDivergences.cs
@@ -0,0 +1,330 @@
+// ------------------------------------------------------------------------------------------------
+//
+//
+// 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 partial 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"];
+
+ ///
+ /// 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
+ ///
+ 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; 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
+ /// 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 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 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
+ ///
+ 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 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
+ ///
+ 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 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 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
+ ///
+ ///
+ /// 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
+ /// 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, 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
+ ///
+ ///
+ /// 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, ,
+ /// 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 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)
+ {
+ 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 List 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..080de5d77
--- /dev/null
+++ b/SySML2.NET.REST.Tests/Helpers/ModelBuilder.cs
@@ -0,0 +1,342 @@
+// ------------------------------------------------------------------------------------------------
+//
+//
+// 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 System.Reflection;
+
+ using SysML2.NET.Extensions.Core.DTO.Comparers;
+ 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;
+
+ ///
+ /// 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. One builder holds
+ /// the whole model, so a later step can wire into the elements of an earlier one.
+ ///
+ public sealed class ModelBuilder
+ {
+ ///
+ /// 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();
+
+ ///
+ /// 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
+ ///
+ private string scope;
+
+ ///
+ /// The created elements with their conversion, in creation order
+ ///
+ 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 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();
+ }
+
+ ///
+ /// 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
+ ///
+ ///
+ /// The DTO
+ ///
+ ///
+ /// The copy
+ ///
+ public static TElement Copy(TElement dto) where TElement : DtoElement
+ {
+ ArgumentNullException.ThrowIfNull(dto);
+
+ 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
+ ///
+ ///
+ /// 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()
+ };
+ }
+
+ ///
+ /// 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
+ ///
+ ///
+ /// 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()
+ {
+ 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(scopedName)
+ };
+
+ poco.ElementId = poco.Id.ToString();
+
+ this.entries.Add((scopedName, poco, includeDerivedProperties => toDto(poco, includeDerivedProperties)));
+
+ return poco;
+ }
+
+ ///
+ /// 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
+ ///
+ ///
+ /// The DTOs, in creation order
+ ///
+ ///
+ /// Thrown when an element cannot be converted, naming that element
+ ///
+ public IReadOnlyList ToDtos()
+ {
+ var withoutDerived = new List();
+
+ var dtos = this.entries.Select(entry =>
+ {
+ try
+ {
+ return entry.Convert(true);
+ }
+ catch (Exception)
+ {
+ withoutDerived.Add(entry.Name);
+ }
+
+ try
+ {
+ return entry.Convert(false);
+ }
+ catch (Exception 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 and reference list it holds
+ ///
+ ///
+ /// The DTO
+ ///
+ ///
+ /// The same DTO
+ ///
+ private static DtoElement Detach(DtoElement dto)
+ {
+ var lists = ListsByClass.GetOrAdd(dto.GetType(), type => type
+ .GetProperties(BindingFlags.Public | BindingFlags.Instance)
+ .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 lists)
+ {
+ switch (property.GetValue(dto))
+ {
+ case List strings:
+ property.SetValue(dto, new List(strings));
+ break;
+ case List references:
+ property.SetValue(dto, new List(references));
+ break;
+ }
+ }
+
+ 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..363c4ff89
--- /dev/null
+++ b/SySML2.NET.REST.Tests/Helpers/Models/CoreModel.cs
@@ -0,0 +1,220 @@
+// ------------------------------------------------------------------------------------------------
+//
+//
+// 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. The type featuring of f by A is marked implied, so f
+ /// includes its implied relationships (validateElementIsImpliedIncluded ).
+ ///
+ 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);
+
+ f.OwnedRelationship.OfType().Single().IsImplied = true;
+ f.IsImpliedIncluded = true;
+
+ 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/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/Models/KerMLUpdateModel.cs b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs
new file mode 100644
index 000000000..b0c9ed856
--- /dev/null
+++ b/SySML2.NET.REST.Tests/Helpers/Models/KerMLUpdateModel.cs
@@ -0,0 +1,294 @@
+// ------------------------------------------------------------------------------------------------
+//
+//
+// 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();
+
+ 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; }
+
+ ///
+ /// 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
+ ///
+ ///
+ /// 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 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;
+ 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;
+
+ this.Builder.Find("kernel/b").IsEnd = true;
+
+ 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/sum").Operator = "-";
+ 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;
+ }
+ }
+ }
+
+ ///
+ /// 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);
+ 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");
+
+ 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..2a4d4586c
--- /dev/null
+++ b/SySML2.NET.REST.Tests/Helpers/Models/KernelModel.cs
@@ -0,0 +1,581 @@
+// ------------------------------------------------------------------------------------------------
+//
+//
+// 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 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);
+ 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