From 5251384d4830647949b0c59ddfccbc0dc747fadf Mon Sep 17 00:00:00 2001 From: Zeynep Delal Mutlu Date: Mon, 9 Nov 2026 16:50:45 +0100 Subject: [PATCH 1/3] Fix float double equality checks in DTO comparers --- .../LiteralRationalComparer.cs | 2 +- .../HandleBarHelpers/PropertyHelper.cs | 343 ++++++++++-------- .../LiteralRationalComparerTestFixture.cs | 56 +++ .../LiteralRationalComparer.cs | 2 +- 4 files changed, 256 insertions(+), 147 deletions(-) create mode 100644 SysML2.NET.Extensions.Tests/Core/DTO/Comparers/LiteralRationalComparerTestFixture.cs diff --git a/SysML2.NET.CodeGenerator.Tests/Expected/UML/Core/AutoGenDtoComparers/LiteralRationalComparer.cs b/SysML2.NET.CodeGenerator.Tests/Expected/UML/Core/AutoGenDtoComparers/LiteralRationalComparer.cs index f029b12c5..94f9e4683 100644 --- a/SysML2.NET.CodeGenerator.Tests/Expected/UML/Core/AutoGenDtoComparers/LiteralRationalComparer.cs +++ b/SysML2.NET.CodeGenerator.Tests/Expected/UML/Core/AutoGenDtoComparers/LiteralRationalComparer.cs @@ -108,7 +108,7 @@ public bool Equals(ILiteralRational x, ILiteralRational y) if (x.OwningRelationship != y.OwningRelationship) return false; - if (FloatingPointComparer.NearlyEqual(x.Value, y.Value, FloatingPointComparer.DefaultDoubleEpsilon)) return false; + if (!FloatingPointComparer.NearlyEqual(x.Value, y.Value, FloatingPointComparer.DefaultDoubleEpsilon)) return false; return true; } diff --git a/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs b/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs index 3adf362cd..9ba8e2ddd 100644 --- a/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs +++ b/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs @@ -17,8 +17,6 @@ namespace SysML2.NET.CodeGenerator.HandleBarHelpers using HandlebarsDotNet; - using Microsoft.CodeAnalysis.CSharp.Syntax; - using SysML2.NET.CodeGenerator.Extensions; using uml4net.SimpleClassifiers; @@ -123,8 +121,8 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) throw new HandlebarsException("{{#Property.WriteForDTOClass}} helper must have exactly two arguments"); } - var property = (parameters[0] as IProperty)!; - var classContext = (parameters[1] as IClass)!; + var property = (IProperty)parameters[0]; + var classContext = (IClass)parameters[1]; var sb = new StringBuilder(); var propertyName = property.Name.CapitalizeFirstLetter(); @@ -132,7 +130,7 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) if (!isRedefinedPropertyInContext) { - sb.Append(property.Visibility.ToString().ToLower(CultureInfo.InvariantCulture)); + sb.Append(property.Visibility?.ToString().ToLower(CultureInfo.InvariantCulture)); sb.Append(' '); } @@ -356,7 +354,7 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) if (!isRedefinedPropertyInContext) { - sb.Append(property.Visibility.ToString().ToLower(CultureInfo.InvariantCulture)); + sb.Append(property.Visibility?.ToString().ToLower(CultureInfo.InvariantCulture)); sb.Append(' '); } @@ -792,101 +790,7 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) writer.WriteSafeString(sb); }); - handlebars.RegisterHelper("Property.WriteForDTOComparer", (writer, _, parameters) => - { - if (parameters.Length != 2) - { - throw new HandlebarsException("{{#Property.WriteForDTOComparer}} helper must have exactly two arguments"); - } - - var property = (parameters[0] as IProperty)!; - var classContext = (parameters[1] as IClass)!; - - var sb = new StringBuilder(); - var propertyName = property.Name.CapitalizeFirstLetter(); - var isRedefinedPropertyInContext = property.TryQueryRedefinedByProperty(classContext, out var _); - - if (isRedefinedPropertyInContext) - { - throw new InvalidOperationException("Property.WriteForDTOComparer is invalid for redefined properties"); - } - - if (property.IsDerived || property.IsDerivedUnion) - { - throw new InvalidOperationException("Property.WriteForDTOComparer is invalid for derived or derivedunion properties"); - } - - if (property.Type is IDataType) - { - if (property.QueryIsString()) - { - if (property.QueryIsEnumerable()) - { - if (property.IsOrdered) - { - sb.AppendLine($"if (!StringSequenceEquality.OrderedEqual(x.{propertyName}, y.{propertyName})) return false;"); - } - else - { - sb.AppendLine($"if (!StringSequenceEquality.UnorderedEqual(x.{propertyName}, y.{propertyName})) return false;"); - } - } - else - { - sb.AppendLine($"if (!OrdinalStringComparer.Equals(x.{propertyName}, y.{propertyName})) return false;"); - } - } - else if (property.QueryIsDouble()) - { - if (property.QueryIsNullable()) - { - sb.AppendLine($"if (x.{propertyName}.HasValue != y.{propertyName}.HasValue) return false;"); - - sb.AppendLine($"if (x.{propertyName}.HasValue && FloatingPointComparer.NearlyEqual(x.{propertyName}, y.{propertyName}, FloatingPointComparer.DefaultDoubleEpsilon)) return false;"); - } - else - { - sb.AppendLine($"if (FloatingPointComparer.NearlyEqual(x.{propertyName}, y.{propertyName}, FloatingPointComparer.DefaultDoubleEpsilon)) return false;"); - } - - } - else if (property.QueryIsFloat()) - { - if (property.QueryIsNullable()) - { - sb.AppendLine($"if (x.{propertyName}.HasValue != y.{propertyName}.HasValue) return false;"); - - sb.AppendLine($"if (x.{propertyName}.HasValue && FloatingPointComparer.NearlyEqual(x.{propertyName}, y.{propertyName}, FloatingPointComparer.DefaultFloatEpsilon)) return false;"); - } - - sb.AppendLine($"if (FloatingPointComparer.NearlyEqual(x.{propertyName}, y.{propertyName}, FloatingPointComparer.DefaultDoubleEpsilon)) return false;"); - } - else - { - sb.AppendLine($"if (x.{propertyName} != y.{propertyName}) return false;"); - } - } - else - { - if (property.QueryIsEnumerable()) - { - if (property.IsOrdered) - { - sb.AppendLine($"if (!GuidSequenceEquality.OrderedEqual(x.{propertyName}, y.{propertyName})) return false;"); - } - else - { - sb.AppendLine($"if (!GuidSequenceEquality.UnorderedEqual(x.{propertyName}, y.{propertyName})) return false;"); - } - } - else - { - sb.AppendLine($"if (x.{propertyName} != y.{propertyName}) return false;"); - } - } - - writer.WriteSafeString(sb + Environment.NewLine); - }); + handlebars.RegisterHelper("Property.WriteForDTOComparer", (writer, _, parameters) => WriteForDtoComparer(writer, parameters)); handlebars.RegisterHelper("Property.IsPropertyRedefinedInClass", (context, arguments) => { @@ -1153,16 +1057,6 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) }); } - /// - /// Builds a complete XML <remarks> block listing every constraint body carried by - /// the supplied sequence, labelled by language. Returns the empty - /// string when no constraint carries an body. - /// - /// The constraints to render. - /// - /// A multi-line string starting with /// <remarks> and ending with /// </remarks>, - /// each line prefixed for direct emission inside the Extend template; empty when nothing to emit. - /// /// /// Returns when at least one constraint in /// carries an with at least one non-blank body line — i.e. when @@ -1185,6 +1079,16 @@ private static bool HasRenderableConstraint(IEnumerable constraints return false; } + /// + /// Builds a complete XML <remarks> block listing every constraint body carried by + /// the supplied sequence, labelled by language. Returns the empty + /// string when no constraint carries an body. + /// + /// The constraints to render. + /// + /// A multi-line string starting with /// <remarks> and ending with /// </remarks>, + /// each line prefixed for direct emission inside the Extend template; empty when nothing to emit. + /// private static string BuildOwnedRulesRemarksBlock(IEnumerable constraints) { var entries = new List<(string Language, string Body)>(); @@ -1193,13 +1097,12 @@ private static string BuildOwnedRulesRemarksBlock(IEnumerable const { var opaqueExpression = constraint.Specification?.OfType().FirstOrDefault(); - if (opaqueExpression == null || opaqueExpression.Body == null) + if (opaqueExpression?.Body == null) { continue; } var bodies = opaqueExpression.Body; - var languages = opaqueExpression.Language; for (var index = 0; index < bodies.Count; index++) { @@ -1208,11 +1111,7 @@ private static string BuildOwnedRulesRemarksBlock(IEnumerable const continue; } - var language = languages != null && index < languages.Count && !string.IsNullOrWhiteSpace(languages[index]) - ? languages[index].Trim() - : "Constraint"; - - entries.Add((language, bodies[index].Trim())); + entries.Add((GetConstraintLanguage(opaqueExpression.Language, index), bodies[index].Trim())); } } @@ -1244,6 +1143,22 @@ private static string BuildOwnedRulesRemarksBlock(IEnumerable const return sb.ToString(); } + /// + /// Gets the language label of the constraint body at , or Constraint when none is given + /// + /// The languages of an , positionally matching its bodies + /// The 0-based index of the body + /// The trimmed language label + private static string GetConstraintLanguage(IList languages, int index) + { + if (languages == null || index >= languages.Count || string.IsNullOrWhiteSpace(languages[index])) + { + return "Constraint"; + } + + return languages[index].Trim(); + } + /// /// Replaces XML-significant characters with their entity equivalents so the result is safe to /// embed inside an XML doc comment. @@ -1258,6 +1173,120 @@ private static string EscapeXml(string value) .Replace(">", ">"); } + /// + /// Writes the equality check of a DTO comparer for the and passed as arguments + /// + /// The to write to + /// The helper arguments: the and its context + private static void WriteForDtoComparer(EncodedTextWriter writer, Arguments parameters) + { + if (parameters.Length != 2) + { + throw new HandlebarsException("{{#Property.WriteForDTOComparer}} helper must have exactly two arguments"); + } + + var property = (IProperty)parameters[0]; + var classContext = (IClass)parameters[1]; + + if (property.TryQueryRedefinedByProperty(classContext, out _)) + { + throw new InvalidOperationException("Property.WriteForDTOComparer is invalid for redefined properties"); + } + + if (property.IsDerived || property.IsDerivedUnion) + { + throw new InvalidOperationException("Property.WriteForDTOComparer is invalid for derived or derivedunion properties"); + } + + var sb = new StringBuilder(); + var propertyName = property.Name.CapitalizeFirstLetter(); + + if (property.Type is IDataType) + { + AppendDataTypeComparison(sb, property, propertyName); + } + else + { + AppendSequenceOrScalarComparison(sb, property, propertyName, "GuidSequenceEquality"); + } + + writer.WriteSafeString(sb + Environment.NewLine); + } + + /// + /// Appends the equality check for an typed by an + /// + /// The to append to + /// The to compare + /// The C# name of the + private static void AppendDataTypeComparison(StringBuilder sb, IProperty property, string propertyName) + { + if (property.QueryIsString()) + { + if (property.QueryIsEnumerable()) + { + AppendSequenceOrScalarComparison(sb, property, propertyName, "StringSequenceEquality"); + } + else + { + sb.AppendLine($"if (!OrdinalStringComparer.Equals(x.{propertyName}, y.{propertyName})) return false;"); + } + } + else if (property.QueryIsDouble()) + { + AppendFloatingPointComparison(sb, property, propertyName, "DefaultDoubleEpsilon"); + } + else if (property.QueryIsFloat()) + { + AppendFloatingPointComparison(sb, property, propertyName, "DefaultFloatEpsilon"); + } + else + { + sb.AppendLine($"if (x.{propertyName} != y.{propertyName}) return false;"); + } + } + + /// + /// Appends the equality check for an compared as an ordered or unordered sequence, or as a single value + /// + /// The to append to + /// The to compare + /// The C# name of the + /// The name of the sequence-equality class used when the property is enumerable + private static void AppendSequenceOrScalarComparison(StringBuilder sb, IProperty property, string propertyName, string sequenceEquality) + { + if (!property.QueryIsEnumerable()) + { + sb.AppendLine($"if (x.{propertyName} != y.{propertyName}) return false;"); + return; + } + + var method = property.IsOrdered ? "OrderedEqual" : "UnorderedEqual"; + + sb.AppendLine($"if (!{sequenceEquality}.{method}(x.{propertyName}, y.{propertyName})) return false;"); + } + + /// + /// Appends the tolerance-based equality check for a floating-point + /// + /// The to append to + /// The floating-point to compare + /// The C# name of the + /// The name of the FloatingPointComparer epsilon constant to compare with + private static void AppendFloatingPointComparison(StringBuilder sb, IProperty property, string propertyName, string epsilon) + { + if (property.QueryIsNullable()) + { + sb.AppendLine($"if (x.{propertyName}.HasValue != y.{propertyName}.HasValue) return false;"); + + sb.AppendLine($"if (x.{propertyName}.HasValue && !FloatingPointComparer.NearlyEqual(x.{propertyName}.Value, y.{propertyName}.Value, FloatingPointComparer.{epsilon})) return false;"); + } + else + { + sb.AppendLine($"if (!FloatingPointComparer.NearlyEqual(x.{propertyName}, y.{propertyName}, FloatingPointComparer.{epsilon})) return false;"); + } + } + /// /// Gets the getter implementation for an that has been redefined, for DTO generation /// @@ -1291,8 +1320,10 @@ private static string GetRedefinedPropertyGetterImplementationForDto(IProperty r : $"[{redefinitionPropertyName}];"; } + var defaultValue = redefinedProperty.QueryIsReferenceType() ? "Guid.Empty" : "default"; + return uml4net.Extensions.PropertyExtensions.QueryIsNullableAndNotString(redefinition) - ? $"{redefinitionPropertyName}.HasValue ? {redefinitionPropertyName}.Value : {(redefinedProperty.QueryIsReferenceType() ? "Guid.Empty" : "default")};" + ? $"{redefinitionPropertyName}.HasValue ? {redefinitionPropertyName}.Value : {defaultValue};" : $"{redefinitionPropertyName};"; } @@ -1416,40 +1447,62 @@ private static string GetRedefinedPropertySetterImplementationForPoco(IProperty return redefinedProperty.Type == redefinition.Type ? $"{redefinitionPropertyName} = value;" : $"{redefinitionPropertyName} = [..value.OfType<{redefinitionPropertyTypeName}>()];"; } + var isSameType = redefinedProperty.Type == redefinition.Type; + + return redefinedProperty.QueryIsEnumerable() + ? GetSetterFromEnumerableForPoco(redefinitionPropertyName, redefinitionPropertyTypeName, isSameType) + : GetSetterFromSingleValueForPoco(redefinitionPropertyName, redefinitionPropertyTypeName, isSameType); + } + + /// + /// Gets the POCO setter body that assigns the first value of an enumerable redefined property to a single-valued redefinition + /// + /// The accessor of the redefining property + /// The C# type name of the redefining property + /// Whether the redefined and redefining properties have the same type + /// The setter implementation + private static string GetSetterFromEnumerableForPoco(string redefinitionPropertyName, string redefinitionPropertyTypeName, bool isSameType) + { var stringBuilder = new StringBuilder(); - if (redefinedProperty.QueryIsEnumerable()) + if (isSameType) { - if (redefinedProperty.Type == redefinition.Type) - { - stringBuilder.AppendLine("if(value.Count != 0)"); - stringBuilder.AppendLine("{"); - stringBuilder.AppendLine($"\t{redefinitionPropertyName} = value[0];"); - } - else - { - stringBuilder.AppendLine($"if(value.OfType<{redefinitionPropertyTypeName}>().FirstOrDefault() is {{ }} firstValue)"); - stringBuilder.AppendLine("{"); - stringBuilder.AppendLine($"\t{redefinitionPropertyName} = firstValue;"); - } - - stringBuilder.Append('}'); + stringBuilder.AppendLine("if(value.Count != 0)"); + stringBuilder.AppendLine("{"); + stringBuilder.AppendLine($"\t{redefinitionPropertyName} = value[0];"); } else { - if (redefinedProperty.Type == redefinition.Type) - { - stringBuilder.Append($"{redefinitionPropertyName} = value;"); - } - else - { - stringBuilder.AppendLine($"if(value is {redefinitionPropertyTypeName} castedValue)"); - stringBuilder.AppendLine("{"); - stringBuilder.AppendLine($"\t{redefinitionPropertyName} = castedValue;"); - stringBuilder.Append('}'); - } + stringBuilder.AppendLine($"if(value.OfType<{redefinitionPropertyTypeName}>().FirstOrDefault() is {{ }} firstValue)"); + stringBuilder.AppendLine("{"); + stringBuilder.AppendLine($"\t{redefinitionPropertyName} = firstValue;"); + } + + stringBuilder.Append('}'); + + return stringBuilder.ToString(); + } + + /// + /// Gets the POCO setter body that assigns a single-valued redefined property to its redefinition + /// + /// The accessor of the redefining property + /// The C# type name of the redefining property + /// Whether the redefined and redefining properties have the same type + /// The setter implementation + private static string GetSetterFromSingleValueForPoco(string redefinitionPropertyName, string redefinitionPropertyTypeName, bool isSameType) + { + if (isSameType) + { + return $"{redefinitionPropertyName} = value;"; } + var stringBuilder = new StringBuilder(); + stringBuilder.AppendLine($"if(value is {redefinitionPropertyTypeName} castedValue)"); + stringBuilder.AppendLine("{"); + stringBuilder.AppendLine($"\t{redefinitionPropertyName} = castedValue;"); + stringBuilder.Append('}'); + return stringBuilder.ToString(); } } diff --git a/SysML2.NET.Extensions.Tests/Core/DTO/Comparers/LiteralRationalComparerTestFixture.cs b/SysML2.NET.Extensions.Tests/Core/DTO/Comparers/LiteralRationalComparerTestFixture.cs new file mode 100644 index 000000000..bbd4e174d --- /dev/null +++ b/SysML2.NET.Extensions.Tests/Core/DTO/Comparers/LiteralRationalComparerTestFixture.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.Extensions.Tests.Core.DTO.Comparers +{ + using System; + + using NUnit.Framework; + + using SysML2.NET.Core.DTO.Kernel.Expressions; + using SysML2.NET.Extensions.Core.DTO.Comparers; + + [TestFixture] + public class LiteralRationalComparerTestFixture + { + [Test] + public void VerifyEquals() + { + var comparer = new LiteralRationalComparer(); + var id = Guid.NewGuid(); + var literal = new LiteralRational { Id = id, Value = 2.5 }; + var copy = new LiteralRational { Id = id, Value = 2.5 }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(comparer.Equals(literal, null), Is.False); + Assert.That(comparer.Equals(literal, literal), Is.True); + Assert.That(comparer.Equals(literal, copy), Is.True); + Assert.That(ComparerProvider.Resolve(literal).Equals(literal, copy), Is.True); + } + + copy.Value = 3.0; + + using (Assert.EnterMultipleScope()) + { + Assert.That(comparer.Equals(literal, copy), Is.False); + Assert.That(ComparerProvider.Resolve(literal).Equals(literal, copy), Is.False); + } + + literal.Value = 0.1 + 0.2; + copy.Value = 0.3; + + Assert.That(comparer.Equals(literal, copy), Is.True); + + copy.Id = Guid.NewGuid(); + + Assert.That(comparer.Equals(literal, copy), Is.False); + } + } +} diff --git a/SysML2.NET.Extensions/Core/AutoGenDtoComparers/LiteralRationalComparer.cs b/SysML2.NET.Extensions/Core/AutoGenDtoComparers/LiteralRationalComparer.cs index f029b12c5..94f9e4683 100644 --- a/SysML2.NET.Extensions/Core/AutoGenDtoComparers/LiteralRationalComparer.cs +++ b/SysML2.NET.Extensions/Core/AutoGenDtoComparers/LiteralRationalComparer.cs @@ -108,7 +108,7 @@ public bool Equals(ILiteralRational x, ILiteralRational y) if (x.OwningRelationship != y.OwningRelationship) return false; - if (FloatingPointComparer.NearlyEqual(x.Value, y.Value, FloatingPointComparer.DefaultDoubleEpsilon)) return false; + if (!FloatingPointComparer.NearlyEqual(x.Value, y.Value, FloatingPointComparer.DefaultDoubleEpsilon)) return false; return true; } From fc9b933c4d78af5f4fc9ef7ee740f3f6fd25cd8b Mon Sep 17 00:00:00 2001 From: Zeynep Delal Mutlu Date: Tue, 10 Nov 2026 09:51:02 +0100 Subject: [PATCH 2/3] sonarqube check --- .../HandleBarHelpers/PropertyHelper.cs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs b/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs index 9ba8e2ddd..7aecaebd0 100644 --- a/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs +++ b/SysML2.NET.CodeGenerator/HandleBarHelpers/PropertyHelper.cs @@ -538,7 +538,7 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) return; } - // properties that have been redefined in the context of the + // properties that have been redefined in the context of the // generated class are ignored if (property.TryQueryRedefinedByProperty(generatedClass, out _)) { @@ -649,7 +649,7 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) return; } - // properties that have been redefined in the context of the + // properties that have been redefined in the context of the // generated class are ignored if (property.TryQueryRedefinedByProperty(generatedClass, out _)) { @@ -936,13 +936,13 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) var oppositePropertyName = property.Opposite.Name.CapitalizeFirstLetter(); var childVariableName = property.Type.Name.LowerCaseFirstLetter(); var parentVariableName = property.Opposite.Type.Name.LowerCaseFirstLetter(); - + stringBuilder.AppendLine($"(({interfaceName})this).{propertyName} = new ContainerList(this, "); stringBuilder.AppendLine($"({childVariableName}, {parentVariableName}) => ((IContained{property.Type.Name}){childVariableName}).{oppositePropertyName} = {parentVariableName},"); stringBuilder.AppendLine($"{childVariableName} => {childVariableName}.{oppositePropertyName});"); writer.WriteSafeString(stringBuilder + Environment.NewLine); }); - + handlebars.RegisterHelper("Property.QueryHasDefaultValueWithDifferentValueThanDefault", (_, arguments) => { if (arguments.Length != 1) @@ -955,8 +955,8 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) throw new ArgumentException("The #Property.QueryHasDefaultValueWithDifferentValueThanDefault argument supposed to be an IProperty"); } - return property.QueryIsEnum() - ? property.QueryIsEnumPropertyWithDefaultValue() + return property.QueryIsEnum() + ? property.QueryIsEnumPropertyWithDefaultValue() : (property.QueryHasDefaultValue() && property.QueryIsDefaultValueDifferentThanDefault()); }); @@ -985,7 +985,7 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) writer.WriteSafeString($"{property.QueryDefaultValueAsString()}"); } }); - + handlebars.RegisterHelper("Property.QueryIsEnumerableAndReferenceProperty", (_, arguments) => { if (arguments.Length != 1) @@ -997,7 +997,7 @@ public static void RegisterPropertyHelper(this IHandlebars handlebars) { throw new ArgumentException("The #Property.QueryIsEnumerableAndReferenceProperty argument supposed to be an IProperty"); } - + return property.QueryIsEnumerable() && property.QueryIsReferenceType(); }); @@ -1149,7 +1149,7 @@ private static string BuildOwnedRulesRemarksBlock(IEnumerable const /// The languages of an , positionally matching its bodies /// The 0-based index of the body /// The trimmed language label - private static string GetConstraintLanguage(IList languages, int index) + private static string GetConstraintLanguage(List languages, int index) { if (languages == null || index >= languages.Count || string.IsNullOrWhiteSpace(languages[index])) { @@ -1441,7 +1441,7 @@ private static string GetRedefinedPropertySetterImplementationForPoco(IProperty } var redefinitionPropertyTypeName = redefinition.QueryIsReferenceType() ? $"I{redefinition.Type.Name}" : redefinition.QueryCSharpTypeName(); - + if (redefinedProperty.QueryIsEnumerable() && redefinition.QueryIsEnumerable()) { return redefinedProperty.Type == redefinition.Type ? $"{redefinitionPropertyName} = value;" : $"{redefinitionPropertyName} = [..value.OfType<{redefinitionPropertyTypeName}>()];"; From 185ecf832b5b6f11ee129329a21d4b37df40afb8 Mon Sep 17 00:00:00 2001 From: Zeynep Delal Mutlu Date: Tue, 10 Nov 2026 13:39:39 +0100 Subject: [PATCH 3/3] sonarqube code coverage check --- .../PropertyHelperTestFixture.cs | 44 +++++++++++++------ 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/SysML2.NET.CodeGenerator.Tests/HandleBarHelpers/PropertyHelperTestFixture.cs b/SysML2.NET.CodeGenerator.Tests/HandleBarHelpers/PropertyHelperTestFixture.cs index ecdc7a98b..2ca5c4073 100644 --- a/SysML2.NET.CodeGenerator.Tests/HandleBarHelpers/PropertyHelperTestFixture.cs +++ b/SysML2.NET.CodeGenerator.Tests/HandleBarHelpers/PropertyHelperTestFixture.cs @@ -9,6 +9,7 @@ namespace SysML2.NET.CodeGenerator.Tests.Generators.UmlHandleBarsGenerators { + using System; using System.Collections.Generic; using System.Linq; @@ -22,7 +23,9 @@ namespace SysML2.NET.CodeGenerator.Tests.Generators.UmlHandleBarsGenerators using uml4net.Classification; using uml4net.Extensions; + using uml4net.SimpleClassifiers; using uml4net.StructuredClassifiers; + using uml4net.Values; [TestFixture] public class PropertyHelperTestFixture @@ -240,24 +243,39 @@ public void Verify_that_WriteForDTOMessagePackFormatterDeSerialize_generates_cod // ------------------------------------------------------------------- [Test] - public void Verify_that_WriteForDTOComparer_generates_comparison_code() + public void VerifyWriteForDTOComparer() { - var nonAbstractClass = this.allClasses.First(x => !x.IsAbstract); + const string helperExpression = "{{Property.WriteForDTOComparer this ../classObj}}"; + var emptyClass = new Class { Name = "Empty" }; - var nonDerivedNonRedefinedProperty = nonAbstractClass.QueryAllProperties() - .FirstOrDefault(p => !p.IsDerived && !p.IsDerivedUnion - && !p.TryQueryRedefinedByProperty(nonAbstractClass, out _)); + Assert.That(() => this.RenderWithPropertyContext("{{Property.WriteForDTOComparer this}}", this.testProperty), + Throws.InstanceOf()); - if (nonDerivedNonRedefinedProperty == null) - { - Assert.Ignore("No suitable property found"); - } + var redefiningClass = this.allClasses.First(c => c.QueryAllProperties().Any(p => p.TryQueryRedefinedByProperty(c, out _))); + var redefinedProperty = redefiningClass.QueryAllProperties().First(p => p.TryQueryRedefinedByProperty(redefiningClass, out _)); - var result = this.RenderWithPropertyAndClassContext( - "{{Property.WriteForDTOComparer this ../classObj}}", nonDerivedNonRedefinedProperty, nonAbstractClass); + Assert.That(() => this.RenderWithPropertyAndClassContext(helperExpression, redefinedProperty, redefiningClass), + Throws.TypeOf()); - Assert.That(result.Trim(), Is.Not.Empty); - Assert.That(result, Does.Contain("return false")); + Assert.That(() => this.RenderWithPropertyAndClassContext(helperExpression, this.derivedProperty, emptyClass), + Throws.TypeOf()); + + var doubleProperty = new Property { Name = "value", Type = new PrimitiveType { Name = "Real" } }; + + Assert.That(this.RenderWithPropertyAndClassContext(helperExpression, doubleProperty, emptyClass), + Does.Contain("if (!FloatingPointComparer.NearlyEqual(x.Value, y.Value, FloatingPointComparer.DefaultDoubleEpsilon)) return false;")); + + var nullableFloatProperty = new Property { Name = "ratio", Type = new PrimitiveType { Name = "float" } }; + nullableFloatProperty.LowerValue.Add(new LiteralInteger { Value = 0 }); + + var result = this.RenderWithPropertyAndClassContext(helperExpression, nullableFloatProperty, emptyClass); + + using (Assert.EnterMultipleScope()) + { + Assert.That(result, Does.Contain("if (x.Ratio.HasValue != y.Ratio.HasValue) return false;")); + Assert.That(result, Does.Contain("if (x.Ratio.HasValue && !FloatingPointComparer.NearlyEqual(x.Ratio.Value, y.Ratio.Value, FloatingPointComparer.DefaultFloatEpsilon)) return false;")); + Assert.That(result, Does.Not.Contain("DefaultDoubleEpsilon")); + } } // -------------------------------------------------------------------