Esempio n. 1
0
        public void Validate_ValidateAllProperties_AddsValidationErrors()
        {
            // Arrange
            ValidateAllPropertiesModel model = new ValidateAllPropertiesModel
            {
                RequiredString = null /* error */,
                RangedInt      = 0 /* error */,
                ValidString    = "dog"
            };

            ModelMetadata       modelMetadata = GetModelMetadata(model);
            HttpActionContext   context       = ContextUtil.CreateActionContext();
            ModelValidationNode node          = new ModelValidationNode(modelMetadata, "theKey")
            {
                ValidateAllProperties = true
            };

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

            // Act
            node.Validate(context);

            // Assert
            Assert.Null(context.ModelState["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.Null(context.ModelState["theKey.ValidString"]);
            Assert.Null(context.ModelState["theKey"]);
        }
Esempio n. 2
0
        public void CombineWith()
        {
            // Arrange
            List <string> log = new List <string>();

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

            ModelValidationNode 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.");

            ModelValidationNode 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.");

            // Act
            parentNode1.CombineWith(parentNode2);
            parentNode1.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(new[] { "Validating parent1.", "Validating parent2.", "Validated parent1.", "Validated parent2." }, log.ToArray());
            Assert.Equal(allChildNodes, parentNode1.ChildNodes.ToArray());
        }
Esempio n. 3
0
        public void Validate_Ordering()
        {
            // Proper order of invocation:
            // 1. OnValidating()
            // 2. Child validators
            // 3. This validator
            // 4. OnValidated()

            // Arrange
            List <string>            log           = new List <string>();
            LoggingValidatableObject model         = new LoggingValidatableObject(log);
            ModelMetadata            modelMetadata = GetModelMetadata(model);
            ModelMetadata            childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), "ValidStringProperty");
            ModelValidationNode      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"));

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(new[] { "In OnValidating()", "In LoggingValidatonAttribute.IsValid()", "In IValidatableObject.Validate()", "In OnValidated()" }, log.ToArray());
        }
Esempio n. 4
0
        public void Validate_ThrowsIfControllerContextIsNull()
        {
            // Arrange
            ModelValidationNode node = new ModelValidationNode(GetModelMetadata(), "someKey");

            // Act & assert
            Assert.ThrowsArgumentNull(() => node.Validate(null), "actionContext");
        }
        private void ValidateChildren(HttpActionContext actionContext)
        {
            for (int i = 0; i < _childNodes.Count; i++)
            {
                ModelValidationNode child = _childNodes[i];
                child.Validate(actionContext, this);
            }

            if (ValidateAllProperties)
            {
                ValidateProperties(actionContext);
            }
        }
Esempio n. 6
0
        public void Validate_SkipsValidationIfSuppressed()
        {
            // Arrange
            List <string>            log           = new List <string>();
            LoggingValidatableObject model         = new LoggingValidatableObject(log);
            ModelMetadata            modelMetadata = GetModelMetadata(model);
            ModelValidationNode      node          = new ModelValidationNode(modelMetadata, "theKey")
            {
                SuppressValidation = true
            };

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

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Empty(log);
        }
Esempio n. 7
0
        public void Validate_SkipsValidationIfHandlerCancels()
        {
            // Arrange
            List <string>            log           = new List <string>();
            LoggingValidatableObject model         = new LoggingValidatableObject(log);
            ModelMetadata            modelMetadata = GetModelMetadata(model);
            ModelValidationNode      node          = new ModelValidationNode(modelMetadata, "theKey");

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

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(new[] { "In OnValidating()" }, log.ToArray());
        }
Esempio n. 8
0
        public void Validate_SkipsRemainingValidationIfModelStateIsInvalid()
        {
            // Because a property validator fails, the model validator shouldn't run

            // Arrange
            List <string>            log           = new List <string>();
            LoggingValidatableObject model         = new LoggingValidatableObject(log);
            ModelMetadata            modelMetadata = GetModelMetadata(model);
            ModelMetadata            childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(
                () => model,
                model.GetType(),
                "InvalidStringProperty"
                );
            ModelValidationNode 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()");
            HttpActionContext context = ContextUtil.CreateActionContext();

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(
                new[]
            {
                "In OnValidating()",
                "In IValidatableObject.Validate()",
                "In OnValidated()"
            },
                log.ToArray()
                );
            Assert.Equal(
                "Sample error message",
                context.ModelState["theKey.InvalidStringProperty"].Errors[0].ErrorMessage
                );
        }
        public void CombineWith()
        {
            // Arrange
            List<string> log = new List<string>();

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

            ModelValidationNode 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.");

            ModelValidationNode 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.");

            // Act
            parentNode1.CombineWith(parentNode2);
            parentNode1.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(new[] { "Validating parent1.", "Validating parent2.", "Validated parent1.", "Validated parent2." }, log.ToArray());
            Assert.Equal(allChildNodes, parentNode1.ChildNodes.ToArray());
        }
        public void Validate_ValidateAllProperties_AddsValidationErrors()
        {
            // Arrange
            ValidateAllPropertiesModel model = new ValidateAllPropertiesModel
            {
                RequiredString = null /* error */,
                RangedInt = 0 /* error */,
                ValidString = "dog"
            };

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

            // Act
            node.Validate(context);

            // Assert
            Assert.Null(context.ModelState["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.Null(context.ModelState["theKey.ValidString"]);
            Assert.Null(context.ModelState["theKey"]);
        }
        public void Validate_ThrowsIfControllerContextIsNull()
        {
            // Arrange
            ModelValidationNode node = new ModelValidationNode(GetModelMetadata(), "someKey");

            // Act & assert
            Assert.ThrowsArgumentNull(
                () => node.Validate(null),
                "actionContext");
        }
        public void Validate_SkipsValidationIfSuppressed()
        {
            // Arrange
            List<string> log = new List<string>();
            LoggingValidatableObject model = new LoggingValidatableObject(log);
            ModelMetadata modelMetadata = GetModelMetadata(model);
            ModelValidationNode node = new ModelValidationNode(modelMetadata, "theKey")
            {
                SuppressValidation = true
            };

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

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Empty(log);
        }
        public void Validate_SkipsValidationIfHandlerCancels()
        {
            // Arrange
            List<string> log = new List<string>();
            LoggingValidatableObject model = new LoggingValidatableObject(log);
            ModelMetadata modelMetadata = GetModelMetadata(model);
            ModelValidationNode node = new ModelValidationNode(modelMetadata, "theKey");
            node.Validating += (sender, e) =>
            {
                log.Add("In OnValidating()");
                e.Cancel = true;
            };
            node.Validated += (sender, e) => log.Add("In OnValidated()");

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(new[] { "In OnValidating()" }, log.ToArray());
        }
        public void Validate_SkipsRemainingValidationIfModelStateIsInvalid()
        {
            // Because a property validator fails, the model validator shouldn't run

            // Arrange
            List<string> log = new List<string>();
            LoggingValidatableObject model = new LoggingValidatableObject(log);
            ModelMetadata modelMetadata = GetModelMetadata(model);
            ModelMetadata childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), "InvalidStringProperty");
            ModelValidationNode 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()");
            HttpActionContext context = ContextUtil.CreateActionContext();

            // Act
            node.Validate(context);

            // Assert
            Assert.Equal(new[] { "In OnValidating()", "In IValidatableObject.Validate()", "In OnValidated()" }, log.ToArray());
            Assert.Equal("Sample error message", context.ModelState["theKey.InvalidStringProperty"].Errors[0].ErrorMessage);
        }
        public void SetProperty_PropertyIsSettable_CallsSetter()
        {
            // Arrange
            Person model = new Person();
            HttpActionContext context = ContextUtil.CreateActionContext();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = GetMetadataForObject(model)
            };

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

            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();

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

            // Assert
            validationNode.Validate(context);
            Assert.True(context.ModelState.IsValid);
            Assert.Equal(new DateTime(2001, 1, 1), model.DateOfBirth);
        }
        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorNotPresent_RegistersValidationCallback()
        {
            // Arrange
            HttpActionContext context = ContextUtil.CreateActionContext();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = GetMetadataForObject(new Person()),
            };

            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == "DateOfBirth");
            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, "foo");
            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);
            ModelValidator requiredValidator = context.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();

            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();

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

            // Assert
            Assert.True(context.ModelState.IsValid);
            validationNode.Validate(context, bindingContext.ValidationNode);
            Assert.False(context.ModelState.IsValid);
        }
        public void Validate_Ordering()
        {
            // Proper order of invocation:
            // 1. OnValidating()
            // 2. Child validators
            // 3. This validator
            // 4. OnValidated()

            // Arrange
            List<string> log = new List<string>();
            LoggingValidatableObject model = new LoggingValidatableObject(log);
            ModelMetadata modelMetadata = GetModelMetadata(model);
            ModelMetadata childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), "ValidStringProperty");
            ModelValidationNode 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"));

            // Act
            node.Validate(ContextUtil.CreateActionContext());

            // Assert
            Assert.Equal(new[] { "In OnValidating()", "In LoggingValidatonAttribute.IsValid()", "In IValidatableObject.Validate()", "In OnValidated()" }, log.ToArray());
        }