diff --git a/CHANGELOG.md b/CHANGELOG.md index f2e1ed8..4c55467 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Added `IsSequence(params T[])` to check a collection against items listed inline, in order, and `HasSameItems` to check the same items in any order with duplicates counted. Failures show the differing index, or the missing and extra items. +- Added `IsExactly()` to check the exact runtime type of any value, including a caught exception. +- Documented the collection quantifiers in the README. The migration guide now maps `AllSatisfy`, `OnlyContain`, `ContainSingle(pred)`, `WithMessage`, `ThrowExactly` and `BeOfType` to checks with the same meaning. + ## 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/MIGRATION.md b/MIGRATION.md index a1e329a..75d487a 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -170,7 +170,7 @@ Required imports: ```csharp using static SharpAssert.Sharp; // For Assert(), Throws() using SharpAssert; // For custom expectations (IsEquivalentTo, etc.) -using SharpAssert.Features.Collections; // For IsInAscendingOrder(), AllUnique() +using SharpAssert.Features.Collections; // For IsInAscendingOrder(), AllUnique(), IsSequence(), HasSameItems() using SharpAssert.Features.Strings; // For Matches(), occurrence counting using SharpAssert.Features.Proximity; // For BeCloseTo(), BeApproximately() ``` @@ -204,12 +204,16 @@ coll.Should().BeEmpty() → Assert(!coll.Any()) coll.Should().NotBeEmpty() → Assert(coll.Any()) coll.Should().HaveCount(n) → Assert(coll.Count() == n) coll.Should().Equal(expected) → Assert(coll.SequenceEqual(expected)) +coll.Should().Equal(1, 2, 3) → Assert(coll.IsSequence(1, 2, 3)) +coll.Should().BeEquivalentTo(expected) → Assert(coll.HasSameItems(expected)) // simple items, any order coll.Should().BeInAscendingOrder() → Assert(coll.IsInAscendingOrder()) coll.Should().BeInDescendingOrder() → Assert(coll.IsInDescendingOrder()) coll.Should().OnlyHaveUniqueItems() → Assert(coll.AllUnique()) coll.Should().OnlyHaveUniqueItems(x=>x.K) → Assert(coll.AllUnique(x => x.K)) coll.Should().ContainSingle() → Assert(coll.Count() == 1) -coll.Should().AllSatisfy(pred) → Assert(coll.All(pred)) +coll.Should().ContainSingle(pred) → Assert(coll.One(pred)) +coll.Should().AllSatisfy(pred) → Assert(coll.Any()); Assert(coll.Each(pred)) // All/Each pass on an empty collection +coll.Should().OnlyContain(pred) → Assert(coll.Any()); Assert(coll.Each(pred)) coll.Should().ContainInOrder(seq) → Assert(coll.ContainsInOrder(seq)) coll.Should().ContainInConsecutiveOrder(s)→ Assert(coll.ContainsInConsecutiveOrder(s)) coll.Should().BeSubsetOf(superset) → Assert(coll.IsSubsetOf(superset)) @@ -218,6 +222,8 @@ coll.Should().Satisfy(p1, p2, p3) → Assert(coll.Satisfies(p1, p2, p3)) // Objects - Basic obj.Should().BeEquivalentTo(exp) → Assert(obj.IsEquivalentTo(exp)) +obj.Should().BeOfType() → Assert(obj.IsExactly()) +obj.Should().BeAssignableTo() → Assert(obj is T) obj.Should().BeEquivalentTo(exp, o=>o.Excluding(x=>x.Id)) → Assert(obj.IsEquivalentTo(exp, c=>c.Excluding(x=>x.Id))) obj.Should().BeEquivalentTo(exp, o=>o.Including(x=>x.Name)) @@ -259,7 +265,8 @@ obj.Should().BeEquivalentTo(exp, o=>o.ComparingRecordsByValue()) act.Should().Throw() → Assert(Throws(act)) act.Should().NotThrow() → Assert(!Throws(act)) act.Should().ThrowAsync() → Assert(await ThrowsAsync(act)) -act.Should().Throw().WithMessage(msg) → Assert(Throws(act).Message.Contains(msg)) +act.Should().Throw().WithMessage(msg) → Assert(Throws(act).Message.Matches(msg)) // * wildcards, full match +act.Should().ThrowExactly() → Assert(Throws(act).Exception.IsExactly()) // Check independent conditions separately. x.Should().Be(5) → Assert(x == 5); diff --git a/README.md b/README.md index 8412204..03d2686 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ SharpAssert uses **MSBuild source rewriting** to automatically transform your as - **[Collection Comparison](#collection-comparisons)** - First mismatch, missing/extra elements detection - **[Collection Ordering](#collection-ordering)** - Ascending/descending order validation - **[Collection Uniqueness](#collection-uniqueness)** - Duplicate detection with key selectors +- **[Collection Quantifiers](#collection-quantifiers)** - `Each`, `Some`, `None`, `One`, `Exactly` with per-item diagnostics - **[Object Deep Diff](#object-deep-comparison)** - Property-level differences for objects/records (powered by Compare-Net-Objects) - **[Object Equivalency](#object-equivalency)** - Structural comparison with property exclusion/inclusion - **[LINQ Operations](#linq-operations)** - Enhanced diagnostics for Contains/Any/All operations @@ -168,6 +169,17 @@ Assert(actual.SequenceEqual(expected)); // Actual: 3 ``` +List the expected items inline, in order or in any order: + +```csharp +using SharpAssert.Features.Collections; + +Assert(ids.IsSequence(1, 2, 3)); // same items, same order +Assert(ids.HasSameItems(3, 1, 2)); // same items, any order, duplicates counted +Assert(names.HasSameItems(expected, StringComparer.OrdinalIgnoreCase)); +// Expected the same items as [3, 1, 2], but found [1, 2, 4]: missing [3], extra [4]. +``` + ### String Pattern Matching Wildcard patterns with `*` (any sequence) and `?` (single character): @@ -230,6 +242,21 @@ Assert(users.AllUnique(u => u.Email)); Assert(items.AllUnique(StringComparer.OrdinalIgnoreCase)); ``` +### Collection Quantifiers + +Check how many items match a condition. Failures list the items that broke it: + +```csharp +Assert(orders.Each(o => o.Total > 0)); // every item; passes on an empty collection +Assert(orders.Some(o => o.IsPaid)); // at least one +Assert(orders.None(o => o.IsCancelled)); // no item +Assert(orders.One(o => o.IsDraft)); // exactly one +Assert(orders.Exactly(2, o => o.IsUrgent)); // also AtLeast and AtMost +``` + +`Each` passes on an empty collection, like LINQ `All`. Add `Assert(orders.Any())` when +the collection must not be empty. + ### Object Deep Comparison Property-level diffs powered by Compare-Net-Objects: @@ -326,6 +353,15 @@ Assert(await ThrowsAsync(() => Task.Run(() => throw new InvalidOperationException()))); ``` +`Throws` also accepts subclasses of `T`. To require the exact type, check it with +`IsExactly()`, which works on any value: + +```csharp +Assert(Throws(() => Parse(text)).Exception.IsExactly()); +Assert(chart.IsExactly()); +// Expected type TextChart, but found ImageChart. +``` + Keep single-use delegates and exception checks inside `Assert`. Do not add an `Action` variable and a separate result just to assert one property. Compound conditions on one captured exception are valid; the action runs once. diff --git a/src/SharpAssert.Runtime/Features/Collections/CollectionExtensions.cs b/src/SharpAssert.Runtime/Features/Collections/CollectionExtensions.cs index 64e34a3..a47190e 100644 --- a/src/SharpAssert.Runtime/Features/Collections/CollectionExtensions.cs +++ b/src/SharpAssert.Runtime/Features/Collections/CollectionExtensions.cs @@ -1,5 +1,5 @@ // ABOUTME: Extension methods for collection validation expectations (ordering, uniqueness, set operations). -// ABOUTME: Provides IsInAscendingOrder/IsInDescendingOrder, AllUnique, ContainsInOrder, subset/superset APIs. +// ABOUTME: Provides IsInAscendingOrder/IsInDescendingOrder, AllUnique, ContainsInOrder, IsSequence, HasSameItems, subset/superset APIs. using System; using System.Collections.Generic; @@ -280,6 +280,70 @@ static Expectation CheckIntersects(IEnumerable collection, IEnumerable public static SatisfiesExpectation Satisfies(this IEnumerable collection, params Func[] predicates) => new SatisfiesExpectation(collection, predicates); + /// Checks that the collection has exactly the given items in the given order. + /// Assert(ids.IsSequence(1, 2, 3)); + public static Expectation IsSequence(this IEnumerable collection, params T[] expected) => + Expectation.From( + () => collection.SequenceEqual(expected), + () => + { + var actual = collection.ToList(); + var reason = actual.Count == expected.Length + ? DifferingItem(actual, expected) + : $"{actual.Count} items instead of {expected.Length}"; + return [$"Expected sequence {FormatSequence(expected.ToList())}, but found {FormatSequence(actual)}: {reason}."]; + } + ); + + static string DifferingItem(List actual, T[] expected) + { + var index = Enumerable.Range(0, actual.Count).First(i => !EqualityComparer.Default.Equals(actual[i], expected[i])); + return $"item at index {index} is {ValueFormatter.Format(actual[index])} instead of {ValueFormatter.Format(expected[index])}"; + } + + /// Checks that the collection has the same items as in any order. Duplicates are counted. + /// Assert(ids.HasSameItems(3, 1, 2)); + public static Expectation HasSameItems(this IEnumerable collection, params T[] expected) => + CheckSameItems(collection, expected, EqualityComparer.Default); + + /// Checks that the collection has the same items as in any order. Duplicates are counted. + public static Expectation HasSameItems(this IEnumerable collection, IEnumerable expected) => + CheckSameItems(collection, expected, EqualityComparer.Default); + + /// Checks that the collection has the same items as in any order, using . + public static Expectation HasSameItems(this IEnumerable collection, IEnumerable expected, IEqualityComparer comparer) => + CheckSameItems(collection, expected, comparer); + + static Expectation CheckSameItems(IEnumerable collection, IEnumerable expected, IEqualityComparer comparer) => + Expectation.From( + () => Difference(collection, expected, comparer) is { Missing.Count: 0, Extra.Count: 0 }, + () => + { + var (missing, extra) = Difference(collection, expected, comparer); + var parts = new List(); + if (missing.Count > 0) parts.Add($"missing {FormatSequence(missing)}"); + if (extra.Count > 0) parts.Add($"extra {FormatSequence(extra)}"); + return [$"Expected the same items as {FormatSequence(expected.ToList())}, but found {FormatSequence(collection.ToList())}: {string.Join(", ", parts)}."]; + } + ); + + static (List Missing, List Extra) Difference(IEnumerable collection, IEnumerable expected, IEqualityComparer comparer) + { + var missing = expected.ToList(); + var extra = new List(); + + foreach (var item in collection) + { + var index = missing.FindIndex(each => comparer.Equals(each, item)); + if (index >= 0) + missing.RemoveAt(index); + else + extra.Add(item); + } + + return (missing, extra); + } + static string FormatSequence(List items) { var formatted = string.Join(", ", items.Select(x => ValueFormatter.Format(x))); diff --git a/src/SharpAssert.Runtime/Features/Types/TypeExtensions.cs b/src/SharpAssert.Runtime/Features/Types/TypeExtensions.cs new file mode 100644 index 0000000..6b92532 --- /dev/null +++ b/src/SharpAssert.Runtime/Features/Types/TypeExtensions.cs @@ -0,0 +1,20 @@ +// ABOUTME: Extension methods for runtime type assertions. +// ABOUTME: Provides IsExactly() to check the exact runtime type without accepting subclasses. + +using SharpAssert.Features.Shared; + +namespace SharpAssert; + +/// +/// Provides runtime type expectations. +/// +public static class TypeExtensions +{ + /// Checks that the value has exactly the runtime type . Subclasses and null fail. + /// Assert(chart.IsExactly<TextChart>()); + public static Expectation IsExactly(this object? value) => + Expectation.From( + () => value?.GetType() == typeof(T), + () => [$"Expected type {typeof(T).Name}, but found {value?.GetType().Name ?? "null"}."] + ); +} diff --git a/src/SharpAssert.Tests/Features/HasSameItemsFixture.cs b/src/SharpAssert.Tests/Features/HasSameItemsFixture.cs new file mode 100644 index 0000000..134956a --- /dev/null +++ b/src/SharpAssert.Tests/Features/HasSameItemsFixture.cs @@ -0,0 +1,76 @@ +// ABOUTME: Tests for HasSameItems expectation +// ABOUTME: Validates that two collections have the same items in any order, duplicates counted + +using FluentAssertions; +using NUnit.Framework; +using SharpAssert.Features.Collections; +using static SharpAssert.Sharp; + +namespace SharpAssert.Features; + +[TestFixture] +public class HasSameItemsFixture : TestBase +{ + [TestFixture] + class LogicTests + { + [Test] + public void Should_pass_when_items_are_in_another_order() + { + var collection = new List { 3, 1, 2 }; + var expected = new[] { 1, 2, 3 }; + + AssertPasses(() => Assert(collection.HasSameItems(expected))); + } + + [Test] + public void Should_fail_when_duplicates_differ() + { + var collection = new[] { 1, 1, 2 }; + + var act = () => Assert(collection.HasSameItems(1, 2, 2)); + act.Should().Throw(); + } + + [Test] + public void Should_compare_items_with_comparer() + { + var collection = new[] { "A", "b" }; + var expected = new[] { "B", "a" }; + + AssertPasses(() => Assert(collection.HasSameItems(expected, StringComparer.OrdinalIgnoreCase))); + } + } + + [TestFixture] + class FormattingTests + { + [Test] + public void Should_render_missing_and_extra_items() + { + var collection = new[] { 1, 2, 4 }; + var expectation = collection.HasSameItems(3, 2, 1); + var context = TestContext("collection.HasSameItems(3, 2, 1)"); + + var result = expectation.Evaluate(context); + + AssertRendersExactly(result, + "False", + "Expected the same items as [3, 2, 1], but found [1, 2, 4]: missing [3], extra [4]."); + } + + [Test] + public void Should_render_only_missing_items() + { + var collection = new[] { 1 }; + var expectation = collection.HasSameItems(1, 2); + var context = TestContext("collection.HasSameItems(1, 2)"); + + var result = expectation.Evaluate(context); + + AssertRendersExactly(result, + "False", + "Expected the same items as [1, 2], but found [1]: missing [2]."); + } + } +} diff --git a/src/SharpAssert.Tests/Features/IsExactlyFixture.cs b/src/SharpAssert.Tests/Features/IsExactlyFixture.cs new file mode 100644 index 0000000..8444389 --- /dev/null +++ b/src/SharpAssert.Tests/Features/IsExactlyFixture.cs @@ -0,0 +1,65 @@ +// ABOUTME: Tests for IsExactly expectation +// ABOUTME: Validates that a value has exactly the given runtime type, not a subclass + +using FluentAssertions; +using NUnit.Framework; +using static SharpAssert.Sharp; + +namespace SharpAssert.Features; + +[TestFixture] +public class IsExactlyFixture : TestBase +{ + [TestFixture] + class LogicTests + { + [Test] + public void Should_pass_for_the_exact_type() + { + object value = new ArgumentException(); + + AssertPasses(() => Assert(value.IsExactly())); + } + + [Test] + public void Should_fail_for_a_subclass() + { + object value = new ArgumentNullException(); + + var act = () => Assert(value.IsExactly()); + act.Should().Throw(); + } + } + + [TestFixture] + class FormattingTests + { + [Test] + public void Should_render_failure_with_actual_type() + { + object value = new ArgumentNullException(); + var expectation = value.IsExactly(); + var context = TestContext("value.IsExactly()"); + + var result = expectation.Evaluate(context); + + AssertRendersExactly(result, + "False", + "Expected type ArgumentException, but found ArgumentNullException."); + } + + [Test] + public void Should_render_failure_for_null() + { + object? value = null; + var expectation = value.IsExactly(); + var context = TestContext("value.IsExactly()"); + + var result = expectation.Evaluate(context); + + AssertRendersExactly(result, + "False", + "Expected type ArgumentException, but found null."); + } + } +} diff --git a/src/SharpAssert.Tests/Features/IsSequenceFixture.cs b/src/SharpAssert.Tests/Features/IsSequenceFixture.cs new file mode 100644 index 0000000..ded5c0f --- /dev/null +++ b/src/SharpAssert.Tests/Features/IsSequenceFixture.cs @@ -0,0 +1,66 @@ +// ABOUTME: Tests for IsSequence expectation +// ABOUTME: Validates that a collection has exactly the given items in the given order + +using FluentAssertions; +using NUnit.Framework; +using SharpAssert.Features.Collections; +using static SharpAssert.Sharp; + +namespace SharpAssert.Features; + +[TestFixture] +public class IsSequenceFixture : TestBase +{ + [TestFixture] + class LogicTests + { + [Test] + public void Should_pass_when_items_match_in_order() + { + var collection = new List { 1, 2, 3 }; + + AssertPasses(() => Assert(collection.IsSequence(1, 2, 3))); + } + + [Test] + public void Should_fail_when_order_differs() + { + var collection = new[] { 3, 2, 1 }; + + var act = () => Assert(collection.IsSequence(1, 2, 3)); + act.Should().Throw(); + } + } + + [TestFixture] + class FormattingTests + { + [Test] + public void Should_render_failure_with_differing_item() + { + var collection = new[] { 1, 2, 4 }; + var expectation = collection.IsSequence(1, 2, 3); + var context = TestContext("collection.IsSequence(1, 2, 3)"); + + var result = expectation.Evaluate(context); + + AssertRendersExactly(result, + "False", + "Expected sequence [1, 2, 3], but found [1, 2, 4]: item at index 2 is 4 instead of 3."); + } + + [Test] + public void Should_render_failure_with_different_length() + { + var collection = new[] { 1, 2, 3 }; + var expectation = collection.IsSequence(1, 2); + var context = TestContext("collection.IsSequence(1, 2)"); + + var result = expectation.Evaluate(context); + + AssertRendersExactly(result, + "False", + "Expected sequence [1, 2], but found [1, 2, 3]: 3 items instead of 2."); + } + } +}