示例#1
0
        public void Validate_Ordering()
        {
            // Proper order of invocation:
            // 1. OnValidating()
            // 2. Child validators
            // 3. This validator
            // 4. OnValidated()

            // Arrange
            var expected = new[]
            {
                "In OnValidating()",
                "In LoggingValidatonAttribute.IsValid()",
                "In IValidatableObject.Validate()",
                "In OnValidated()"
            };
            var log           = new List <string>();
            var model         = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var provider      = new EmptyModelMetadataProvider();
            var childMetadata = provider.GetMetadataForProperty(() => model, model.GetType(), "ValidStringProperty");
            var node          = new ModelValidationNode(modelMetadata, "theKey");

            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated  += (sender, e) => log.Add("In OnValidated()");
            node.ChildNodes.Add(new ModelValidationNode(childMetadata, "theKey.ValidStringProperty"));
            var context = CreateContext(modelMetadata);

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(expected, log);
        }
        public void SetProperty_PropertyIsSettable_CallsSetter()
        {
            // Arrange
            var model          = new Person();
            var bindingContext = CreateContext(GetMetadataForObject(model));

            var propertyMetadata  = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "DateOfBirth");
            var validationNode    = new ModelValidationNode(propertyMetadata, "foo");
            var dtoResult         = new ComplexModelDtoResult(new DateTime(2001, 1, 1), validationNode);
            var requiredValidator = bindingContext.ValidatorProviders
                                    .SelectMany(v => v.GetValidators(propertyMetadata))
                                    .Where(v => v.IsRequired)
                                    .FirstOrDefault();
            var validationContext = new ModelValidationContext(bindingContext, propertyMetadata);

            var testableBinder = new TestableMutableObjectModelBinder();

            // Act
            testableBinder.SetPropertyPublic(bindingContext, propertyMetadata, dtoResult, requiredValidator);

            // Assert
            validationNode.Validate(validationContext);
            Assert.Equal(true, bindingContext.ModelState.IsValid);
            Assert.Equal(new DateTime(2001, 1, 1), model.DateOfBirth);
        }
示例#3
0
        public void Validate_SkipsRemainingValidationIfModelStateIsInvalid()
        {
            // Because a property validator fails, the model validator shouldn't run

            // Arrange
            var expected = new[]
            {
                "In OnValidating()",
                "In IValidatableObject.Validate()",
                "In OnValidated()"
            };
            var log           = new List <string>();
            var model         = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var provider      = new EmptyModelMetadataProvider();
            var childMetadata = provider.GetMetadataForProperty(() => model,
                                                                model.GetType(),
                                                                "InvalidStringProperty");
            var node = new ModelValidationNode(modelMetadata, "theKey");

            node.ChildNodes.Add(new ModelValidationNode(childMetadata, "theKey.InvalidStringProperty"));
            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated  += (sender, e) => log.Add("In OnValidated()");
            var context = CreateContext(modelMetadata);

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(expected, log);
            Assert.Equal("Sample error message",
                         context.ModelState["theKey.InvalidStringProperty"].Errors[0].ErrorMessage);
        }
示例#4
0
        public void Validate_ValidateAllProperties_AddsValidationErrors()
        {
            // Arrange
            var model = new ValidateAllPropertiesModel
            {
                RequiredString = null /* error */,
                RangedInt      = 0 /* error */,
                ValidString    = "dog"
            };

            var modelMetadata = GetModelMetadata(model);
            var node          = new ModelValidationNode(modelMetadata, "theKey")
            {
                ValidateAllProperties = true
            };
            var context = CreateContext(modelMetadata);

            context.ModelState.AddModelError("theKey.RequiredString.Dummy", "existing Error Text");

            // Act
            node.Validate(context);

            // Assert
            Assert.False(context.ModelState.ContainsKey("theKey.RequiredString"));
            Assert.Equal("existing Error Text",
                         context.ModelState["theKey.RequiredString.Dummy"].Errors[0].ErrorMessage);
            Assert.Equal("The field RangedInt must be between 10 and 30.",
                         context.ModelState["theKey.RangedInt"].Errors[0].ErrorMessage);
            Assert.False(context.ModelState.ContainsKey("theKey.ValidString"));
            Assert.False(context.ModelState.ContainsKey("theKey"));
        }
示例#5
0
        public void Validate_ShortCircuits_IfModelStateHasReachedMaxNumberOfErrors()
        {
            // Arrange
            var model = new ValidateAllPropertiesModel
            {
                RequiredString = null /* error */,
                RangedInt      = 0 /* error */,
                ValidString    = "cat" /* error */
            };

            var modelMetadata = GetModelMetadata(model);
            var node          = new ModelValidationNode(modelMetadata, "theKey")
            {
                ValidateAllProperties = true
            };
            var context = CreateContext(modelMetadata);

            context.ModelState.MaxAllowedErrors = 3;
            context.ModelState.AddModelError("somekey", "error text");

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(3, context.ModelState.Count);
            Assert.IsType <TooManyModelErrorsException>(context.ModelState[""].Errors[0].Exception);
            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("RequiredString"),
                         context.ModelState["theKey.RequiredString"].Errors[0].ErrorMessage);
            Assert.False(context.ModelState.ContainsKey("theKey.RangedInt"));
            Assert.False(context.ModelState.ContainsKey("theKey.ValidString"));
        }
示例#6
0
        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorNotPresent_RegistersValidationCallback()
        {
            // Arrange
            var bindingContext    = CreateContext(GetMetadataForObject(new Person()));
            var propertyMetadata  = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "DateOfBirth");
            var validationNode    = new ModelValidationNode(propertyMetadata, "foo");
            var dtoResult         = new ComplexModelDtoResult(model: null, validationNode: validationNode);
            var requiredValidator = GetRequiredValidator(bindingContext, propertyMetadata);
            var validationContext = new ModelValidationContext(bindingContext, propertyMetadata);

            var testableBinder = new TestableMutableObjectModelBinder();

            // Act
            testableBinder.SetPropertyPublic(bindingContext, propertyMetadata, dtoResult, requiredValidator);

            // Assert
            Assert.Equal(true, bindingContext.ModelState.IsValid);
            validationNode.Validate(validationContext, bindingContext.ValidationNode);
            Assert.Equal(false, bindingContext.ModelState.IsValid);
        }
示例#7
0
        public void CombineWith()
        {
            // Arrange
            var expected = new[]
            {
                "Validating parent1.",
                "Validating parent2.",
                "Validated parent1.",
                "Validated parent2."
            };
            var log = new List <string>();

            var allChildNodes = new[]
            {
                new ModelValidationNode(GetModelMetadata(), "key1"),
                new ModelValidationNode(GetModelMetadata(), "key2"),
                new ModelValidationNode(GetModelMetadata(), "key3"),
            };

            var parentNode1 = new ModelValidationNode(GetModelMetadata(), "parent1");

            parentNode1.ChildNodes.Add(allChildNodes[0]);
            parentNode1.Validating += (sender, e) => log.Add("Validating parent1.");
            parentNode1.Validated  += (sender, e) => log.Add("Validated parent1.");

            var parentNode2 = new ModelValidationNode(GetModelMetadata(), "parent2");

            parentNode2.ChildNodes.Add(allChildNodes[1]);
            parentNode2.ChildNodes.Add(allChildNodes[2]);
            parentNode2.Validating += (sender, e) => log.Add("Validating parent2.");
            parentNode2.Validated  += (sender, e) => log.Add("Validated parent2.");
            var context = CreateContext();

            // Act
            parentNode1.CombineWith(parentNode2);
            parentNode1.Validate(context);

            // Assert
            Assert.Equal(expected, log);
            Assert.Equal(allChildNodes, parentNode1.ChildNodes.ToArray());
        }
        public void Validate_ValidatesIfModelIsNull()
        {
            // Arrange
            var modelMetadata = GetModelMetadata(typeof(ValidateAllPropertiesModel));
            var node          = new ModelValidationNode(modelMetadata, "theKey");

            var context = CreateContext(modelMetadata);

            // Act
            node.Validate(context);

            // Assert
            var modelState = Assert.Single(context.ModelState);

            Assert.Equal("theKey", modelState.Key);
            Assert.Equal(ModelValidationState.Invalid, modelState.Value.ValidationState);

            var error = Assert.Single(modelState.Value.Errors);

            Assert.Equal("A value is required but was not present in the request.", error.ErrorMessage);
        }
示例#9
0
        public void Validate_SkipsValidationIfSuppressed()
        {
            // Arrange
            var log           = new List <string>();
            var model         = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var node          = new ModelValidationNode(modelMetadata, "theKey")
            {
                SuppressValidation = true
            };

            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated  += (sender, e) => log.Add("In OnValidated()");
            var context = CreateContext();

            // Act
            node.Validate(context);

            // Assert
            Assert.Empty(log);
        }
示例#10
0
        public void Validate_SkipsValidationIfHandlerCancels()
        {
            // Arrange
            var log           = new List <string>();
            var model         = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var node          = new ModelValidationNode(modelMetadata, "theKey");

            node.Validating += (sender, e) =>
            {
                log.Add("In OnValidating()");
                e.Cancel = true;
            };
            node.Validated += (sender, e) => log.Add("In OnValidated()");
            var context = CreateContext(modelMetadata);

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(new[] { "In OnValidating()" }, log.ToArray());
        }
示例#11
0
        public void CombineWith()
        {
            // Arrange
            var expected = new[]
            {
                "Validating parent1.",
                "Validating parent2.",
                "Validated parent1.",
                "Validated parent2."
            };
            var log = new List<string>();

            var allChildNodes = new[]
            {
                new ModelValidationNode(GetModelMetadata(), "key1"),
                new ModelValidationNode(GetModelMetadata(), "key2"),
                new ModelValidationNode(GetModelMetadata(), "key3"),
            };

            var parentNode1 = new ModelValidationNode(GetModelMetadata(), "parent1");
            parentNode1.ChildNodes.Add(allChildNodes[0]);
            parentNode1.Validating += (sender, e) => log.Add("Validating parent1.");
            parentNode1.Validated += (sender, e) => log.Add("Validated parent1.");

            var parentNode2 = new ModelValidationNode(GetModelMetadata(), "parent2");
            parentNode2.ChildNodes.Add(allChildNodes[1]);
            parentNode2.ChildNodes.Add(allChildNodes[2]);
            parentNode2.Validating += (sender, e) => log.Add("Validating parent2.");
            parentNode2.Validated += (sender, e) => log.Add("Validated parent2.");
            var context = CreateContext();

            // Act
            parentNode1.CombineWith(parentNode2);
            parentNode1.Validate(context);

            // Assert
            Assert.Equal(expected, log);
            Assert.Equal(allChildNodes, parentNode1.ChildNodes.ToArray());
        }
示例#12
0
        public void Validate_Ordering()
        {
            // Proper order of invocation:
            // 1. OnValidating()
            // 2. Child validators
            // 3. This validator
            // 4. OnValidated()

            // Arrange
            var expected = new[]
            {
                "In OnValidating()",
                "In LoggingValidatonAttribute.IsValid()",
                "In IValidatableObject.Validate()",
                "In OnValidated()"
            };
            var log = new List<string>();
            var model = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var provider = new EmptyModelMetadataProvider();
            var childMetadata = provider.GetMetadataForProperty(() => model, model.GetType(), "ValidStringProperty");
            var node = new ModelValidationNode(modelMetadata, "theKey");
            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated += (sender, e) => log.Add("In OnValidated()");
            node.ChildNodes.Add(new ModelValidationNode(childMetadata, "theKey.ValidStringProperty"));
            var context = CreateContext(modelMetadata);

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(expected, log);
        }
示例#13
0
        public void Validate_SkipsValidationIfHandlerCancels()
        {
            // Arrange
            var log = new List<string>();
            var model = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var node = new ModelValidationNode(modelMetadata, "theKey");
            node.Validating += (sender, e) =>
            {
                log.Add("In OnValidating()");
                e.Cancel = true;
            };
            node.Validated += (sender, e) => log.Add("In OnValidated()");
            var context = CreateContext(modelMetadata);

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(new[] { "In OnValidating()" }, log.ToArray());
        }
示例#14
0
        public void Validate_SkipsValidationIfSuppressed()
        {
            // Arrange
            var log = new List<string>();
            var model = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var node = new ModelValidationNode(modelMetadata, "theKey")
            {
                SuppressValidation = true
            };

            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated += (sender, e) => log.Add("In OnValidated()");
            var context = CreateContext();

            // Act
            node.Validate(context);

            // Assert
            Assert.Empty(log);
        }
示例#15
0
        public void Validate_ValidateAllProperties_AddsValidationErrors()
        {
            // Arrange
            var model = new ValidateAllPropertiesModel
            {
                RequiredString = null /* error */,
                RangedInt = 0 /* error */,
                ValidString = "dog"
            };

            var modelMetadata = GetModelMetadata(model);
            var node = new ModelValidationNode(modelMetadata, "theKey")
            {
                ValidateAllProperties = true
            };
            var context = CreateContext(modelMetadata);
            context.ModelState.AddModelError("theKey.RequiredString.Dummy", "existing Error Text");

            // Act
            node.Validate(context);

            // Assert
            Assert.False(context.ModelState.ContainsKey("theKey.RequiredString"));
            Assert.Equal("existing Error Text",
                         context.ModelState["theKey.RequiredString.Dummy"].Errors[0].ErrorMessage);
            Assert.Equal("The field RangedInt must be between 10 and 30.",
                         context.ModelState["theKey.RangedInt"].Errors[0].ErrorMessage);
            Assert.False(context.ModelState.ContainsKey("theKey.ValidString"));
            Assert.False(context.ModelState.ContainsKey("theKey"));
        }
示例#16
0
        public void SetProperty_PropertyIsSettable_CallsSetter()
        {
            // Arrange
            var model = new Person();
            var bindingContext = CreateContext(GetMetadataForObject(model));

            var propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "DateOfBirth");
            var validationNode = new ModelValidationNode(propertyMetadata, "foo");
            var dtoResult = new ComplexModelDtoResult(new DateTime(2001, 1, 1), validationNode);
            var requiredValidator = bindingContext.ValidatorProviders
                                                  .SelectMany(v => v.GetValidators(propertyMetadata))
                                                  .Where(v => v.IsRequired)
                                                  .FirstOrDefault();
            var validationContext = new ModelValidationContext(bindingContext, propertyMetadata);

            var testableBinder = new TestableMutableObjectModelBinder();

            // Act
            testableBinder.SetPropertyPublic(bindingContext, propertyMetadata, dtoResult, requiredValidator);

            // Assert
            validationNode.Validate(validationContext);
            Assert.Equal(true, bindingContext.ModelState.IsValid);
            Assert.Equal(new DateTime(2001, 1, 1), model.DateOfBirth);
        }
示例#17
0
        public void Validate_SkipsRemainingValidationIfModelStateIsInvalid()
        {
            // Because a property validator fails, the model validator shouldn't run

            // Arrange
            var expected = new[]
            {
                "In OnValidating()",
                "In IValidatableObject.Validate()",
                "In OnValidated()"
            };
            var log = new List<string>();
            var model = new LoggingValidatableObject(log);
            var modelMetadata = GetModelMetadata(model);
            var provider = new EmptyModelMetadataProvider();
            var childMetadata = provider.GetMetadataForProperty(() => model,
                                                                model.GetType(),
                                                                "InvalidStringProperty");
            var node = new ModelValidationNode(modelMetadata, "theKey");
            node.ChildNodes.Add(new ModelValidationNode(childMetadata, "theKey.InvalidStringProperty"));
            node.Validating += (sender, e) => log.Add("In OnValidating()");
            node.Validated += (sender, e) => log.Add("In OnValidated()");
            var context = CreateContext(modelMetadata);

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(expected, log);
            Assert.Equal("Sample error message",
                         context.ModelState["theKey.InvalidStringProperty"].Errors[0].ErrorMessage);
        }
示例#18
0
        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorNotPresent_RegistersValidationCallback()
        {
            // Arrange
            var bindingContext = CreateContext(GetMetadataForObject(new Person()));
            var propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "DateOfBirth");
            var validationNode = new ModelValidationNode(propertyMetadata, "foo");
            var dtoResult = new ComplexModelDtoResult(model: null, validationNode: validationNode);
            var requiredValidator = GetRequiredValidator(bindingContext, propertyMetadata);
            var validationContext = new ModelValidationContext(bindingContext, propertyMetadata);

            var testableBinder = new TestableMutableObjectModelBinder();

            // Act
            testableBinder.SetPropertyPublic(bindingContext, propertyMetadata, dtoResult, requiredValidator);

            // Assert
            Assert.Equal(true, bindingContext.ModelState.IsValid);
            validationNode.Validate(validationContext, bindingContext.ValidationNode);
            Assert.Equal(false, bindingContext.ModelState.IsValid);
        }