AttributeExistsConstraint
AttributeExistsConstraint tests for the presence of a
specified attribute on a Type.
using NUnit.Compatibility;
using System;
using System.Runtime.CompilerServices;
namespace NUnit.Framework.Constraints
{
[NullableContext(1)]
[Nullable(0)]
public class AttributeExistsConstraint : Constraint
{
private readonly Type _expectedType;
public override string Description => "type with attribute " + MsgUtils.FormatValue(_expectedType);
public AttributeExistsConstraint(Type type)
: base(type)
{
_expectedType = type;
if (!typeof(Attribute).IsAssignableFrom(_expectedType)) {
DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(25, 1);
defaultInterpolatedStringHandler.AppendLiteral("Type ");
defaultInterpolatedStringHandler.AppendFormatted(_expectedType);
defaultInterpolatedStringHandler.AppendLiteral(" is not an attribute");
throw new ArgumentException(defaultInterpolatedStringHandler.ToStringAndClear(), "type");
}
}
public override ConstraintResult ApplyTo<[Nullable(2)] TActual>(TActual actual)
{
Guard.ArgumentNotNull(actual, "actual");
Attribute[] customAttributes = AttributeHelper.GetCustomAttributes(actual, _expectedType, true);
ConstraintResult constraintResult = new ConstraintResult(this, actual);
constraintResult.Status = ((customAttributes.Length != 0) ? ConstraintStatus.Success : ConstraintStatus.Failure);
return constraintResult;
}
}
}