Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions learnings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Func<T, object?>>` would cause CS8620 for existing `Expression<Func<T, object>>` 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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ public EquivalencyConfig<T> Including<TMember>(Expression<Func<T, TMember>> memb
public EquivalencyConfig<T> WithoutStrictOrdering()
{
ComparisonConfig.IgnoreCollectionOrder = true;
ComparisonConfig.CustomComparers.Add(new UnorderedCollectionComparer());
return this;
}

Expand All @@ -188,6 +189,7 @@ public EquivalencyConfig<T> WithoutStrictOrdering()
public EquivalencyConfig<T> WithStrictOrdering()
{
ComparisonConfig.IgnoreCollectionOrder = false;
ComparisonConfig.CustomComparers.RemoveAll(comparer => comparer is UnorderedCollectionComparer);
return this;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<object?> Items(object collection) =>
((IEnumerable)collection).Cast<object?>().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
});
}
84 changes: 84 additions & 0 deletions src/SharpAssert.Tests/Features/EquivalencyFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SharpAssertionException>();
}

[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<SharpAssertionException>();
}

[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<SharpAssertionException>();
}

[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<SharpAssertionException>();
}

[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<SharpAssertionException>();
}

[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<SharpAssertionException>();
}

[Test]
public void Should_fail_when_collection_order_differs_by_default()
{
Expand Down Expand Up @@ -374,11 +443,26 @@ public void Should_fail_when_record_Equals_returns_false()
config.ComparingRecordsByValue()));
action.Should().Throw<SharpAssertionException>();
}

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()
{
Expand Down