Skip to content

Make new PropertiesComparer optional #4572

Closed

Description

@Mazzelfassel

I updated NUnit to bersion 4.0 and run my tests like usual. After doing the required migrations some tests that I didn't even touched start to fail. After some investigation I discovered that this is related to the new PopertiesComparer added by #4394.

The affected tests compare classes via Is.EqualTo() and before they were compared by reference. But due to some objects having the exact same properties the new comparer now consideres them equal, failing my tests.

The new comparer is used by default and it looks like it cannot be disabled in the current version.

Example of a Test that worked before but fails in version 4:

private class TestClass 
{
    public int Prop { get; set; } = 0;
}

[Test]
public void CompareObjects()
{
    TestClass a = new() { Prop = 2 };
    TestClass b = new() { Prop = 2 };

    Assert.That(b, Is.Not.EqualTo(a));
}

Activity

  1. OsirisTerje commented on Nov 29, 2023

    @OsirisTerje
    Member

    @manfred-brands Comments?

  2. manfred-brands commented on Nov 29, 2023

    @manfred-brands
    Member

    In the example, I would say a and b are considered equal.

    If you want reference comparison, you should use Is.SameAs instead.

    Unfortunately the definition of Equals in .NET is not defined as being value or reference. One has to use ReferenceEquals to quantify.

    If your classes were either struct or implemented IEquality the behaviour of Is.EqualTo changes

    I see the behaviour is breaking, but is that because the wrong test was used?

  3. Mazzelfassel commented on Nov 29, 2023

    @Mazzelfassel
    Author

    By default if you write a == b it would return false for reference types such as class or interface. I'm not completly sure how it is for a.Equals(b) but I think it behaves the same.

    I have to admit I forgot about Is.SameAs because Is.EqualTo usually also did the job, but that should solve most of my issues for now.
    But there may be some edge cases. I also had some issues with CollectionAssert related functions that could possibly originate from the new comparer. However I did not found the time to investigate these tests yet and will look into this tomorrow.

  4. OsirisTerje commented on Nov 29, 2023

    @OsirisTerje
    Member

    @manfred-brands We should perhaps clarify in the docs for EqualTo that it is intended to do Value equality, and if you need reference equality they should turn to SameAs. It is not explicitly stated in the docs there, and that could be helpful to do.

  5. Mazzelfassel commented on Nov 30, 2023

    @Mazzelfassel
    Author

    I did some further testing and made some new discoveries.
    This case where the test fails in accordance to the new PropertyComparer.

    [Test]
    public void CompareObjects()
    {
        TestClass[] a = new[]
        {
            new TestClass() { Prop = 1 },
            new TestClass() { Prop = 2 },
            new TestClass() { Prop = 3 }
        };
        TestClass b = new() { Prop = 2 };
    
        Assert.That(a, Does.Not.Contain(b));
    }
    

    Is there an equivalent to Is.SameAs for collection asserts?

    Additionally I found a bug that occours when you have an Indexer in your tested class, causing the comparer to throw an exception.
    Example:

    public class ClassB
    {
        public int Prop { get; set; }
        public object? this[int i] => 1;
    }
    
    [Test]
    public void CompareObjects()
    {
        ClassB a = new() { Prop = 3 };
        ClassB b = new() { Prop = 3 };
        Assert.That(a, Is.EqualTo(b));
    }
    

    Which throws the following exception:

    System.Reflection.TargetParameterCountException
      HResult=0x8002000E
      Message=Parameter count mismatch.
      Source=System.Private.CoreLib
      StackTrace:
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
       at NUnit.Framework.Constraints.Comparers.PropertiesComparer.Equal(Object x, Object y, Tolerance& tolerance, ComparisonState state, NUnitEqualityComparer equalityComparer)
       at NUnit.Framework.Constraints.NUnitEqualityComparer.AreEqual(Object x, Object y, Tolerance& tolerance, ComparisonState state)
       at NUnit.Framework.Constraints.NUnitEqualityComparer.AreEqual(Object x, Object y, Tolerance& tolerance)
       at NUnit.Framework.Constraints.EqualConstraint.ApplyTo[TActual](TActual actual)
       at NUnit.Framework.Assert.That[TActual](TActual actual, IResolveConstraint expression, NUnitString message, String actualExpression, String constraintExpression)
       ...
    
  6. manfred-brands commented on Nov 30, 2023

    @manfred-brands
    Member

    Is there an equivalent to Is.SameAs for collection asserts?

    This seems to work for me:

    [Test]
    public void CollectionReferenceComparison()
    {
        TestClass b1 = new() { Prop = 2 };
        TestClass b2 = new() { Prop = 2 };
    
        TestClass[] a = new[]
        {
            new() { Prop = 1 },
            b1,
            new() { Prop = 3 }
        };
    
        Assert.Multiple(() =>
        {
            Assert.That(a, Has.One.SameAs(b1));
            Assert.That(a, Has.None.SameAs(b2));
        });
    }
  7. Mazzelfassel commented on Nov 30, 2023

    @Mazzelfassel
    Author

    That solution should work. I checked the documentation and it states that Does.Contain is a shortcut for what you just described. I probalby was unaware of that fact similar to the Is.SameAs situation.

    That just leaves the issue with the exception when testing a class with an indexer.

  8. manfred-brands commented on Nov 30, 2023

    @manfred-brands
    Member

    Does.Contains is equivalent to Has.Some.EqualTo

    That just leaves the issue with the exception when testing a class with an indexer.

    Yes, I will see if I can get a fix for that soon.

  9. batzen commented on Dec 8, 2023

    @batzen
    Contributor

    I have to complain a bit more about the new PropertiesComparer.

    In my case it's also totally undesired that there is no way of turning it off.

    Exceptions are not only thrown for indexers but also for properties without getters.

    In addition to that:
    What happens if property getters aren't idempotent?
    What happens if property getters throw exceptions?

  10. batzen commented on Dec 8, 2023

    @batzen
    Contributor

    For anyone interested in a quick fix:

    [SetUpFixture]
    public class TestAssemblySetup
    {
        [OneTimeSetUp]
        public void RunBeforeAnyTests()
        {
            // Workaround for https://github.com/nunit/nunit/issues/4572
            {
                var comparersFieldInfo = typeof(NUnitEqualityComparer).GetField("Comparers", BindingFlags.NonPublic | BindingFlags.Static);
    
                if (comparersFieldInfo?.GetValue(null) is Array comparers)
                {
                    object equalsComparerDelegate = null;
                    for (var i = 0; i < comparers.Length; i++)
                    {
                        var comparer = comparers.GetValue(i);
    
                        switch (comparer)
                        {
                            case Delegate { Method: { DeclaringType: { Name: "EqualsComparer" } } }:
                                equalsComparerDelegate = comparer;
                                break;
                            case Delegate { Method: { DeclaringType: { Name: "PropertiesComparer" } } } when equalsComparerDelegate is not null:
                                comparers.SetValue(equalsComparerDelegate, i);
                                break;
                        }
                    }
                }
            }
        }
    }
    
  11. stevenaw commented on Dec 8, 2023

    @stevenaw
    Member

    Thanks for sharing your work around @batzen !

    @OsirisTerje @manfred-brands What do you think about us adding an opt out mechanism here, and if so what could one look like?

    Alternately, would it make sense to only use the property comparer internally for value types and let reference types use the default "Equals" function? Is there a use case where we'd want to enforce requiring only value equality over reference types?

  12. manfred-brands commented on Dec 8, 2023

    @manfred-brands
    Member

    I'm ok with an opt-in or opt-out, but don't want it to restrict to value types.

    I had PropertiesComparer intended for DTO classes to test equality without the need to implement IEquatable<T> or a special comparer or write an Assert method asserting every property one selves.

    However I get the impression that @batzen wants reference comparison for which we have the different constraints. As @OsirisTerje said we need to better document that EqualTo is for value comparison and SameAs for reference comparison.

    But historically most users will have used EqualTo for everything.

  13. batzen commented on Dec 8, 2023

    @batzen
    Contributor

    @manfred-brands I don't always want reference comparison when using EqualTo.
    What i absolutely don't want is every property getter being called automatically, with no way of preventing that behavior.

    The PropertiesComparer only kicks in when the types are exactly equal and everything else failed to check for equality.
    Why not remove it from EqualTo and add a new Has.PropertyValuesEqualTo?
    That way the assert could also assert when different types are passed.

    I had PropertiesComparer intended for DTO classes to test equality without the need to implement IEquatable or a special comparer or write an Assert method asserting every property one selves.

    That's totally fine as a convenience method, but it should be explicit instead of implicit.

  14. OsirisTerje commented on Dec 8, 2023

    @OsirisTerje
    Member

    @manfred-brands @stevenaw @batzen

    EqualTo is meant to be value equality. The problem with value equality is always how deep you should go. So including the properties makes sense to me.

    However, if I use fields instead it actually doesn't say that the objects are value equal - but they are, so we have a glitch there.

    I looked up how XUnit resolves this, and they have an new assertion Equivalent , which does value equality.
    From their docs:

    Assert.Equivalent differs from Assert.Equal is the “level of equality” that is expected from the two values. For example, Assert.Equal requires that both values are the same (or a compatible) type, whereas Assert.Equivalent will simply compare all the public fields and properties of the two values to ensure they contain the same values, even if they aren’t the same type. Equivalence comes with a “strictness” switch which allows the developer to say whether the expected value contains the complete set of values that the actual value should contain (‘strict’) vs. only a subset of values (‘not strict’). When strict comparisons are done, an “extra” properties on the actual object vs. the expected object cause failure, whereas they are ignored for non-strict comparisons.

    We might need to rethink equality. I have always thought of EqualTo as full value equality, but I can understand that it actually is not. It is something in between. It compares by value until it is nearly finished, then sort of continues by comparing by reference (It doesnt, but the effect is the same). So I like the PropertyComparer, but it is a breaking change (which is fine as it is 4.0), but it should then also have done fields the same way.

    So, perhaps we should do something like what XUnit has done with the Equivalent ?
    Or should we have a modifier to control this for the EqualTo ?

  15. 6 remaining items

  16. stevenaw commented on Dec 8, 2023

    @stevenaw
    Member

    Changing this from question to enhancement as it sounds like something the team wants to explore

  17. manfred-brands commented on Dec 9, 2023

    @manfred-brands
    Member

    However, if I use fields instead it actually doesn't say that the objects are value equal - but they are, so we have a glitch there.

    Yes. Initially, before settling on properties, I was thinking of using fields iso properties, as even auto-properties are backed by hidden fields. I guess I made the wrong decision there. But that was based on my companies use case.

    Value comparing classes only makes sense for data classes and in theory those should have public properties, not fields. When following CA1051 field are internal implementation details. However CA2211 only raises for mutable fields. So immutable data classes using read-only fields should be fine.

    EqualTo does other things which might be not expected for user that expect standard .net Equals behaviour.
    We iterate enumerables, dictionaries and even read whole streams, so properties/fields fits in that paradigm.

    One option would be to rename EqualTo into ValueEquals along the SameAs to clearly specify the intend.
    It is too late for NUnit4 but we could already add a ValueEquals for people to make the transition.

    But as @stevenaw says, there are many constraints that implicit use an EqualConstraint:

    • Has.Member
    • Does.Contain
    • Contains.Item
    • Contains
    • Member
    • EqualTo

    There also the separate constraints uses NUnitEqualityComparer themselves:

    • CollectionItemsEqualConstraint which again is used by several other mainly Dictionary constraints.
    • AnyOfConstraint, is documented with value is equal. I don't think there is a reference equivalent.
    • CollectionTally as used by Equivalent, Subset, Superset.

    Not all have an SameAs equivalent, nor the same options to specify an additional comparer.

    When adding the PropertiesComparer, I initially thought of using it as an extra comparer users can specify, but that only would test a top level class, not nested and also would not have the benefit of calling into the NUnitEqualityComparer recursively to get the benefits of the other comparers (including tolerance) for each property.

    We need to see if we can come up with or have to add to a set of all constraints that use either Value or Reference comparison.

    • Is.EqualTo vs Is.SameAs
    • Has.Member == Has.Some.EqualTo vs Has.Some.SameAs
    • Is.EquivalentTo has no equivalent for reference comparison only, but could use .Using<object, object>((x, y) => object.ReferenceEquals(x, y)) which is quite long.
    • etc.
      Once we have that list and added any missing constraints we need to add that to the documentation.
      But I think all the above needs to have it own issue.

    An alternative is to have a "comparison mode" where users specify value or reference behaviour.
    Again this means changing API.

    For the immediate case I can change PropertiesComparer into a FieldComparer, but I would like to compare both public and private fields (to catch backing fields of properties). This will work around properties that are not value properties and will fix the indexer throwing.

    I give another thought on making it optional with a Using. I couldn't do what I wanted with a class outside NUnit, but it might work with one defined there.

    Sorry that this got a bit long.

  18. batzen commented on Dec 9, 2023

    @batzen
    Contributor

    @manfred-brands I think comparing fields would be even worse than comparing properties. Comparing something private should be way out of scope for a test framework.

    All i am asking for is to be able, without using reflection, to globally turn off the PropertiesComparer.

    I still think that blindly calling into every property is generally a bad idea as no one knows which cost and side effects that might have.

  19. appel1 commented on Dec 12, 2023

    @appel1

    Ran into a problem because of this when comparing not yet completed tasks. PropertiesComparer called Task.Result which caused a deadlock.

    The fix here is not to use EqualsTo but instead use SameAs. But thought I should mention it.

    var tcs1 = new TaskCompletionSource<int>();
    var tcs2 = new TaskCompletionSource<int>();
    
    // Do things here that results in two tasks that took the completion source tasks as input. 
    
    var task1 = tcs1.Task;
    var task2 = tcs2.Task;
    
    Assert.That(task2, Is.Not.EqualTo(task1)); <- Causes hang
    
    tcs1.SetResult(0);
    Assert.That(task1.IsCompleted, Is.True);
    Assert.That(task2.IsCompleted, Is.False);
  20. rauhs commented on Jan 22, 2024

    @rauhs

    Could this added to the breaking changes for v4? This behavior change just cost us a bit of time.

  21. manfred-brands commented on Jan 24, 2024

    @manfred-brands
    Member

    I created a PR to go back to 3.14 behaviour for Is.EqualTo and add an UsingPropertiesComparer() method to enable it.
    This would cause no breaking changes, but allows the functionality to be used when needed.

  22. added this to the 4.1 milestone on Jan 27, 2024
  23. OsirisTerje commented on Feb 19, 2024

    @OsirisTerje
    Member
  24. Mazzelfassel commented on Feb 19, 2024

    @Mazzelfassel
    Author

    Tested it on my code and it seems to work fine so far. The tests that were broken before are working as expected now.

  25. OsirisTerje commented on Feb 21, 2024

    @OsirisTerje
    Member

    @manfred-brands We need to document the UsingPropertiesComparer. From what I can see it is added to four constraints. I'm adding it to the Modifiers list for those four.

    We probably don't need to do anything more right now, but we could add some more description of it later, how it works (like single level, not deep), and when to use it.

    I'm also considering mentioning it as a possible breaking change since in 4.0 it is included, whereas in 4.1. it is optional. However, in earlier versions it did not exist, so. What do you think?

    PS: A bit more than four actually:

    image

  26. OsirisTerje commented on Feb 21, 2024

    @OsirisTerje
    Member

    It might be a bit late for changes here, but when doing the documentation I see that the naming differs from the other Using modifiers.
    image

    Should it follow the others, it would be more like : Using(IPropertiesComparer compare)

    But it is not easier to use, and it causes the user to specify which propertycomparer to use.

    It is probably ok as is. Just wanted to mention it.

  27. manfred-brands commented on Feb 22, 2024

    @manfred-brands
    Member

    @OsirisTerje I initially tried to create a class PropertiesComparer : IComparer however that means NUnit only calls into that comparer. What I needed was an integration where only if all other known comparers were exhausted, NUnit will call into the properties comparer. The properties comparer also calls into NUnit comparer for all individual properties which in turn only as a means of last resort call properties comparer again.
    This was the reason it was initially 'always on'.
    I thought of calling the method EnablePropertiesComparer, but choose the Using prefix to align with the others that select a different compare mode.

  28. manfred-brands commented on Feb 22, 2024

    @manfred-brands
    Member

    @OsirisTerje I'll make time to work on nunit/docs#812

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

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions