ExactCountConstraint
ExactCountConstraint applies another constraint to each
item in a collection, succeeding only if a specified
number of items succeed.
using NUnit.Framework.Internal;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
namespace NUnit.Framework.Constraints
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class ExactCountConstraint : Constraint
{
private readonly int _expectedCount;
[System.Runtime.CompilerServices.Nullable(2)]
private readonly IConstraint _itemConstraint;
public override string Description {
get {
object obj;
if (_expectedCount != 0) {
if (_expectedCount != 1) {
DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(14, 1);
defaultInterpolatedStringHandler.AppendLiteral("exactly ");
defaultInterpolatedStringHandler.AppendFormatted(_expectedCount);
defaultInterpolatedStringHandler.AppendLiteral(" items");
obj = defaultInterpolatedStringHandler.ToStringAndClear();
} else
obj = "exactly one item";
} else
obj = "no item";
string text = (string)obj;
if (_itemConstraint == null)
return text;
return PrefixConstraint.FormatDescription(text, _itemConstraint);
}
}
public ExactCountConstraint(int expectedCount)
: base(Array.Empty<object>())
{
_expectedCount = expectedCount;
}
public ExactCountConstraint(int expectedCount, IConstraint itemConstraint)
: base(itemConstraint)
{
Guard.ArgumentNotNull(itemConstraint, "itemConstraint");
_itemConstraint = itemConstraint.Resolve();
_expectedCount = expectedCount;
}
public override ConstraintResult ApplyTo<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual)
{
IEnumerable enumerable = ConstraintUtils.RequireActual<IEnumerable>(actual, "actual", false);
Collection<object> collection = new Collection<object>();
int num = 0;
foreach (object item in enumerable) {
if (_itemConstraint != null) {
if (_itemConstraint.ApplyTo(item).IsSuccess)
num++;
} else
num++;
if (collection.Count <= 10)
collection.Add(item);
}
return new ExactCountConstraintResult(this, actual, num == _expectedCount, num, collection);
}
}
}