Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using FluentAssertions;
using Light.GuardClauses.Exceptions;
Expand Down Expand Up @@ -75,4 +76,68 @@ public static void CallerArgumentExpression()
act.Should().Throw<ExistingItemException>()
.WithParameterName(nameof(array));
}

[Theory]
[InlineData(new[] { "Foo", "Bar" }, "Foo")]
[InlineData(new[] { "Baz", "Qux", "Quux" }, "Qux")]
[InlineData(new[] { "Corge", "Grault", null }, null)]
public static void ImmutableArrayItemExists(string[] items, string item)
{
var array = ImmutableArray.Create(items);

Action act = () => array.MustNotContain(item, nameof(array));

var assertions = act.Should().Throw<ExistingItemException>().Which;
assertions.Message.Should()
.Contain($"{nameof(array)} must not contain {item.ToStringOrNull()}, but it actually does.");
assertions.ParamName.Should().BeSameAs(nameof(array));
}

[Theory]
[InlineData(new[] { 100, 101, 102 }, 42)]
[InlineData(new[] { 11 }, -5000)]
public static void ImmutableArrayItemExistsNot(int[] items, int item)
{
var array = ImmutableArray.Create(items);
array.MustNotContain(item).Should().Equal(array);
}

[Fact]
public static void ImmutableArrayEmptyDoesNotContainItem()
{
var emptyArray = ImmutableArray<int>.Empty;
emptyArray.MustNotContain(42).Should().Equal(emptyArray);
}

[Fact]
public static void ImmutableArrayCustomException() =>
Test.CustomException(
ImmutableArray.Create("Foo"),
"Foo",
(array, value, exceptionFactory) => array.MustNotContain(value, exceptionFactory)
);

[Fact]
public static void ImmutableArrayNoCustomExceptionThrown()
{
var array = ImmutableArray.Create(1, 2);
array.MustNotContain(3, (_, _) => new ()).Should().Equal(array);
}

[Fact]
public static void ImmutableArrayCustomMessage() =>
Test.CustomMessage<ExistingItemException>(
message => ImmutableArray.Create(42).MustNotContain(42, message: message)
);

[Fact]
public static void ImmutableArrayCallerArgumentExpression()
{
var array = ImmutableArray.Create(1, 2, 3);

Action act = () => array.MustNotContain(3);

act.Should().Throw<ExistingItemException>()
.WithParameterName(nameof(array));
}
}
48 changes: 48 additions & 0 deletions Code/Light.GuardClauses/Check.MustNotContain.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
Expand Down Expand Up @@ -197,4 +198,51 @@ public static string MustNotContain(

return parameter;
}

/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" /> does not contain the specified item, or otherwise throws an <see cref="ExistingItemException" />.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="item">The item that must not be part of the <see cref="ImmutableArray{T}" />.</param>
/// <param name="parameterName">The name of the parameter (optional).</param>
/// <param name="message">The message that will be passed to the resulting exception (optional).</param>
/// <exception cref="ExistingItemException">Thrown when <paramref name="parameter" /> contains <paramref name="item" />.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustNotContain<T>(
this ImmutableArray<T> parameter,
T item,
[CallerArgumentExpression("parameter")] string? parameterName = null,
string? message = null
)
{
if (parameter.Contains(item))
{
Throw.ExistingItem(parameter, item, parameterName, message);
}

return parameter;
}

/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" /> does not contain the specified item, or otherwise throws your custom exception.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="item">The item that must not be part of the <see cref="ImmutableArray{T}" />.</param>
/// <param name="exceptionFactory">The delegate that creates your custom exception. <paramref name="parameter" /> and <paramref name="item" /> are passed to this delegate.</param>
/// <exception cref="Exception">Your custom exception thrown when <paramref name="parameter" /> contains <paramref name="item" />.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[ContractAnnotation("exceptionFactory:null => halt")]
public static ImmutableArray<T> MustNotContain<T>(
this ImmutableArray<T> parameter,
T item,
Func<ImmutableArray<T>, T, Exception> exceptionFactory
)
{
if (parameter.Contains(item))
{
Throw.CustomException(exceptionFactory, parameter, item);
}

return parameter;
}
}
20 changes: 20 additions & 0 deletions Code/Plans/issue-116-must-not-contain-for-immutable-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Issue 116 - MustNotContain for ImmutableArray

## Context

The .NET library Light.GuardClauses already has several assertions for collections. They often rely on `IEnumerable<T>` or `IEnumerable`. However, these assertions would result in `ImmutableArray<T>` being boxed - we want to avoid that by providing dedicated assertions for this type which avoids boxing. For this issue, we implement the `MustNotContain` assertion for `ImmutableArray<T>`.

## Tasks for this issue

- [ ] The production code should be placed in the Light.GuardClauses project. The file `Check.MustNotContain.cs` already exists in the root folder of the project - extend this existing file.
- [ ] In this file, create two extension method overloads called `MustNotContain` for `ImmutableArray<T>`. It should be placed in the class `Check` which is marked as `partial`.
- [ ] Each assertion in Light.GuardClauses has two overloads - the first one takes the optional `parameterName` and `message` arguments and throw the default exception. The actual exception is thrown in the `Throw` class - use the existing `Throw.ExistingItem` method which is located in `ExceptionFactory/Throw.ExistingItem.cs`.
- [ ] The other overload takes a delegate which allows the caller to provide their own custom exceptions. Use the existing `Throw.CustomException` method and pass the delegate, the erroneous `ImmutableArray<T>` instance and the unwanted item.
- [ ] Create unit tests for both overloads. The corresponding tests should be placed in Light.GuardClauses.Tests project, in the existing file 'CollectionAssertions/MustNotContainTests.cs'. Please follow conventions of the existing tests (e.g. use FluentAssertions' `Should()` for assertions).

## Notes

- There are already plenty of other assertions and tests in this library. All overloads are placed in the same file in the production code project. The test projects has top-level folders for different groups of assertions, like `CollectionAssertions`, `StringAssertions`, `DateTimeAssertions` and so on. Please take a look at them to follow a similar structure and code style.
- This assertion specifically targets `ImmutableArray<T>` to avoid boxing that would occur with generic `IEnumerable<T>` extensions.
- The assertion should verify that the `ImmutableArray<T>` does not contain the specified item.
- If you have any questions or suggestions, please ask me about them.