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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>()` 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.
Expand Down
13 changes: 10 additions & 3 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ Required imports:
```csharp
using static SharpAssert.Sharp; // For Assert(), Throws<T>()
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()
```
Expand Down Expand Up @@ -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))
Expand All @@ -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<T>() → Assert(obj.IsExactly<T>())
obj.Should().BeAssignableTo<T>() → 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))
Expand Down Expand Up @@ -259,7 +265,8 @@ obj.Should().BeEquivalentTo(exp, o=>o.ComparingRecordsByValue())
act.Should().Throw<T>() → Assert(Throws<T>(act))
act.Should().NotThrow() → Assert(!Throws<Exception>(act))
act.Should().ThrowAsync<T>() → Assert(await ThrowsAsync<T>(act))
act.Should().Throw<T>().WithMessage(msg) → Assert(Throws<T>(act).Message.Contains(msg))
act.Should().Throw<T>().WithMessage(msg) → Assert(Throws<T>(act).Message.Matches(msg)) // * wildcards, full match
act.Should().ThrowExactly<T>() → Assert(Throws<T>(act).Exception.IsExactly<T>())

// Check independent conditions separately.
x.Should().Be(5) → Assert(x == 5);
Expand Down
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -326,6 +353,15 @@ Assert(await ThrowsAsync<InvalidOperationException>(() =>
Task.Run(() => throw new InvalidOperationException())));
```

`Throws<T>` also accepts subclasses of `T`. To require the exact type, check it with
`IsExactly<T>()`, which works on any value:

```csharp
Assert(Throws<ArgumentException>(() => Parse(text)).Exception.IsExactly<ArgumentException>());
Assert(chart.IsExactly<TextChart>());
// 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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -280,6 +280,70 @@ static Expectation CheckIntersects<T>(IEnumerable<T> collection, IEnumerable<T>
public static SatisfiesExpectation<T> Satisfies<T>(this IEnumerable<T> collection, params Func<T, bool>[] predicates) =>
new SatisfiesExpectation<T>(collection, predicates);

/// <summary>Checks that the collection has exactly the given items in the given order.</summary>
/// <example><code>Assert(ids.IsSequence(1, 2, 3));</code></example>
public static Expectation IsSequence<T>(this IEnumerable<T> 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<T>(List<T> actual, T[] expected)
{
var index = Enumerable.Range(0, actual.Count).First(i => !EqualityComparer<T>.Default.Equals(actual[i], expected[i]));
return $"item at index {index} is {ValueFormatter.Format(actual[index])} instead of {ValueFormatter.Format(expected[index])}";
}

/// <summary>Checks that the collection has the same items as <paramref name="expected"/> in any order. Duplicates are counted.</summary>
/// <example><code>Assert(ids.HasSameItems(3, 1, 2));</code></example>
public static Expectation HasSameItems<T>(this IEnumerable<T> collection, params T[] expected) =>
CheckSameItems(collection, expected, EqualityComparer<T>.Default);

/// <summary>Checks that the collection has the same items as <paramref name="expected"/> in any order. Duplicates are counted.</summary>
public static Expectation HasSameItems<T>(this IEnumerable<T> collection, IEnumerable<T> expected) =>
CheckSameItems(collection, expected, EqualityComparer<T>.Default);

/// <summary>Checks that the collection has the same items as <paramref name="expected"/> in any order, using <paramref name="comparer"/>.</summary>
public static Expectation HasSameItems<T>(this IEnumerable<T> collection, IEnumerable<T> expected, IEqualityComparer<T> comparer) =>
CheckSameItems(collection, expected, comparer);

static Expectation CheckSameItems<T>(IEnumerable<T> collection, IEnumerable<T> expected, IEqualityComparer<T> 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<string>();
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<T> Missing, List<T> Extra) Difference<T>(IEnumerable<T> collection, IEnumerable<T> expected, IEqualityComparer<T> comparer)
{
var missing = expected.ToList();
var extra = new List<T>();

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<T>(List<T> items)
{
var formatted = string.Join(", ", items.Select(x => ValueFormatter.Format(x)));
Expand Down
20 changes: 20 additions & 0 deletions src/SharpAssert.Runtime/Features/Types/TypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// ABOUTME: Extension methods for runtime type assertions.
// ABOUTME: Provides IsExactly<T>() to check the exact runtime type without accepting subclasses.

using SharpAssert.Features.Shared;

namespace SharpAssert;

/// <summary>
/// Provides runtime type expectations.
/// </summary>
public static class TypeExtensions
{
/// <summary>Checks that the value has exactly the runtime type <typeparamref name="T"/>. Subclasses and null fail.</summary>
/// <example><code>Assert(chart.IsExactly&lt;TextChart&gt;());</code></example>
public static Expectation IsExactly<T>(this object? value) =>
Expectation.From(
() => value?.GetType() == typeof(T),
() => [$"Expected type {typeof(T).Name}, but found {value?.GetType().Name ?? "null"}."]
);
}
76 changes: 76 additions & 0 deletions src/SharpAssert.Tests/Features/HasSameItemsFixture.cs
Original file line number Diff line number Diff line change
@@ -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<int> { 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<SharpAssertionException>();
}

[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].");
}
}
}
65 changes: 65 additions & 0 deletions src/SharpAssert.Tests/Features/IsExactlyFixture.cs
Original file line number Diff line number Diff line change
@@ -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<ArgumentException>()));
}

[Test]
public void Should_fail_for_a_subclass()
{
object value = new ArgumentNullException();

var act = () => Assert(value.IsExactly<ArgumentException>());
act.Should().Throw<SharpAssertionException>();
}
}

[TestFixture]
class FormattingTests
{
[Test]
public void Should_render_failure_with_actual_type()
{
object value = new ArgumentNullException();
var expectation = value.IsExactly<ArgumentException>();
var context = TestContext("value.IsExactly<ArgumentException>()");

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<ArgumentException>();
var context = TestContext("value.IsExactly<ArgumentException>()");

var result = expectation.Evaluate(context);

AssertRendersExactly(result,
"False",
"Expected type ArgumentException, but found null.");
}
}
}
Loading