public void CustomValidation_Legal_Custom_Reference_Type() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidRefType"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNull(cva.GetValidationResult(new BaseRefType(), context)); }
public void CustomValidation_Ctor_1_Param() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidNoMessage"); Assert.AreEqual(typeof(MockValidator), cva.ValidatorType); Assert.AreEqual("IsValidNoMessage", cva.Method); }
public static void GetValidationResult_MethodReturnDerivedValidationResult_ReturnsExpected() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.ValidationMethodDerivedReturnTypeReturnsSomeError)); ValidationResult validationResult = attribute.GetValidationResult(new object(), s_testValidationContext); Assert.Equal(DerivedValidationResult.SomeError, validationResult); }
public static CustomValidationAttribute CreateCustomAttribute(Type validatorType, string method, string errorMessage = null) { var returnValue = new CustomValidationAttribute(validatorType, method); UpdateErrorMessage(returnValue, errorMessage); return(returnValue); }
private void WriteCustomValidation(ILWriter writer, PropertyInfo property, CustomValidationAttribute customValidationAttribute) { var validationKind = ValidationKind.Custom; var validatorType = typeof(ICustomValidator <>).MakeGenericType(property.PropertyType); if (!customValidationAttribute.ValidatorType.CanBe(validatorType)) { var message = CommonErrors.CustomValidatorMustBeOfType.WithValues(property.ReflectedType.Name, property.Name, property.PropertyType.Name); throw new IncorrectValidationAttributeException(typeof(CustomValidationAttribute), message); } var localValidator = writer.DeclareLocal(validatorType); writer.New(customValidationAttribute.ValidatorType); writer.SetLocal(localValidator); var validate = KnownMetadata.Methods.ICustomValidator_OfType(property.PropertyType); writer.LoadLocal(localValidator); writer.LoadFirstParameter(); writer.GetPropertyValue(property); writer.InstanceMethodCall(validate); var end = writer.IfFalseThen(); WriteFailureResult(writer, validationKind, CommonResults.CustomValidationDidNotSucceed.WithValues(property.ReflectedType.Name, property.Name)); writer.Return(); writer.MarkLabel(end); }
public void CustomValidation_Explicit_Null_Nullable_Value_Type() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidNullableValueType"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNull(cva.GetValidationResult(null, context)); }
public static void Ctor_Type_String(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Equal(validatorType, attribute.ValidatorType); Assert.Equal(method, attribute.Method); }
public void CustomValidation_Valid_Value_2_Param() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValid"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNull(cva.GetValidationResult("Fred", context)); }
public void CustomValidation_Invalid_Type_Reference_Type_Fails() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValid"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNotNull(cva.GetValidationResult(cva, context)); // cva is wrong type -- must be string Assert.AreEqual("wrong is not valid.", cva.FormatErrorMessage("wrong")); }
public void CustomValidation_Legal_Derived_Reference_Type() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidRefType"); DerivedRefType instance = new DerivedRefType(); ValidationContext context = new ValidationContext(instance, null, null); Assert.IsNull(cva.GetValidationResult(instance, context)); }
public void CustomValidation_Illegal_SuperType_Reference_Type_Fails() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidRefType"); BaseBaseRefType instance = new BaseBaseRefType(); ValidationContext context = new ValidationContext(instance, null, null); Assert.IsNotNull(cva.GetValidationResult(instance, context)); }
public void CustomValidation_NonConvertable_Nullable_Value_Type_Fails() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidNullableValueType"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNotNull(cva.GetValidationResult("fred", context)); Assert.AreEqual("type is not valid.", cva.FormatErrorMessage("type")); }
public void FormatErrorMessage_NotPerformedValidation_ContainsName() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)); string errorMessage = attribute.FormatErrorMessage("name"); Assert.Contains("name", errorMessage); Assert.Equal(errorMessage, attribute.FormatErrorMessage("name")); }
public void CustomValidation_Out_of_Range_Value_Type_Fails() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidValueType"); ValidationContext context = new ValidationContext(new object(), null, null); context.MemberName = "range"; Assert.IsNotNull(cva.GetValidationResult(-1, context)); Assert.AreEqual("wrong range", cva.FormatErrorMessage("")); }
public void CustomValidation_Method_Throws() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "Throws"); Assert.AreEqual("Throws", cva.Method); ValidationContext context = new ValidationContext(new object(), null, null); ExceptionHelper.ExpectArgumentException(delegate() { cva.GetValidationResult("Fred", context); // valid call, but this method throws }, "o"); }
public static void Validate_IConvertibleThrowsCustomException_IsNotCaught() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgInt)); Assert.Throws <ArithmeticException>(() => attribute.Validate(new IConvertibleImplementor() { IntThrow = new ArithmeticException() }, s_testValidationContext)); }
public void CustomValidation_Invalid_Value_3_Param() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValid"); ValidationContext context = new ValidationContext(new object(), null, null); context.MemberName = "member"; Assert.IsNotNull(cva.GetValidationResult("Joe", context)); Assert.AreEqual("$member", cva.FormatErrorMessage("")); }
public void CustomValidation_CustomType_Succeeds() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidCustomType"); Customer cust = new Customer { IsValid = true }; ValidationContext context = new ValidationContext(cust, null, null); Assert.IsNull(cva.GetValidationResult(cust, context)); }
public void CustomValidation_Invalid_Value_1_Param() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidNoMessage"); cva.ErrorMessage = "The value '{0}' is bogus"; // to show we get message from ErrorMessage instead ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNotNull(cva.GetValidationResult("Joe", context)); Assert.AreEqual("The value 'joe' is bogus", cva.FormatErrorMessage("joe")); }
public void FormatErrorMessage_PerformedValidation_DoesNotContainName() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)); Assert.False(attribute.IsValid(new TestClass("AnyString"))); string errorMessage = attribute.FormatErrorMessage("name"); Assert.DoesNotContain("name", errorMessage); Assert.Equal(errorMessage, attribute.FormatErrorMessage("name")); }
// Helper to assert the attribute fails with the expected error private static void AssertFailure(CustomValidationAttribute cva, string expectedError) { ValidationContext context = new ValidationContext(new object(), null, null); ExceptionHelper.ExpectException <InvalidOperationException>(delegate() { cva.GetValidationResult(null, context); }, expectedError); ExceptionHelper.ExpectException <InvalidOperationException>(delegate() { cva.FormatErrorMessage(string.Empty); }, expectedError); }
public static void RequiresValidationContext_Get_ReturnsExpected(string method, bool expected) { CustomValidationAttribute attribute = GetAttribute(method); // The .NET Framework has a bug where CustomValidationAttribute doesn't // validate the context. See https://github.com/dotnet/runtime/issues/21100. if (PlatformDetection.IsNetFramework) { Assert.False(attribute.RequiresValidationContext); } else { Assert.Equal(expected, attribute.RequiresValidationContext); } }
public void Attributes_Cities_State_Name_Has_Expected_Validation_Attributes() { RequiredAttribute r = ExpectPropertyAttribute <RequiredAttribute>(typeof(State), "Name"); StringLengthAttribute sl = ExpectPropertyAttribute <StringLengthAttribute>(typeof(State), "Name"); Assert.AreEqual(2, sl.MaximumLength); RegularExpressionAttribute regEx = ExpectPropertyAttribute <RegularExpressionAttribute>(typeof(State), "Name"); Assert.AreEqual("^[A-Z]*", regEx.Pattern); CustomValidationAttribute custom = ExpectPropertyAttribute <CustomValidationAttribute>(typeof(State), "Name"); Assert.AreEqual(typeof(StateNameValidator), custom.ValidatorType); Assert.AreEqual("IsStateNameValid", custom.Method); }
public void CustomValidation_Legal_Convertible_Value_Type() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidValueType"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNull(cva.GetValidationResult(5, context)); Assert.IsNull(cva.GetValidationResult((byte)1, context)); Assert.IsNull(cva.GetValidationResult((short)2, context)); Assert.IsNull(cva.GetValidationResult((long)2, context)); Assert.IsNull(cva.GetValidationResult((uint)3, context)); Assert.IsNull(cva.GetValidationResult((ulong)3, context)); Assert.IsNull(cva.GetValidationResult(4.1f, context)); Assert.IsNull(cva.GetValidationResult(5.2d, context)); Assert.IsNull(cva.GetValidationResult("6", context)); Assert.IsNull(cva.GetValidationResult((decimal)7.33, context)); }
public static CustomValidationAttribute CreateCustomValidationAttribute(this XElement annotation) { const string NAME = "CustomValidation"; string name = annotation.Attribute(SchemaVocab.Name).Value; if (name != NAME) { throw new ArgumentException(string.Format(SchemaMessages.ExpectedBut, NAME, name)); } string type = annotation.GetArgumentValue("ValidatorType"); Type validatorType = GetType(type); string method = annotation.GetArgumentValue("Method"); CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); FillValidationAttribute(attribute, annotation); return(attribute); }
public override AttributeDeclaration GetAttributeDeclaration(Attribute attribute) { CustomValidationAttribute cva = (CustomValidationAttribute)attribute; // Our convention is that parameter validation in the CVA occurs when it is // first used. Simply ask the attribute to produce an error message, as this // will trigger an InvalidOperationException if the attribute is ill-formed cva.FormatErrorMessage(string.Empty); // Delegate to the base implementation to generate the attribute. // Note that the base implementation already checks that Types are // shared so we do not perform that check here. AttributeDeclaration attributeDeclaration = base.GetAttributeDeclaration(attribute); attributeDeclaration.RequiredTypes.Add(cva.ValidatorType); attributeDeclaration.RequiredMethods.Add(cva.ValidatorType.GetMethod(cva.Method)); return(attributeDeclaration); }
public void Constructor() { var attr = new CustomValidationAttribute(null, "MyMethod"); Assert.IsNull(attr.ValidatorType, "#A1-1"); Assert.AreEqual("MyMethod", attr.Method, "#A1-2"); attr = new CustomValidationAttribute(typeof(string), null); Assert.AreEqual(typeof(string), attr.ValidatorType, "#A2-1"); Assert.IsNull(attr.Method, "#A2-2"); attr = new CustomValidationAttribute(null, null); Assert.IsNull(attr.ValidatorType, "#A3-1"); Assert.IsNull(attr.Method, "#A3-2"); attr = new CustomValidationAttribute(typeof(string), "NoSuchMethod"); Assert.AreEqual(typeof(string), attr.ValidatorType, "#A5-1"); Assert.AreEqual("NoSuchMethod", attr.Method, "#A5-2"); }
public void TypeId() { var attr = new CustomValidationAttribute(null, "MyMethod"); Assert.IsNotNull(attr.TypeId, "#A1-1"); Assert.AreEqual(typeof(Tuple <string, Type>), attr.TypeId.GetType(), "#A1-2"); var typeid = attr.TypeId as Tuple <string, Type>; Assert.IsNotNull(typeid.Item1, "#A2-1"); Assert.AreEqual("MyMethod", typeid.Item1, "#A2-2"); Assert.IsNull(typeid.Item2, "#A2-3"); attr = new CustomValidationAttribute(typeof(CustomValidationAttributeTest), "MyMethod"); typeid = attr.TypeId as Tuple <string, Type>; Assert.IsNotNull(typeid.Item1, "#A3-1"); Assert.AreEqual("MyMethod", typeid.Item1, "#A3-2"); Assert.IsNotNull(typeid.Item2, "#A3-3"); Assert.AreEqual(typeof(CustomValidationAttributeTest), typeid.Item2, "#A3-4"); var typeid2 = attr.TypeId as Tuple <string, Type>; Assert.IsTrue(Object.ReferenceEquals(typeid, typeid2), "#A4"); }
public static void FormatErrorMessage_BadlyFormed_ThrowsInvalidOperationException(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Throws<InvalidOperationException>(() => attribute.FormatErrorMessage("name")); }
// Helper to assert the attribute fails with the expected error private static void AssertFailure(CustomValidationAttribute cva, string expectedError) { ValidationContext context = new ValidationContext(new object(), null, null); ExceptionHelper.ExpectException<InvalidOperationException>(delegate() { cva.GetValidationResult(null, context); }, expectedError); ExceptionHelper.ExpectException<InvalidOperationException>(delegate() { cva.FormatErrorMessage(string.Empty); }, expectedError); }
public void CustomValidation_Fail_Ctor_Empty_Method() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), string.Empty); AssertFailure(cva, "The CustomValidationAttribute.Method was not specified."); }
public void CustomValidation_Fail_Ctor_Non_Public() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(PrivateMockValidator), "IsValid"); AssertFailure(cva, "The custom validation type 'PrivateMockValidator' must be public."); }
public void CustomValidation_Fail_Method_Not_Static() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "NotStatic"); AssertFailure(cva, String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.CustomValidationAttribute_Method_Not_Found, cva.Method, cva.ValidatorType.Name)); }
public void CustomValidation_Fail_Method_Void_Return() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "VoidReturn"); AssertFailure(cva, String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.CustomValidationAttribute_Method_Must_Return_ValidationResult, cva.Method, cva.ValidatorType.Name)); }
public static void RequiresValidationContext_BadlyFormed_ThrowsInvalidOperationException(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Throws<InvalidOperationException>(() => attribute.RequiresValidationContext); }
public static void Constructor(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Equal(validatorType, attribute.ValidatorType); Assert.Equal(method, attribute.Method); }
public void CustomValidation_Null_Nullable_Value_Type() { int? nullableInt = null; CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidNullableValueType"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNull(cva.GetValidationResult(nullableInt, context)); }
public void CustomValidation_Fail_Ctor_Null_Type() { CustomValidationAttribute cva = new CustomValidationAttribute(null, "IsValid"); AssertFailure(cva, "The CustomValidationAttribute.ValidatorType was not specified."); }
public void CustomValidation_Legal_Nullable_Value_Type_Literal() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "IsValidNullableValueType"); ValidationContext context = new ValidationContext(new object(), null, null); Assert.IsNull(cva.GetValidationResult(5, context)); }
public static void Validate_BadlyFormed_ThrowsInvalidOperationException(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Does not matter", s_testValidationContext)); }
public void CustomValidation_Fail_Method_Not_Public() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "NotPublic"); AssertFailure(cva, String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.CustomValidationAttribute_Method_Not_Found, cva.Method, cva.ValidatorType.Name)); }
public void CustomValidation_Fail_Method_Too_Many_Params() { CustomValidationAttribute cva = new CustomValidationAttribute(typeof(MockValidator), "TooManyParams"); AssertFailure(cva, String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.CustomValidationAttribute_Method_Signature, cva.Method, cva.ValidatorType.Name)); }