SomeItemsConstraint
SomeItemsConstraint applies another constraint to each
item in a collection, succeeding if any of them succeeds.
using NUnit.Framework.Compatibility;
using System;
using System.Collections;
using System.Reflection;
using NUnit.Framework.Compatibility;
using System;
using System.Reflection;
namespace NUnit.Framework.Constraints
{
public class AttributeConstraint : PrefixConstraint
{
private readonly Type expectedType = type;
private Attribute attrFound;
public AttributeConstraint(Type type, IConstraint baseConstraint)
: base(baseConstraint)
{
descriptionPrefix = "attribute " + expectedType.FullName;
if (!IntrospectionExtensions.GetTypeInfo(typeof(Attribute)).IsAssignableFrom(expectedType.GetTypeInfo()))
throw new ArgumentException($"""{expectedType}""", "type");
}
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
Guard.ArgumentNotNull(actual, "actual");
Attribute[] customAttributes = AttributeHelper.GetCustomAttributes(actual, expectedType, true);
Attribute[] customAttributes;
if (customAttributes.Length == 0)
throw new ArgumentException($"""{expectedType}""", "actual");
attrFound = customAttributes[0];
return baseConstraint.ApplyTo(attrFound);
}
protected override string GetStringRepresentation()
{
return $"""{expectedType}""{baseConstraint}""";
}
}
}
namespace NUnit.Framework.Constraints
{
public class SomeItemsConstraint : PrefixConstraint
{
public SomeItemsConstraint(IConstraint itemConstraint)
: base(itemConstraint)
{
base.DisplayName = "Some";
descriptionPrefix = "some item";
}
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
if (!(((object)actual) is IEnumerable))
throw new ArgumentException("The actual value must be an IEnumerable", "actual");
foreach (object item in (IEnumerable)(object)actual) {
if (baseConstraint.ApplyTo(item).IsSuccess)
return new ConstraintResult(this, actual, ConstraintStatus.Success);
}
return new ConstraintResult(this, actual, ConstraintStatus.Failure);
}
}
}