diff --git a/CHANGELOG.md b/CHANGELOG.md index f2e1ed8..21f3ec0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Fixed `WithoutStrictOrdering()` comparing only the first item of collections whose items have no settable simple properties or differ only in nested members. Items are now paired by full equivalency, and a failure shows the member differences of the items left without a pair. Tests that passed with such differing items now fail. + ## 2.0.0 - **Breaking change:** Restored C# short-circuit evaluation for assertion `&&` operators, including async, dynamic, local-function, and pattern expressions. Conditions after the first false operand no longer run. Null and type guards keep their native behavior. diff --git a/learnings.md b/learnings.md index b74249c..1e67a34 100644 --- a/learnings.md +++ b/learnings.md @@ -100,6 +100,7 @@ This document is organized by topic to consolidate key learnings about the proje - `scripts/test-nunit-output.sh` checks an intentional failure outside the solution with NUnit 4.6.1 and adapter 6.3.0; a nonzero test exit alone is not enough to prove diagnostics. - DateTimeOffset equivalency needs a native `==` comparer: the dependency's built-in comparer compares local clock values and ignores sub-millisecond differences. Put explicit custom comparers before the default so `EqualsExact` can compare offsets. +- Unordered equivalency must not use the dependency's `IgnoreCollectionOrder` matching: it keys items by settable simple properties only, so get-only objects all get the type name as key and only the first pair is compared. Pair items by full deep comparison instead. - Nullable equivalency selectors use generic overloads. The legacy non-generic signatures use nullable-oblivious annotations: `Expression>` would cause CS8620 for existing `Expression>` variables. Keep nullable warnings enabled and test both forms. For a generic selector, unwrap only conversion nodes; a unary operation such as `-item.Id` is not a member selector. diff --git a/src/SharpAssert.Runtime/Features/Equivalency/EquivalencyConfig.cs b/src/SharpAssert.Runtime/Features/Equivalency/EquivalencyConfig.cs index 6cc369f..9bb29f9 100644 --- a/src/SharpAssert.Runtime/Features/Equivalency/EquivalencyConfig.cs +++ b/src/SharpAssert.Runtime/Features/Equivalency/EquivalencyConfig.cs @@ -163,6 +163,7 @@ public EquivalencyConfig Including(Expression> memb public EquivalencyConfig WithoutStrictOrdering() { ComparisonConfig.IgnoreCollectionOrder = true; + ComparisonConfig.CustomComparers.Add(new UnorderedCollectionComparer()); return this; } @@ -188,6 +189,7 @@ public EquivalencyConfig WithoutStrictOrdering() public EquivalencyConfig WithStrictOrdering() { ComparisonConfig.IgnoreCollectionOrder = false; + ComparisonConfig.CustomComparers.RemoveAll(comparer => comparer is UnorderedCollectionComparer); return this; } diff --git a/src/SharpAssert.Runtime/Features/Equivalency/UnorderedCollectionComparer.cs b/src/SharpAssert.Runtime/Features/Equivalency/UnorderedCollectionComparer.cs new file mode 100644 index 0000000..f781a45 --- /dev/null +++ b/src/SharpAssert.Runtime/Features/Equivalency/UnorderedCollectionComparer.cs @@ -0,0 +1,73 @@ +// ABOUTME: Compares collections without regard to order by pairing each item with an equivalent one. +// ABOUTME: Matches items by full deep comparison and reports member differences of the items left without a pair. + +using System.Collections; +using KellermanSoftware.CompareNetObjects; +using KellermanSoftware.CompareNetObjects.TypeComparers; + +namespace SharpAssert; + +sealed class UnorderedCollectionComparer : BaseTypeComparer +{ + public UnorderedCollectionComparer() : base(RootComparerFactory.GetRootComparer()) { } + + public override bool IsTypeMatch(Type type1, Type type2) => + IsCollection(type1) && IsCollection(type2); + + public override void CompareType(CompareParms parms) + { + var unmatchedActual = new List<(object? item, int index)>(); + var unmatchedExpected = Items(parms.Object2).Select((item, index) => (item, index)).ToList(); + + foreach (var (item, index) in Items(parms.Object1).Select((item, index) => (item, index))) + { + var match = unmatchedExpected.FindIndex(each => AreEquivalent(parms.Config, item, each.item)); + if (match >= 0) + unmatchedExpected.RemoveAt(match); + else + unmatchedActual.Add((item, index)); + } + + foreach (var (actual, expected) in unmatchedActual.Zip(unmatchedExpected)) + CompareLeftovers(parms, actual.index, actual.item, expected.item); + + foreach (var (item, index) in unmatchedActual.Skip(unmatchedExpected.Count)) + AddUnmatched(parms, index, item, null); + + foreach (var (item, index) in unmatchedExpected.Skip(unmatchedActual.Count)) + AddUnmatched(parms, index, null, item); + } + + void CompareLeftovers(CompareParms parms, int index, object? actual, object? expected) => + RootComparer.Compare(new CompareParms + { + Result = parms.Result, + Config = parms.Config, + ParentObject1 = parms.Object1, + ParentObject2 = parms.Object2, + Object1 = actual, + Object2 = expected, + BreadCrumb = $"{parms.BreadCrumb}[{index}]" + }); + + static bool IsCollection(Type type) => + typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string); + + static List Items(object collection) => + ((IEnumerable)collection).Cast().ToList(); + + static bool AreEquivalent(ComparisonConfig config, object? actual, object? expected) => + new CompareLogic(config).Compare(actual, expected).AreEqual; + + void AddUnmatched(CompareParms parms, int index, object? actual, object? expected) => + AddDifference(parms.Result, new Difference + { + ParentObject1 = parms.ParentObject1, + ParentObject2 = parms.ParentObject2, + PropertyName = $"{parms.BreadCrumb}[{index}]", + Object1Value = NiceString(actual), + Object2Value = NiceString(expected), + Object1 = actual, + Object2 = expected + }); +} diff --git a/src/SharpAssert.Tests/Features/EquivalencyFixture.cs b/src/SharpAssert.Tests/Features/EquivalencyFixture.cs index 841fd04..9745688 100644 --- a/src/SharpAssert.Tests/Features/EquivalencyFixture.cs +++ b/src/SharpAssert.Tests/Features/EquivalencyFixture.cs @@ -77,6 +77,75 @@ public void Should_ignore_collection_order_when_configured() AssertPasses(() => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering()))); } + [Test] + public void Should_fail_when_unordered_get_only_objects_differ_after_first_item() + { + var actual = new[] { new Money(1, "USD"), new Money(2, "EUR") }; + var expected = new[] { new Money(1, "USD"), new Money(3, "UAH") }; + + var action = () => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering())); + action.Should().Throw(); + } + + [Test] + public void Should_fail_when_unordered_objects_differ_only_in_nested_member() + { + var actual = new[] { Married("Anna"), Married("Kate") }; + var expected = new[] { Married("Anna"), Married("Mary") }; + + var action = () => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering())); + action.Should().Throw(); + } + + [Test] + public void Should_pass_when_unordered_get_only_objects_are_shuffled() + { + var actual = new[] { new Money(1, "USD"), new Money(2, "EUR") }; + var expected = new[] { new Money(2, "EUR"), new Money(1, "USD") }; + + AssertPasses(() => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering()))); + } + + [Test] + public void Should_fail_when_unordered_collection_has_an_extra_item() + { + var actual = new[] { new Money(1, "USD"), new Money(2, "EUR") }; + var expected = new[] { new Money(2, "EUR") }; + + var action = () => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering())); + action.Should().Throw(); + } + + [Test] + public void Should_fail_when_unordered_collection_misses_an_item() + { + var actual = new[] { new Money(2, "EUR") }; + var expected = new[] { new Money(1, "USD"), new Money(2, "EUR") }; + + var action = () => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering())); + action.Should().Throw(); + } + + [Test] + public void Should_keep_string_characters_in_order_when_collection_order_is_ignored() + { + var actual = new Person { Name = "abc" }; + var expected = new Person { Name = "cba" }; + + var action = () => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering())); + action.Should().Throw(); + } + + [Test] + public void Should_fail_when_strict_ordering_follows_unordered_configuration() + { + var actual = new[] { new Money(1, "USD"), new Money(2, "EUR") }; + var expected = new[] { new Money(2, "EUR"), new Money(1, "USD") }; + + var action = () => Assert(actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering().WithStrictOrdering())); + action.Should().Throw(); + } + [Test] public void Should_fail_when_collection_order_differs_by_default() { @@ -374,11 +443,26 @@ public void Should_fail_when_record_Equals_returns_false() config.ComparingRecordsByValue())); action.Should().Throw(); } + + static PersonWithSpouse Married(string spouse) => + new() { Name = "John", Age = 30, Spouse = new PersonWithSpouse { Name = spouse, Age = 30 } }; } [TestFixture] class FormattingTests { + [Test] + public void Should_render_member_differences_of_unmatched_unordered_items() + { + var actual = new[] { new Money(1, "USD"), new Money(2, "EUR") }; + var expected = new[] { new Money(1, "USD"), new Money(3, "UAH") }; + + var expectation = actual.IsEquivalentTo(expected, config => config.WithoutStrictOrdering()); + var result = expectation.Evaluate(TestContext("test")); + + Rendered(result).Should().Contain("[1].Amount: expected \"3\", got \"2\""); + } + [Test] public void Should_render_property_differences_clearly() {