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.Empty(validationResult.MemberName);
            Assert.Equal("Longueur est invalide : 4", validationResult.Message);
        }
        public void Validate_ValidationResultSuccess()
        {
            // Arrange
            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(ValidationResult.Success);
            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 Valdate_ReturnsExpectedResults(
            string errorMessage,
            IEnumerable <string> memberNames,
            IEnumerable <ModelValidationResult> expectedResults)
        {
            // Arrange
            var metadata  = _metadataProvider.GetMetadataForProperty(typeof(string), nameof(string.Length));
            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));

            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.Equal(expectedResults, results, ModelValidationResultComparer.Instance);
        }
        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 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.Empty(validationResult.MemberName);
            Assert.Equal(attribute.Object.FormatErrorMessage("Length"), 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 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_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_CanUseRequestServices_WithinValidationAttribute()
        {
            // Arrange
            var service = new Mock <IExampleService>();

            service.Setup(x => x.DoSomething()).Verifiable();

            var provider = new ServiceCollection().AddSingleton(service.Object).BuildServiceProvider();

            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(x => x.RequestServices).Returns(provider);

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

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Callback((object o, ValidationContext context) =>
            {
                var receivedService = context.GetService <IExampleService>();
                Assert.Equal(service.Object, receivedService);
                receivedService.DoSomething();
            });

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

            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext
            {
                HttpContext = httpContext.Object
            },
                modelMetadata: _metadataProvider.GetMetadataForType(typeof(object)),
                metadataProvider: _metadataProvider,
                container: null,
                model: new object());

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

            // Assert
            service.Verify();
        }
예제 #11
0
        public void Validate_RequiredAndNotNullAtTopLevel_Valid()
        {
            // Arrange
            var metadata  = _metadataProvider.GetMetadataForProperty(typeof(string), "Length");
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                new RequiredAttribute(),
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: 123);

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

            // Assert
            Assert.Empty(result);
        }
예제 #12
0
        public void Validate_RequiredButNullAtTopLevel_Invalid()
        {
            // Arrange
            var metadata  = _metadataProvider.GetMetadataForProperty(typeof(string), "Length");
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                new RequiredAttribute(),
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: null);

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

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

            Assert.Empty(validationResult.MemberName);
            Assert.Equal(new RequiredAttribute().FormatErrorMessage("Length"), validationResult.Message);
        }