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
Expand Up @@ -68,4 +68,47 @@ public static void CallerArgumentExpression()
act.Should().Throw<ArgumentOutOfRangeException>()
.WithParameterName(nameof(testArray));
}

[Fact]
public static void DefaultImmutableArrayInRange()
{
var defaultArray = default(ImmutableArray<int>);

var result = defaultArray.MustHaveLengthIn(Range.FromInclusive(0).ToInclusive(5));

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void DefaultImmutableArrayNotInRange()
{
var defaultArray = default(ImmutableArray<int>);

var act = () => defaultArray.MustHaveLengthIn(Range.FromInclusive(1).ToInclusive(5), nameof(defaultArray));

act.Should().Throw<ArgumentOutOfRangeException>()
.And.Message.Should().Contain("must have its length in between 1 (inclusive) and 5 (inclusive)")
.And.Contain("has no length because it is the default instance");
}

[Fact]
public static void DefaultImmutableArrayCustomException()
{
var defaultArray = default(ImmutableArray<int>);

Test.CustomException(
defaultArray,
Range.FromInclusive(1).ToInclusive(5),
(array, r, exceptionFactory) => array.MustHaveLengthIn(r, exceptionFactory)
);
}

[Fact]
public static void DefaultImmutableArrayCustomMessage() =>
Test.CustomMessage<ArgumentOutOfRangeException>(
message => default(ImmutableArray<int>).MustHaveLengthIn(
Range.FromInclusive(1).ToInclusive(5),
message: message
)
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
using System;
using System.Collections.Immutable;
using FluentAssertions;
using Light.GuardClauses.Exceptions;
using Xunit;

namespace Light.GuardClauses.Tests.CollectionAssertions;

public static class MustHaveMaximumLengthTests
{
[Theory]
[InlineData(new[] { 1, 2, 3, 4 }, 3)]
[InlineData(new[] { 1, 2 }, 1)]
[InlineData(new[] { 500 }, 0)]
public static void ImmutableArrayMoreItems(int[] items, int length)
{
var immutableArray = items.ToImmutableArray();
Action act = () => immutableArray.MustHaveMaximumLength(length, nameof(immutableArray));

var assertion = act.Should().Throw<InvalidCollectionCountException>().Which;
assertion.Message.Should().Contain(
$"{nameof(immutableArray)} must have at most a length of {length}, but it actually has a length of {immutableArray.Length}."
);
assertion.ParamName.Should().BeSameAs(nameof(immutableArray));
}

[Theory]
[InlineData(new[] { "Foo" }, 1)]
[InlineData(new[] { "Bar" }, 2)]
[InlineData(new[] { "Baz", "Qux", "Quux" }, 5)]
public static void ImmutableArrayLessOrEqualItems(string[] items, int length)
{
var immutableArray = items.ToImmutableArray();
var result = immutableArray.MustHaveMaximumLength(length);
result.Should().Equal(immutableArray);
}

[Fact]
public static void ImmutableArrayEmpty()
{
var emptyArray = ImmutableArray<int>.Empty;
var result = emptyArray.MustHaveMaximumLength(5);
result.Should().Equal(emptyArray);
}

[Theory]
[InlineData(new[] { 87, 89, 99 }, 1)]
[InlineData(new[] { 1, 2, 3 }, -30)]
public static void ImmutableArrayCustomException(int[] items, int maximumLength)
{
var immutableArray = items.ToImmutableArray();

Action act = () => immutableArray.MustHaveMaximumLength(
maximumLength,
(array, length) => new ($"Custom exception for array with length {array.Length} and max {length}")
);

act.Should().Throw<Exception>()
.WithMessage($"Custom exception for array with length {immutableArray.Length} and max {maximumLength}");
}

[Fact]
public static void ImmutableArrayNoCustomExceptionThrown()
{
var immutableArray = new[] { "Foo", "Bar" }.ToImmutableArray();
var result = immutableArray.MustHaveMaximumLength(2, (_, _) => new ());
result.Should().Equal(immutableArray);
}

[Fact]
public static void ImmutableArrayCustomMessage()
{
var immutableArray = new[] { 1, 2, 3 }.ToImmutableArray();

Test.CustomMessage<InvalidCollectionCountException>(
message => immutableArray.MustHaveMaximumLength(2, message: message)
);
}

[Fact]
public static void ImmutableArrayCallerArgumentExpression()
{
var myImmutableArray = new[] { 1, 2, 3 }.ToImmutableArray();

var act = () => myImmutableArray.MustHaveMaximumLength(2);

act.Should().Throw<InvalidCollectionCountException>()
.WithParameterName(nameof(myImmutableArray));
}

[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(5)]
public static void
DefaultImmutableArrayInstanceShouldNotThrowWhenLengthIsGreaterThanOrEqualToZero(int validLength) =>
default(ImmutableArray<int>).MustHaveMaximumLength(validLength).IsDefault.Should().BeTrue();

[Theory]
[InlineData(-1)]
[InlineData(-5)]
[InlineData(-12)]
public static void DefaultImmutableArrayInstanceShouldNotThrowWhenLengthIsNegative(int negativeLength)
{
var act = () => default(ImmutableArray<int>).MustHaveMaximumLength(negativeLength);

act.Should().Throw<InvalidCollectionCountException>()
.WithParameterName("default(ImmutableArray<int>)")
.WithMessage(
$"default(ImmutableArray<int>) must have at most a length of {negativeLength}, but it actually has no length because it is the default instance.*"
);
}

[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(5)]
public static void DefaultImmutableArrayInstanceCustomExceptionShouldNotThrow(int validLength)
{
var result = default(ImmutableArray<int>).MustHaveMaximumLength(validLength, (_, _) => new Exception());
result.IsDefault.Should().BeTrue();
}

[Theory]
[InlineData(-1)]
[InlineData(-5)]
[InlineData(-12)]
public static void DefaultImmutableArrayInstanceCustomExceptionShouldThrow(int negativeLength)
{
var act = () => default(ImmutableArray<int>).MustHaveMaximumLength(
negativeLength,
(array, length) => new ArgumentException(
$"Custom: Array length {(array.IsDefault ? 0 : array.Length)} exceeds maximum {length}"
)
);

act.Should().Throw<ArgumentException>()
.WithMessage("Custom: Array length 0 exceeds maximum *");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,51 @@ public static void ImmutableArrayCallerArgumentExpression()
act.Should().Throw<ExistingItemException>()
.WithParameterName(nameof(array));
}

[Fact]
public static void ImmutableArrayDefaultInstanceDoesNotContainItem()
{
var defaultArray = default(ImmutableArray<int>);

// Default instance should not throw for any item since it cannot contain anything
var result = defaultArray.MustNotContain(42);

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void ImmutableArrayDefaultInstanceCustomException()
{
var defaultArray = default(ImmutableArray<string>);

// Default instance should not throw even with custom exception factory
var result = defaultArray.MustNotContain(
"test",
(_, _) => new InvalidOperationException("Should not be called")
);

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void ImmutableArrayDefaultInstanceCustomMessage()
{
var defaultArray = default(ImmutableArray<object>);

// Default instance should not throw even with custom message
var result = defaultArray.MustNotContain(new object(), message: "Custom message");

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void ImmutableArrayDefaultInstanceCallerArgumentExpression()
{
var defaultArray = default(ImmutableArray<char>);

// Default instance should not throw, so no exception to check parameter name
var result = defaultArray.MustNotContain('x');

result.IsDefault.Should().BeTrue();
}
}
6 changes: 4 additions & 2 deletions Code/Light.GuardClauses/Check.MustHaveLengthIn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ public static ImmutableArray<T> MustHaveLengthIn<T>(
string? message = null
)
{
if (!range.IsValueWithinRange(parameter.Length))
var length = parameter.IsDefault ? 0 : parameter.Length;
if (!range.IsValueWithinRange(length))
{
Throw.ImmutableArrayLengthNotInRange(parameter, range, parameterName, message);
}
Expand All @@ -98,7 +99,8 @@ public static ImmutableArray<T> MustHaveLengthIn<T>(
Func<ImmutableArray<T>, Range<int>, Exception> exceptionFactory
)
{
if (!range.IsValueWithinRange(parameter.Length))
var length = parameter.IsDefault ? 0 : parameter.Length;
if (!range.IsValueWithinRange(length))
{
Throw.CustomException(exceptionFactory, parameter, range);
}
Expand Down
60 changes: 60 additions & 0 deletions Code/Light.GuardClauses/Check.MustHaveMaximumLength.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using Light.GuardClauses.ExceptionFactory;
using Light.GuardClauses.Exceptions;

namespace Light.GuardClauses;

public static partial class Check
{
/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" /> has at most the specified length, or otherwise throws an <see cref="InvalidCollectionCountException" />.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="length">The maximum length the <see cref="ImmutableArray{T}" /> should have.</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="InvalidCollectionCountException">Thrown when <paramref name="parameter" /> has more than the specified length.</exception>
/// <remarks>The default instance of <see cref="ImmutableArray{T}"/> will be treated as having length 0.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustHaveMaximumLength<T>(
this ImmutableArray<T> parameter,
int length,
[CallerArgumentExpression("parameter")] string? parameterName = null,
string? message = null
)
{
var parameterLength = parameter.IsDefault ? 0 : parameter.Length;
if (parameterLength > length)
{
Throw.InvalidMaximumImmutableArrayLength(parameter, length, parameterName, message);
}

return parameter;
}

/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" /> has at most the specified length, or otherwise throws your custom exception.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="length">The maximum length the <see cref="ImmutableArray{T}" /> should have.</param>
/// <param name="exceptionFactory">The delegate that creates your custom exception. <paramref name="parameter" /> and <paramref name="length" /> are passed to this delegate.</param>
/// <exception cref="Exception">Your custom exception thrown when <paramref name="parameter" /> has more than the specified length.</exception>
/// <remarks>The default instance of <see cref="ImmutableArray{T}"/> will be treated as having length 0.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustHaveMaximumLength<T>(
this ImmutableArray<T> parameter,
int length,
Func<ImmutableArray<T>, int, Exception> exceptionFactory
)
{
var parameterLength = parameter.IsDefault ? 0 : parameter.Length;
if (parameterLength > length)
{
Throw.CustomException(exceptionFactory, parameter, length);
}

return parameter;
}
}
10 changes: 8 additions & 2 deletions Code/Light.GuardClauses/Check.MustNotContain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ public static string MustNotContain(
/// <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>
/// <remarks>
/// The default instance of <see cref="ImmutableArray{T}" /> cannot contain any items, so this method will not throw for default instances.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustNotContain<T>(
this ImmutableArray<T> parameter,
Expand All @@ -215,7 +218,7 @@ public static ImmutableArray<T> MustNotContain<T>(
string? message = null
)
{
if (parameter.Contains(item))
if (!parameter.IsDefault && parameter.Contains(item))
{
Throw.ExistingItem(parameter, item, parameterName, message);
}
Expand All @@ -230,6 +233,9 @@ public static ImmutableArray<T> MustNotContain<T>(
/// <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>
/// <remarks>
/// The default instance of <see cref="ImmutableArray{T}" /> cannot contain any items, so this method will not throw for default instances.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[ContractAnnotation("exceptionFactory:null => halt")]
public static ImmutableArray<T> MustNotContain<T>(
Expand All @@ -238,7 +244,7 @@ public static ImmutableArray<T> MustNotContain<T>(
Func<ImmutableArray<T>, T, Exception> exceptionFactory
)
{
if (parameter.Contains(item))
if (!parameter.IsDefault && parameter.Contains(item))
{
Throw.CustomException(exceptionFactory, parameter, item);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ public static void ImmutableArrayLengthNotInRange<T>(
throw new ArgumentOutOfRangeException(
parameterName,
message ??
$"{parameterName ?? "The immutable array"} must have its length in between {range.CreateRangeDescriptionText("and")}, but it actually has length {parameter.Length}."
$"{parameterName ?? "The immutable array"} must have its length in between {range.CreateRangeDescriptionText("and")}, but it actually {(parameter.IsDefault ? "has no length because it is the default instance" : $"has length {parameter.Length}")}."
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Light.GuardClauses.Exceptions;

namespace Light.GuardClauses.ExceptionFactory;

public static partial class Throw
{
/// <summary>
/// Throws the default <see cref="InvalidCollectionCountException" /> indicating that an <see cref="ImmutableArray{T}" /> has more than a
/// maximum number of items, using the optional parameter name and message.
/// </summary>
[ContractAnnotation("=> halt")]
[DoesNotReturn]
public static void InvalidMaximumImmutableArrayLength<T>(
ImmutableArray<T> parameter,
int length,
[CallerArgumentExpression("parameter")] string? parameterName = null,
string? message = null
)
{
throw new InvalidCollectionCountException(
parameterName,
message ??
$"{parameterName ?? "The immutable array"} must have at most a length of {length}, but it actually {(parameter.IsDefault ? "has no length because it is the default instance" : $"has a length of {parameter.Length}")}."
);
}
}
Loading