public void Validate_SetsMemberName_OnValidationContext_ForProperties(
            ModelMetadata metadata,
            object container,
            object model,
            string expectedMemberName)
        {
            // Arrange
            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Callback((object o, ValidationContext context) =>
                     {
                         Assert.Equal(expectedMemberName, context.MemberName);
                     })
                     .Returns(ValidationResult.Success)
                     .Verifiable();
            var validator = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer: null);
            var validationContext = new ModelValidationContext()
            {
                Metadata = metadata,
                Container = container,
                Model = model,
            };

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            Assert.Empty(results);
            attribute.VerifyAll();
        }
        public void Validate_SetsMemberName_OnValidationContext_ForProperties(
            ModelMetadata metadata,
            object container,
            object model,
            string expectedMemberName)
        {
            // Arrange
            var attribute = new Mock<TestableValidationAttribute> { CallBase = true };
            attribute
                .Setup(p => p.IsValidPublic(It.IsAny<object>(), It.IsAny<ValidationContext>()))
                .Callback((object o, ValidationContext context) =>
                {
                    Assert.Equal(expectedMemberName, context.MemberName);
                })
                .Returns(ValidationResult.Success)
                .Verifiable();
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            Assert.Empty(results);
            attribute.VerifyAll();
        }
        public void Constructor_SetsAttribute()
        {
            // Arrange
            var attribute = new RequiredAttribute();

            // Act
            var validator = new DataAnnotationsModelValidator(attribute, stringLocalizer : null);

            // Assert
            Assert.Same(attribute, validator.Attribute);
        }
        public void ValuesSet()
        {
            // Arrange
            var attribute = new RequiredAttribute();

            // Act
            var validator = new DataAnnotationsModelValidator(attribute);

            // Assert
            Assert.Same(attribute, validator.Attribute);
        }
Пример #5
0
        public void GetValidators(ModelValidatorProviderContext context)
        {
            IStringLocalizer stringLocalizer = null;

            if (_stringLocalizerFactory != null && _options.Value.DataAnnotationLocalizerProvider != null)
            {
                stringLocalizer = _options.Value.DataAnnotationLocalizerProvider(
                    context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType,
                    _stringLocalizerFactory);
            }

            for (var i = 0; i < context.ValidatorMetadata.Count; i++)
            {
                var attribute = context.ValidatorMetadata[i] as ValidationAttribute;
                if (attribute == null)
                {
                    continue;
                }

                var validator = new DataAnnotationsModelValidator(
                    _validationAttributeAdapterProvider,
                    attribute,
                    stringLocalizer);

                // Inserts validators based on whether or not they are 'required'. We want to run
                // 'required' validators first so that we get the best possible error message.
                if (attribute is RequiredAttribute)
                {
                    context.Validators.Insert(0, validator);
                }
                else
                {
                    context.Validators.Add(validator);
                }
            }

            // Produce a validator if the type supports IValidatableObject
            if (typeof(IValidatableObject).IsAssignableFrom(context.ModelMetadata.ModelType))
            {
                context.Validators.Add(new ValidatableObjectAdapter());
            }
        }
        public void GetValidators(ModelValidatorProviderContext context)
        {
            IStringLocalizer stringLocalizer = null;
            if (_stringLocalizerFactory != null && _options.Value.DataAnnotationLocalizerProvider != null)
            {
                stringLocalizer = _options.Value.DataAnnotationLocalizerProvider(
                    context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType,
                    _stringLocalizerFactory);
            }

            for (var i = 0; i < context.ValidatorMetadata.Count; i++)
            {
                var attribute = context.ValidatorMetadata[i] as ValidationAttribute;
                if (attribute == null)
                {
                    continue;
                }

                var validator = new DataAnnotationsModelValidator(
                    _validationAttributeAdapterProvider,
                    attribute,
                    stringLocalizer);

                // Inserts validators based on whether or not they are 'required'. We want to run
                // 'required' validators first so that we get the best possible error message.
                if (attribute is RequiredAttribute)
                {
                    context.Validators.Insert(0, validator);
                }
                else
                {
                    context.Validators.Add(validator);
                }
            }

            // Produce a validator if the type supports IValidatableObject
            if (typeof(IValidatableObject).IsAssignableFrom(context.ModelMetadata.ModelType))
            {
                context.Validators.Add(new ValidatableObjectAdapter());
            }
        }
Пример #7
0
        public void GetClientValidationRules_ReturnsEmptyRuleSet()
        {
            // Arrange
            var attribute = new FileExtensionsAttribute();
            var validator = new DataAnnotationsModelValidator <FileExtensionsAttribute>(attribute);

            var metadata = _metadataProvider.GetMetadataForProperty(
                containerType: typeof(string),
                propertyName: nameof(string.Length));

            var serviceCollection = new ServiceCollection();
            var requestServices   = serviceCollection.BuildServiceProvider();

            var context = new ClientModelValidationContext(metadata, _metadataProvider, requestServices);

            // Act
            var results = validator.GetClientValidationRules(context);

            // Assert
            Assert.Empty(results);
        }
        public void ValidateWithIsValidTrue()
        {
            // Arrange
            var modelExplorer = _metadataProvider
                                .GetModelExplorerForType(typeof(string), "Hello")
                                .GetExplorerForProperty("Length");

            var attribute = new Mock <ValidationAttribute> {
                CallBase = true
            };

            attribute.Setup(a => a.IsValid(modelExplorer.Model)).Returns(true);

            var validator         = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            Assert.Empty(result);
        }
        public void ValidatateWithValidationResultSuccess()
        {
            // Arrange
            var modelExplorer = _metadataProvider
                                .GetModelExplorerForType(typeof(string), "Hello")
                                .GetExplorerForProperty("Length");

            var attribute = new Mock <ValidationAttribute> {
                CallBase = true
            };

            attribute.Protected()
            .Setup <ValidationResult>("IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>())
            .Returns(ValidationResult.Success);
            var validator         = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            Assert.Empty(result);
        }
Пример #10
0
        public void Validate_ReturnsSingleValidationResult_IfMemberNameSequenceIsEmpty()
        {
            // Arrange
            const string errorMessage = "Some error message";

            var metadata  = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model     = container.Length;

            var attribute = new Mock <TestableValidationAttribute> {
                CallBase = true
            };

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Returns(new ValidationResult(errorMessage, memberNames: null));
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);

            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            var validationResult = Assert.Single(results);

            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Empty(validationResult.MemberName);
        }
Пример #11
0
        public void Validate_SetsMemberName_OnValidationContext_ForProperties(
            ModelMetadata metadata,
            object container,
            object model,
            string expectedMemberName)
        {
            // Arrange
            var attribute = new Mock <TestableValidationAttribute> {
                CallBase = true
            };

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Callback((object o, ValidationContext context) =>
            {
                Assert.Equal(expectedMemberName, context.MemberName);
            })
            .Returns(ValidationResult.Success)
            .Verifiable();
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            Assert.Empty(results);
            attribute.VerifyAll();
        }
Пример #12
0
        public void Validate_IsValidFalse_StringLocalizerReturnsLocalizerErrorMessage()
        {
            // Arrange
            var metadata  = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model     = container.Length;

            var attribute = new Mock <ValidationAttribute> {
                CallBase = true
            };

            attribute.Setup(a => a.IsValid(model)).Returns(false);

            attribute.Object.ErrorMessage = "Length";

            var localizedString = new LocalizedString("Length", "Longueur est invalide");
            var stringLocalizer = new Mock <IStringLocalizer>();

            stringLocalizer.Setup(s => s["Length"]).Returns(localizedString);

            var validator         = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer.Object);
            var validationContext = new ModelValidationContext()
            {
                Metadata  = metadata,
                Container = container,
                Model     = model,
            };

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();

            Assert.Equal("", validationResult.MemberName);
            Assert.Equal("Longueur est invalide", validationResult.Message);
        }
        public void ValidateSetsMemberNamePropertyOfValidationContextForProperties(
            ModelExplorer modelExplorer,
            string expectedMemberName)
        {
            // Arrange
            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Callback((object o, ValidationContext context) =>
                     {
                         Assert.Equal(expectedMemberName, context.MemberName);
                     })
                     .Returns(ValidationResult.Success)
                     .Verifiable();
            var validator = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            Assert.Empty(results);
            attribute.VerifyAll();
        }
Пример #14
0
        public void Validate_ReturnsSingleValidationResult_IfOneMemberNameIsSpecified()
        {
            // Arrange
            const string errorMessage = "A different error message";

            var metadata = _metadataProvider.GetMetadataForType(typeof(object));
            var model    = new object();

            var attribute = new Mock <TestableValidationAttribute> {
                CallBase = true
            };

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Returns(new ValidationResult(errorMessage, new[] { "FirstName" }));

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);

            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Equal("FirstName", validationResult.MemberName);
        }
        public void ValidateReturnsMemberNameIfItIsDifferentFromDisplayName()
        {
            // Arrange
            var modelExplorer = _metadataProvider.GetModelExplorerForType(typeof(SampleModel), new SampleModel());

            var attribute = new Mock <ValidationAttribute> {
                CallBase = true
            };

            attribute.Protected()
            .Setup <ValidationResult>("IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>())
            .Returns(new ValidationResult("Name error", new[] { "Name" }));

            var validator         = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);

            Assert.Equal("Name", validationResult.MemberName);
        }
        public void Validate_Valid()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model = container.Length;

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Setup(a => a.IsValid(model)).Returns(true);

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: model);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            Assert.Empty(result);
        }
        public void ValidateReturnsMemberNameIfItIsDifferentFromDisplayName()
        {
            // Arrange
            var modelExplorer = _metadataProvider.GetModelExplorerForType(typeof(SampleModel), new SampleModel());

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Returns(new ValidationResult("Name error", new[] { "Name" }));

            var validator = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);
            Assert.Equal("Name", validationResult.MemberName);
        }
        public void ValidateReturnsSingleValidationResultIfOneMemberNameIsSpecified()
        {
            // Arrange
            const string errorMessage = "A different error message";

            var modelExplorer = _metadataProvider.GetModelExplorerForType(typeof(object), new object());

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Returns(new ValidationResult(errorMessage, new[] { "FirstName" }));

            var validator = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);
            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Equal("FirstName", validationResult.MemberName);
        }
        public void ValidateReturnsSingleValidationResultIfMemberNameSequenceIsEmpty()
        {
            // Arrange
            const string errorMessage = "Some error message";

            var modelExplorer = _metadataProvider
                .GetModelExplorerForType(typeof(string), "Hello")
                .GetExplorerForProperty("Length");

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Returns(new ValidationResult(errorMessage, memberNames: null));
            var validator = new DataAnnotationsModelValidator(attribute.Object);

            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);
            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Empty(validationResult.MemberName);
        }
        public void ValidatateWithValidationResultSuccess()
        {
            // Arrange
            var modelExplorer = _metadataProvider
                .GetModelExplorerForType(typeof(string), "Hello")
                .GetExplorerForProperty("Length");

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Returns(ValidationResult.Success);
            var validator = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            Assert.Empty(result);
        }
        public void ValidateWithIsValidFalse()
        {
            // Arrange
            var modelExplorer = _metadataProvider
                .GetModelExplorerForType(typeof(string), "Hello")
                .GetExplorerForProperty("Length");

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Setup(a => a.IsValid(modelExplorer.Model)).Returns(false);

            var validator = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();
            Assert.Equal("", validationResult.MemberName);
            Assert.Equal(attribute.Object.FormatErrorMessage("Length"), validationResult.Message);
        }
        public void Validate_ReturnsSingleValidationResult_IfMemberNameSequenceIsEmpty()
        {
            // Arrange
            const string errorMessage = "Some error message";

            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model = container.Length;

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Returns(new ValidationResult(errorMessage, memberNames: null));
            var validator = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer: null);

            var validationContext = new ModelValidationContext()
            {
                Metadata = metadata,
                Container = container,
                Model = model,
            };

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            var validationResult = Assert.Single(results);
            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Empty(validationResult.MemberName);
        }
        public void ValidateWithIsValidTrue()
        {
            // Arrange
            var modelExplorer = _metadataProvider
                .GetModelExplorerForType(typeof(string), "Hello")
                .GetExplorerForProperty("Length");

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Setup(a => a.IsValid(modelExplorer.Model)).Returns(true);

            var validator = new DataAnnotationsModelValidator(attribute.Object);
            var validationContext = CreateValidationContext(modelExplorer);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            Assert.Empty(result);
        }
        public void Validatate_ValidationResultSuccess()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model = container.Length;

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Protected()
                     .Setup<ValidationResult>("IsValid", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())
                     .Returns(ValidationResult.Success);
            var validator = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer: null);
            var validationContext = new ModelValidationContext()
            {
                Metadata = metadata,
                Container = container,
                Model = model,
            };

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            Assert.Empty(result);
        }
        public void Validate_IsValidFalse_StringLocalizerGetsArguments(
            ValidationAttribute attribute,
            string model,
            object[] values)
        {
            // Arrange
            var stringLocalizer = new Mock<IStringLocalizer>();

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute,
                stringLocalizer.Object);

            var metadata = _metadataProvider.GetMetadataForType(typeof(SampleModel));
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: model);

            // Act
            validator.Validate(validationContext);

            // Assert
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(values) + " " + attribute.GetType().Name;

            stringLocalizer.Verify(l => l[LocalizationKey, values], json);
        }
        public void Validate_IsValidFalse_StringLocalizerReturnsLocalizerErrorMessage()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";

            var attribute = new MaxLengthAttribute(4);
            attribute.ErrorMessage = "{0} should have no more than {1} characters.";

            var localizedString = new LocalizedString(attribute.ErrorMessage, "Longueur est invalide : 4");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[attribute.ErrorMessage, It.IsAny<object[]>()]).Returns(localizedString);

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute,
                stringLocalizer.Object);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: "abcde");

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();
            Assert.Equal("", validationResult.MemberName);
            Assert.Equal("Longueur est invalide : 4", validationResult.Message);
        }
        public void GetClientValidationRules_WithIClientModelValidator_CallsAttribute()
        {
            // Arrange
            var attribute = new TestableAttribute();
            var validator = new DataAnnotationsModelValidator<TestableAttribute>(attribute);

            var metadata = _metadataProvider.GetMetadataForProperty(
                containerType: typeof(string),
                propertyName: nameof(string.Length));

            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();

            var context = new ClientModelValidationContext(metadata, _metadataProvider, requestServices);

            // Act
            var results = validator.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(results);
            Assert.Equal("an error", rule.ErrorMessage);
            Assert.Empty(rule.ValidationParameters);
            Assert.Equal("testable", rule.ValidationType);
        }
        public void Validate_ReturnsSingleValidationResult_IfMemberNameSequenceIsEmpty()
        {
            // Arrange
            const string errorMessage = "Some error message";

            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model = container.Length;

            var attribute = new Mock<TestableValidationAttribute> { CallBase = true };
            attribute
                 .Setup(p => p.IsValidPublic(It.IsAny<object>(), It.IsAny<ValidationContext>()))
                 .Returns(new ValidationResult(errorMessage, memberNames: null));
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);

            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            var validationResult = Assert.Single(results);
            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Empty(validationResult.MemberName);
        }
        public void Validate_Invalid()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForProperty(typeof(string), "Length");
            var container = "Hello";
            var model = container.Length;

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Setup(a => a.IsValid(model)).Returns(false);

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: model);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();
            Assert.Equal("", validationResult.MemberName);
            Assert.Equal(attribute.Object.FormatErrorMessage("Length"), validationResult.Message);
        }
        public void Validate_ReturnsSingleValidationResult_IfOneMemberNameIsSpecified()
        {
            // Arrange
            const string errorMessage = "A different error message";

            var metadata = _metadataProvider.GetMetadataForType(typeof(object));
            var model = new object();

            var attribute = new Mock<TestableValidationAttribute> { CallBase = true };
            attribute
                 .Setup(p => p.IsValidPublic(It.IsAny<object>(), It.IsAny<ValidationContext>()))
                 .Returns(new ValidationResult(errorMessage, new[] { "FirstName" }));

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);
            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Equal("FirstName", validationResult.MemberName);
        }
        public void Validate_IsValidFalse_StringLocalizerReturnsLocalizerErrorMessage()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(string));
            var container = "Hello";
            var model = container.Length;

            var attribute = new Mock<ValidationAttribute> { CallBase = true };
            attribute.Setup(a => a.IsValid(model)).Returns(false);

            attribute.Object.ErrorMessage = "Length";

            var localizedString = new LocalizedString("Length", "Longueur est invalide");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s["Length"]).Returns(localizedString);

            var validator = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer.Object);
            var validationContext = new ModelValidationContext()
            {
                Metadata = metadata,
                Container = container,
                Model = model,
            };

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();
            Assert.Equal("", validationResult.MemberName);
            Assert.Equal("Longueur est invalide", validationResult.Message);
        }
        public void Validate_ReturnsMemberName_IfItIsDifferentFromDisplayName()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(SampleModel));
            var model = new SampleModel();

            var attribute = new Mock<TestableValidationAttribute> { CallBase = true };
            attribute
                 .Setup(p => p.IsValidPublic(It.IsAny<object>(), It.IsAny<ValidationContext>()))
                 .Returns(new ValidationResult("Name error", new[] { "Name" }));

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);
            Assert.Equal("Name", validationResult.MemberName);
        }
        public void GetClientValidationRules_ReturnsEmptyRuleSet()
        {
            // Arrange
            var attribute = new FileExtensionsAttribute();
            var validator = new DataAnnotationsModelValidator<FileExtensionsAttribute>(attribute);

            var metadata = _metadataProvider.GetMetadataForProperty(
                containerType: typeof(string),
                propertyName: nameof(string.Length));

            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();

            var context = new ClientModelValidationContext(metadata, _metadataProvider, requestServices);

            // Act
            var results = validator.GetClientValidationRules(context);

            // Assert
            Assert.Empty(results);
        }