Skip to content

Commit

Permalink
Replace constraints on EqualNumericConstraint with Guard
Browse files Browse the repository at this point in the history
Also only allow conversions on supported NumericTypes

For everything else drop back to pre 4.3 behaviour
  • Loading branch information
manfred-brands committed Dec 19, 2024
1 parent a12d6ab commit bd45e7c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt

using System;

namespace NUnit.Framework.Constraints
{
/// <summary>
Expand All @@ -10,10 +8,8 @@ namespace NUnit.Framework.Constraints
/// considered equal if both are null, or if both have the same
/// value. NUnit has special semantics for some object types.
/// </summary>
#pragma warning disable CS3024 // Constraint type is not CLS-compliant
public class EqualNumericConstraint<T> : EqualNumericWithoutUsingConstraint<T>, IEqualWithUsingConstraint<T>
where T : unmanaged, IConvertible, IEquatable<T>
#pragma warning restore CS3024 // Constraint type is not CLS-compliant
where T : struct
{
#region Constructor

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ namespace NUnit.Framework.Constraints
/// considered equal if both are null, or if both have the same
/// value. NUnit has special semantics for some object types.
/// </summary>
#pragma warning disable CS3024 // Constraint type is not CLS-compliant
public class EqualNumericWithoutUsingConstraint<T> : Constraint
where T : unmanaged, IConvertible, IEquatable<T>
#pragma warning restore CS3024 // Constraint type is not CLS-compliant
where T : struct
{
#region Static and Instance Fields

Expand All @@ -36,6 +34,8 @@ public class EqualNumericWithoutUsingConstraint<T> : Constraint
internal EqualNumericWithoutUsingConstraint(T expected)
: base(expected)
{
Guard.ArgumentValid(Numerics.IsNumericType(typeof(T)), "EqualNumericWithoutUsingConstraint<T> may only be used with numeric types.", nameof(T));

_expected = expected;
}

Expand Down Expand Up @@ -155,13 +155,15 @@ public override ConstraintResult ApplyTo<TActual>(TActual actual)

hasSucceeded = equatable.Equals(_expected);
}
else if (actual is not string and IConvertible)
else if (Numerics.IsNumericType(typeof(TActual)))
{
hasSucceeded = Numerics.AreEqual(actual, _expected, ref _tolerance);
}
else
{
hasSucceeded = false;
// We fall back to pre 4.3 EqualConstraint behavior
// Maybe TActual is not a numeric type, but supports indirect comparions with T
return new EqualConstraint(_expected).ApplyTo(actual);
}

return ConstraintResult(actual, hasSucceeded);
Expand Down

0 comments on commit bd45e7c

Please sign in to comment.