Skip to content

Core dto validator is added. - #445

Open
zeynepatsoprasteria wants to merge 5 commits into
developmentfrom
406-feature-core-dto-validator
Open

zeynepatsoprasteria wants to merge 5 commits into
developmentfrom
406-feature-core-dto-validator

Conversation

@zeynepatsoprasteria

Copy link
Copy Markdown
Contributor

Prerequisites

  • I have written a descriptive pull-request title
  • I have verified that there are no overlapping pull-requests open
  • I have verified that I am following the SysML2.NET code style guidelines
  • I have provided test coverage for my change (where applicable)

Description

Implemented #406 for validation of Core DTO elements.

@zeynepatsoprasteria zeynepatsoprasteria linked an issue Nov 16, 2026 that may be closed by this pull request
4 of 5 tasks

@antoineatsoprasteria antoineatsoprasteria left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The collection rules mix three different concerns, which makes them look redundant and contradictory. I'd scope the generated rules to required values only, i.e. what the UML multiplicity demands.

Collections

  • Each RuleFor runs on its own, so NotNull() followed by Must(value => value == null || ...) says null is invalid and then tolerates it. A single chain (Cascade(CascadeMode.Stop).NotEmpty()...) covers both.
  • NotNull() on [0..*] isn't a model constraint: an empty [0..*] is valid. No rule is needed there.
  • The Distinct() and RuleForEach(...).NotEmpty() checks are about uniqueness and item validity, not required values. I'd drop them, or add them separately later if we want them.

Scalars

  • Optional references don't need the !HasValue || != Guid.Empty check.

Proposed mapping

  • [1] reference → NotEmpty(); [1] string → NotNull(); enum → IsInEnum(); other value types and optional scalars → no rule.
  • [0..*] → no rule; lower ≥ 1 → NotEmpty(), plus Count >= n when n > 1; finite upper → Count <= n, in the same chain.

Gap: required values lost through redefinition
Redefined properties are excluded, so a [1] requirement disappears when the redefining property is derived. For example, OwningMembership::ownedMemberElement [1] {derived} redefines memberElement and subsets ownedRelatedElement. As a result, OwningMembershipValidator has no rule for the member element. When a derived property with lower ≥ 1 subsets a non-derived collection, that collection should get the lower-bound rule (here OwnedRelatedElement.NotEmpty()). The same pattern shows up in other membership subclasses.

@samatstariongroup samatstariongroup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of 30fc4552

The rule mapping in the reworked DtoValidatorHelper is right. Checked against the KerML / SysML v2 metamodel for all 167 concrete metaclasses: every multiplicity rule matches, no rule sits on a derived property (the #406 requirement), and redefinition narrowing is handled correctly (Dependency.client / supplier, Membership.memberElement, the specialization family).

What blocks the merge is one missed step, not the design: the generator changed but its output was not regenerated. The list below is in working order. Steps 1 and 2 turn the build green; step 3 is the one real code change; the rest is small.

Almost everything is a change in DtoValidatorHelper.cs or a test. Nothing below asks you to touch a generated file by hand.

Step 1 — Regenerate (blocking)

dotnet test SysML2.NET.sln fails with 21 tests at this commit:

  • 19 × UmlCoreDtoValidatorGeneratorTestFixture.VerifyGenerateDtoValidatorAsync
  • MembershipValidatorTestFixture.VerifyValidate (line 47)
  • OwningMembershipValidatorTestFixture.VerifyValidate (line 33)

All 21 have the same cause. 30fc4552 changed DtoValidatorHelper.cs and core-dto-validator-uml-template.hbs, but the generated files still date from e0dd0abf. The shipped MembershipValidator still has the Distinct() / RuleForEach / NotNull() rules that the helper no longer emits, and OwningMembershipValidator lacks the new OwnedRelatedElement rule.

  • Regenerate the 167 files in SysML2.NET.Validation/Core/DTO/AutoGenValidator/
  • Refresh the 19 files in SysML2.NET.CodeGenerator.Tests/Expected/UML/Core/AutoGenDtoValidators/
  • Commit them together with the helper

Step 2 — Fix the fixture that regeneration will break (blocking)

SysML2.NET.Validation.Tests/Core/DTO/AutoGenValidator/RequirementConstraintMembershipValidatorTestFixture.cs:28 and :34 pass today only because the validator is stale. After step 1 the validator requires OwnedRelatedElement, the fixture leaves it empty, and both assertions fail.

  • Seed OwnedRelatedElement = [Guid.NewGuid()] in the valid DTO
  • Add the empty collection as a negative scenario, as OwningMembershipValidatorTestFixture does

Step 3 — Apply the raised lower bound to scalars too

DtoValidatorHelper.cs:150-156 passes the effective lower bound to QueryCollectionRules only; QueryScalarRules uses property.Lower. The same reasoning therefore gives a rule in one storage shape and none in the other:

Required derived property Storage it subsets Rule today
OwningMembership::ownedMemberElement [1..1] ownedRelatedElement [0..*] NotEmpty()
Membership::membershipOwningNamespace [1..1] owningRelatedElement [0..1] none

31 concrete classes miss an OwningRelatedElement rule this way (Membership, FeatureMembership, Import, FeatureValue, Differencing, Intersecting, Unioning, FeatureChaining, PortConjugation, …). CrossSubsetting and ReferenceSubsetting are the worst case: their source end has no check at all, because subsettingFeature is redefined by a derived property and dropped.

  • Pass the effective lower into QueryScalarRules; a Guid? with effective lower ≥ 1 gets NotEmpty()
  • Update DtoValidatorHelperTestFixture.cs:52-53, which currently asserts that Membership has no OwningRelatedElement rule
  • Regenerate again

Step 4 — Tests for the new helper logic

All in DtoValidatorHelperTestFixture.VerifyQueryRules unless stated. Ordered by value.

  • Count-bound branches (DtoValidatorHelper.cs:182-204). No property in the model has lower > 1 or a finite upper bound, so three branches are never executed by any test or any generated file. Assert the exact rule string for [0..*], [0..3], [1..*], [2..*], [1..3], [2..5]. This needs a synthetic IClass, or extract the pure (lower, upper) → rule function and test that.
  • Effective lower beyond the direct case (:87-142). Today only OwningMembership (positive) and Membership (negative) are asserted. Add FeatureMembership.OwnedRelatedElement (transitive, through a redefinition) and ConjugatedPortDefinition.OwnedRelationship as positives; PortDefinition and Feature without an OwnedRelationship rule, and Dependency without an OwnedRelatedElement rule, as negatives.
  • Property selection (:65-78, :214-231). Assert QueryRules(membership) with Is.EqualTo so the order is pinned; assert no rule for Feature.IsComposite, Feature.DeclaredName and LiteralInteger.Value.
  • A guard that the mapping stays as agreed. Over all 167 classes: no rule contains RuleForEach, Distinct() or HasValue, and no property has more than one rule.
  • RegisterDtoValidatorHelper (:36-54) has no direct test. New VerifyRegisterDtoValidatorHelper, modelled on OpenApiHandleBarHelpers/HttpMethodHelperTestFixture.cs: null IHandlebars, no argument, a non-IClass argument, and that the output contains a literal =>.
  • Validator-level — new DependencyValidatorTestFixture and ConjugatedPortDefinitionValidatorTestFixture in SysML2.NET.Validation.Tests/Core/DTO/AutoGenValidator/. Dependency.Client / Supplier are the only natively required collections and have no behavioural test.
  • A check that committed output matches the generator. Step 1 went unnoticed for 148 of the 167 validators because nothing compares them with anything. Cheapest form: in VerifyGenerateAsync, assert one {Class}Validator.cs per concrete class and none for an abstract class such as Element.

Step 5 — Standards and cleanup

  • DtoValidatorHelper.cs:85-233 — private methods are not in name order (DEVELOPMENT_STANDARDS.md §1.8). Order: QueryCollectionCountRule, QueryCollectionRules, QueryEffectiveLower, QueryPropertyRules, QueryRedefinitionChainIds, QueryScalarRules, QuerySupersetIds.
  • SysML2.NET/PIM/DTO/Project.cs:1 — a leading space was added before the file header. Unrelated to #406; revert the file.
  • DtoValidatorHelperTestFixture.cs lives in HandleBarHelpers/ but declares namespace …Tests.Generators.UmlHandleBarsGenerators (TESTING.md §1: the fixture mirrors the namespace of its production type).

Optional

  • DtoValidatorHelper.cs:103-142 — QuerySupersetIds and QueryRedefinitionChainIds are the same breadth-first walk over different edges; one QueryTransitiveIds(property, next) would do. new HashSet<string> { property.XmiId } (lines 105, 128) → collection expression [property.XmiId].
  • :191 — .Cascade(CascadeMode.Stop) is emitted when the chain holds a single validator.
  • :219-221 — ElementId.NotNull() accepts an empty or whitespace string, while elementId is String [1..1]. NotEmpty() fits there; leave Body and Value as they are, an empty string is a legitimate value for those.
  • Template line 25 — the inferred rules are necessary conditions on the storage (count ≥ 1); they cannot check the [1..1] upper bound or the element type on Guid data. One sentence in the validator summary avoids the impression that the derived multiplicity is validated.
  • UmlCoreDtoValidatorGenerator.cs:70-77 — untested: null name, an abstract or unknown class name (Single throws InvalidOperationException), and that the file lands in the output directory.
  • DtoValidator.cs:27-31 — the remarks say AddCustomValidation runs once, before the generated rules; no test pins the count or the order.

Not part of this PR

  • Annotation.annotatingElement [1..1] is derived, redefines source and subsets nothing, so no storage rule can be inferred for it. A hand-coded rule through AddCustomValidation would be the place; fine as a follow-up.

Grounding: metamodel facts from Hypha release 2026-08 (model https://www.omg.org/spec/SysML/20250201), tiers MODEL and DERIVED. No specification clause text was consulted. Build: 0 errors, 24 warnings (not triaged).

public void VerifyValidate()
{
var validator = new RequirementConstraintMembershipValidator();
var membership = new RequirementConstraintMembership { Id = Guid.NewGuid(), ElementId = "the element id", Kind = RequirementConstraintKind.Requirement };

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Step 2. This passes only because the checked-in validator is stale. After regeneration RequirementConstraintMembershipValidator requires OwnedRelatedElement, so this DTO is invalid and the ["Kind"] assertion below gets ["Kind", "OwnedRelatedElement"]. Seed OwnedRelatedElement = [Guid.NewGuid()] and add the empty collection as a negative scenario.


return property.QueryIsEnumerable()
? QueryCollectionRules(property, collectionLower, selector)
: QueryScalarRules(property, selector);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Step 3. The effective lower bound reaches QueryCollectionRules only; scalars use property.Lower. OwningMembership::ownedMemberElement [1..1] therefore makes OwnedRelatedElement required, while Membership::membershipOwningNamespace [1..1] (subsets owningRelatedElement [0..1]) yields no rule. 31 classes are affected; CrossSubsetting and ReferenceSubsetting end up with no source-end check at all. Pass the effective lower into QueryScalarRules as well.

Assert.That(QueryValidatedPropertyNames(owningMembership), Does.Not.Contain("MemberElement"));
Assert.That(QueryValidatedPropertyNames(owningMembership), Does.Not.Contain("OwnedMemberElement"));
Assert.That(QueryValidatedPropertyNames(membership), Does.Not.Contain("OwnedRelatedElement"));
Assert.That(QueryValidatedPropertyNames(membership), Does.Not.Contain("OwningRelatedElement"));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Step 3. This assertion pins the missing scalar rule; it flips to Does.Contain once the effective lower bound is applied to scalars.

/// <param name="lower">The lower bound of the collection.</param>
/// <param name="upper">The upper bound of the collection, <see cref="int.MaxValue"/> when unbounded.</param>
/// <returns>The rule chain appended to <c>RuleFor</c>, or <c>null</c> when the bounds demand nothing.</returns>
private static string QueryCollectionCountRule(int lower, int upper)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Step 4. Three branches of this method are never executed: the model has no non-derived collection with lower > 1 or a finite upper bound, so no generated file and no test reaches them. Assert the exact rule string for [0..*], [0..3], [1..*], [2..*], [1..3], [2..5].

/// <param name="property">The non-derived <see cref="IProperty"/>.</param>
/// <param name="requiredDerivedProperties">The lower bound and the superset ids of each required derived property of the class.</param>
/// <returns>The effective lower bound.</returns>
private static int QueryEffectiveLower(IProperty property, List<(int Lower, HashSet<string> SupersetIds)> requiredDerivedProperties)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Step 5. The private methods from here down are not in name order (DEVELOPMENT_STANDARDS.md §1.8).

// </copyright>
// ------------------------------------------------------------------------------------------------

namespace SysML2.NET.CodeGenerator.Tests.Generators.UmlHandleBarsGenerators

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Step 5. The file lives in HandleBarHelpers/ but declares the Generators.UmlHandleBarsGenerators namespace (TESTING.md §1).

Comment thread SysML2.NET/PIM/DTO/Project.cs Outdated
@@ -1,4 +1,4 @@
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Step 5. Stray leading space before the header, unrelated to #406. Please revert this file.

@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Core DTO validator

3 participants