예제 #1
0
        public void Constructor_FindsBinderTypeProviders_FirstAttributeHasPrecedence()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();

            var binderProviders = new[]
            {
                new TestBinderTypeProvider()
                {
                    BinderType = typeof(int)
                },
                new TestBinderTypeProvider()
                {
                    BinderType = typeof(string)
                }
            };

            // Act
            var metadata = new CachedDataAnnotationsModelMetadata(
                provider,
                containerType: null,
                modelType: typeof(object),
                propertyName: null,
                attributes: binderProviders);

            // Assert
            Assert.Same(typeof(int), metadata.BinderType);
        }
        public void ClientRulesWithMaxLengthAttributeAndCustomMessage()
        {
            // Arrange
            var propertyName = "Length";
            var message      = "{0} must be at most {1}";
            var provider     = new DataAnnotationsModelMetadataProvider();
            var metadata     = provider.GetMetadataForProperty(() => null, typeof(string), propertyName);
            var attribute    = new MaxLengthAttribute(5)
            {
                ErrorMessage = message
            };
            var adapter = new MaxLengthAttributeAdapter(attribute);
            var context = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("maxlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(5, rule.ValidationParameters["max"]);
            Assert.Equal("Length must be at most 5", rule.ErrorMessage);
        }
예제 #3
0
        public void GetClientValidationRules_WithMinAndMaxLength_ReturnsValidationParameters()
        {
            // Arrange
            var provider  = new DataAnnotationsModelMetadataProvider();
            var metadata  = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new StringLengthAttribute(10)
            {
                MinimumLength = 3
            };
            var adapter = new StringLengthAttributeAdapter(attribute);
            var context = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("length", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(3, rule.ValidationParameters["min"]);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal("The field Length must be a string with a minimum length of 3 and a maximum length of 10.",
                         rule.ErrorMessage);
        }
        public void Constructor_DefersDefaultsToBaseModelMetadata()
        {
            // Arrange
            var attributes = Enumerable.Empty <Attribute>();
            var provider   = new DataAnnotationsModelMetadataProvider();

            // Act
            var metadata = new CachedDataAnnotationsModelMetadata(
                provider,
                containerType: null,
                modelType: typeof(object),
                propertyName: null,
                attributes: attributes);

            // Assert
            Assert.True(metadata.ConvertEmptyStringToNull);
            Assert.False(metadata.HasNonDefaultEditFormat);
            Assert.False(metadata.HideSurroundingHtml);
            Assert.True(metadata.IsComplexType);
            Assert.False(metadata.IsReadOnly);
            Assert.False(metadata.IsRequired);
            Assert.True(metadata.ShowForDisplay);
            Assert.True(metadata.ShowForEdit);

            Assert.Null(metadata.DataTypeName);
            Assert.Null(metadata.Description);
            Assert.Null(metadata.DisplayFormatString);
            Assert.Null(metadata.DisplayName);
            Assert.Null(metadata.EditFormatString);
            Assert.Null(metadata.NullDisplayText);
            Assert.Null(metadata.SimpleDisplayText);
            Assert.Null(metadata.TemplateHint);

            Assert.Equal(ModelMetadata.DefaultOrder, metadata.Order);
        }
예제 #5
0
        public void ClientRulesWithCompareAttribute_ErrorMessageUsesResourceOverride()
        {
            if (TestPlatformHelper.IsMono)
            {
                // ValidationAttribute in Mono does not read non-public resx properties.
                return;
            }

            // Arrange
            var metadataProvider = new DataAnnotationsModelMetadataProvider();
            var metadata         = metadataProvider.GetMetadataForProperty(() => null, typeof(PropertyNameModel), "MyProperty");
            var attribute        = new CompareAttribute("OtherProperty")
            {
                ErrorMessageResourceName = "CompareAttributeTestResource",
                ErrorMessageResourceType = typeof(Test.Resources),
            };
            var context = new ClientModelValidationContext(metadata, metadataProvider);
            var adapter = new CompareAttributeAdapter(attribute);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("Comparing MyProperty to OtherProperty.", rule.ErrorMessage);
        }
예제 #6
0
        public void DataAnnotationsModelMetadataProvider_UsesPredicateOnType()
        {
            // Arrange
            var type = typeof(User);

            var provider = new DataAnnotationsModelMetadataProvider();
            var context  = new ModelBindingContext();

            var expected = new[] { "IsAdmin", "UserName" };

            // Act
            var metadata = provider.GetMetadataForType(null, type);

            // Assert
            var predicate = metadata.PropertyBindingPredicateProvider.PropertyFilter;

            var matched = new HashSet <string>();

            foreach (var property in metadata.Properties)
            {
                if (predicate(context, property.PropertyName))
                {
                    matched.Add(property.PropertyName);
                }
            }

            Assert.Equal <string>(expected, matched);
        }
예제 #7
0
 // Constructor for creating the prototype instances of the metadata class
 protected CachedModelMetadata(DataAnnotationsModelMetadataProvider provider,
                               Type containerType,
                               Type modelType,
                               string propertyName,
                               TPrototypeCache prototypeCache)
     : base(provider, containerType, modelAccessor: null, modelType: modelType, propertyName: propertyName)
 {
     PrototypeCache = prototypeCache;
 }
예제 #8
0
        private static ModelMetadata GetMetadataForParameter(MethodInfo methodInfo, string parameterName)
        {
            var metadataProvider = new DataAnnotationsModelMetadataProvider();

            return(metadataProvider.GetMetadataForParameter(
                       modelAccessor: null,
                       methodInfo: methodInfo,
                       parameterName: parameterName,
                       binderMetadata: null));
        }
        public void DataAnnotationsModelMetadataProvider_ReadsScaffoldColumnAttribute_ForShowForEdit()
        {
            // Arrange
            var type     = typeof(ScaffoldColumnModel);
            var provider = new DataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.True(provider.GetMetadataForProperty(null, type, "NoAttribute").ShowForEdit);
            Assert.True(provider.GetMetadataForProperty(null, type, "ScaffoldColumnTrue").ShowForEdit);
            Assert.False(provider.GetMetadataForProperty(null, type, "ScaffoldColumnFalse").ShowForEdit);
        }
예제 #10
0
        public void DataAnnotationsModelMetadataProvider_ReadsModelNameProperty_ForTypes()
        {
            // Arrange
            var type     = typeof(User);
            var provider = new DataAnnotationsModelMetadataProvider();

            // Act
            var metadata = provider.GetMetadataForType(null, type);

            // Assert
            Assert.Equal("TypePrefix", metadata.BinderModelName);
        }
예제 #11
0
 public CachedDataAnnotationsModelMetadata(DataAnnotationsModelMetadataProvider provider,
                                           Type containerType,
                                           Type modelType,
                                           string propertyName,
                                           IEnumerable <Attribute> attributes)
     : base(provider,
            containerType,
            modelType,
            propertyName,
            new CachedDataAnnotationsMetadataAttributes(attributes))
 {
 }
예제 #12
0
        public void DataAnnotationsModelMetadataProvider_ReadsModelNameProperty_ForTypes()
        {
            // Arrange
            var type     = typeof(TypeWithExludedAndIncludedPropertiesUsingBindAttribute);
            var provider = new DataAnnotationsModelMetadataProvider();

            // Act
            var metadata = provider.GetMetadataForType(null, type);

            // Assert
            Assert.Equal("TypePrefix", metadata.ModelName);
        }
        // TODO #1000; enable test once we detect attributes on the property's type
        public void HiddenInputWorksOnPropertyType()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();
            var metadata = provider.GetMetadataForType(modelAccessor: null, modelType: typeof(ClassWithHiddenProperties));
            var property = metadata.Properties.First(m => string.Equals("OfHiddenType", m.PropertyName));

            // Act
            var result = property.HideSurroundingHtml;

            // Assert
            Assert.True(result);
        }
예제 #14
0
        public void GetMetadataForProperty_WithBinderMetadataOnPropertyAndType_GetsMetadataFromProperty()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();

            // Act
            var propertyMetadata = provider.GetMetadataForProperty(null, typeof(Person), nameof(Person.GrandParent));

            // Assert
            Assert.NotNull(propertyMetadata.BinderMetadata);
            var attribute = Assert.IsType <NonTypeBasedBinderAttribute>(propertyMetadata.BinderMetadata);

            Assert.Equal("GrandParentProperty", propertyMetadata.BinderModelName);
        }
예제 #15
0
        public void GetMetadataForProperty_WithNoBinderMetadata_GetsItFromType()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();

            // Act
            var propertyMetadata = provider.GetMetadataForProperty(null, typeof(Person), nameof(Person.Parent));

            // Assert
            Assert.NotNull(propertyMetadata.BinderMetadata);
            var attribute = Assert.IsType <TypeBasedBinderAttribute>(propertyMetadata.BinderMetadata);

            Assert.Equal("PersonType", propertyMetadata.BinderModelName);
        }
예제 #16
0
        public void DataAnnotationsModelMetadataProvider_ReadsIncludedAndExcludedProperties_ForTypes()
        {
            // Arrange
            var type     = typeof(TypeWithExludedAndIncludedPropertiesUsingBindAttribute);
            var provider = new DataAnnotationsModelMetadataProvider();
            var expectedIncludedPropertyNames = new[] { "IncludedAndExcludedExplicitly1", "IncludedExplicitly1" };
            var expectedExcludedPropertyNames = new[] { "IncludedAndExcludedExplicitly1", "ExcludedExplicitly1" };

            // Act
            var metadata = provider.GetMetadataForType(null, type);

            // Assert
            Assert.Equal(expectedIncludedPropertyNames.ToList(), metadata.IncludedProperties);
            Assert.Equal(expectedExcludedPropertyNames.ToList(), metadata.ExcludedProperties);
        }
예제 #17
0
        private void DisplayFormatString_DoesNotAffectEditFormat()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();
            var metadata = new CachedDataAnnotationsModelMetadata(
                provider,
                containerType: null,
                modelType: typeof(object),
                propertyName: null,
                attributes: Enumerable.Empty <Attribute>());

            // Act
            metadata.DisplayFormatString = "custom format";

            // Assert
            Assert.Null(metadata.EditFormatString);
        }
예제 #18
0
        public void ModelMetadataProvider_ReadsPrefixProperty_OnlyAtParameterLevel_ForParameters()
        {
            // Arrange
            var type       = typeof(TypeWithExludedAndIncludedPropertiesUsingBindAttribute);
            var methodInfo = type.GetMethod("ActionWithBindAttribute");
            var provider   = new DataAnnotationsModelMetadataProvider();

            // Act
            var metadata = provider.GetMetadataForParameter(
                modelAccessor: null,
                methodInfo: methodInfo,
                parameterName: "param",
                binderMetadata: null);

            // Assert
            Assert.Equal("ParameterPrefix", metadata.ModelName);
        }
예제 #19
0
        public void GetMetadataForParameter_WithBinderDataOnParameterAndType_GetsMetadataFromParameter()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();

            // Act
            var parameterMetadata = provider.GetMetadataForParameter(
                null,
                typeof(Person).GetMethod("Save"),
                "person");

            // Assert
            Assert.NotNull(parameterMetadata.BinderMetadata);
            var attribute = Assert.IsType <NonTypeBasedBinderAttribute>(parameterMetadata.BinderMetadata);

            Assert.Equal("PersonParameter", parameterMetadata.BinderModelName);
        }
예제 #20
0
        public void ClientRulesWithCompareAttribute_ErrorMessageUsesPropertyName()
        {
            // Arrange
            var metadataProvider = new DataAnnotationsModelMetadataProvider();
            var metadata         = metadataProvider.GetMetadataForProperty(() => null, typeof(PropertyNameModel), "MyProperty");
            var attribute        = new CompareAttribute("OtherProperty");
            var context          = new ClientModelValidationContext(metadata, metadataProvider);
            var adapter          = new CompareAttributeAdapter(attribute);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("'MyProperty' and 'OtherProperty' do not match.", rule.ErrorMessage);
        }
예제 #21
0
        public void Constructor_FindsBinderTypeProviders_Null()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();

            var binderProviders = new[] { new TestBinderTypeProvider(), new TestBinderTypeProvider() };

            // Act
            var metadata = new CachedDataAnnotationsModelMetadata(
                provider,
                containerType: null,
                modelType: typeof(object),
                propertyName: null,
                attributes: binderProviders);

            // Assert
            Assert.Null(metadata.BinderType);
        }
예제 #22
0
        public void BinderMetadataIfPresent_Overrides_DefaultBinderMetadata()
        {
            // Arrange
            var firstBinderMetadata  = new TestBinderMetadata();
            var secondBinderMetadata = new TestBinderMetadata();
            var provider             = new DataAnnotationsModelMetadataProvider();
            var metadata             = new CachedDataAnnotationsModelMetadata(
                provider,
                containerType: null,
                modelType: typeof(object),
                propertyName: null,
                attributes: new object[] { firstBinderMetadata, secondBinderMetadata });

            // Act
            var result = metadata.BinderMetadata;

            // Assert
            Assert.Same(firstBinderMetadata, result);
        }
예제 #23
0
        public void GetClientValidationRules_ReturnsValidationParameters()
        {
            // Arrange
            var provider  = new DataAnnotationsModelMetadataProvider();
            var metadata  = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new RequiredAttribute();
            var adapter   = new RequiredAttributeAdapter(attribute);
            var context   = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("required", rule.ValidationType);
            Assert.Empty(rule.ValidationParameters);
            Assert.Equal("The Length field is required.", rule.ErrorMessage);
        }
예제 #24
0
        public void DataAnnotationsModelMetadataProvider_ReadsModelNameProperty_ForParameters()
        {
            // Arrange
            var type       = GetType();
            var methodInfo = type.GetMethod(
                "ActionWithBindAttribute",
                BindingFlags.Instance | BindingFlags.NonPublic);

            var provider = new DataAnnotationsModelMetadataProvider();

            // Act
            var metadata = provider.GetMetadataForParameter(
                modelAccessor: null,
                methodInfo: methodInfo,
                parameterName: "param");

            // Assert
            Assert.Equal("ParameterPrefix", metadata.BinderModelName);
        }
예제 #25
0
        public void ClientRulesWithMinLengthAttribute()
        {
            // Arrange
            var provider  = new DataAnnotationsModelMetadataProvider();
            var metadata  = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new MinLengthAttribute(6);
            var adapter   = new MinLengthAttributeAdapter(attribute);
            var context   = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("minlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(6, rule.ValidationParameters["min"]);
            Assert.Equal("The field Length must be a string or array type with a minimum length of '6'.", rule.ErrorMessage);
        }
        public void ClientRulesWithMaxLengthAttribute()
        {
            // Arrange
            var provider  = new DataAnnotationsModelMetadataProvider();
            var metadata  = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new MaxLengthAttribute(10);
            var adapter   = new MaxLengthAttributeAdapter(attribute);
            var context   = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("maxlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage);
        }
예제 #27
0
        public void DataTypeName_Null_IfHtmlEncodeTrue()
        {
            // Arrange
            var displayFormat = new DisplayFormatAttribute {
                HtmlEncode = true,
            };
            var provider = new DataAnnotationsModelMetadataProvider();
            var metadata = new CachedDataAnnotationsModelMetadata(
                provider,
                containerType: null,
                modelType: typeof(object),
                propertyName: null,
                attributes: new Attribute[] { displayFormat });

            // Act
            var result = metadata.DataTypeName;

            // Assert
            Assert.Null(result);
        }
예제 #28
0
        public void GetClientValidationRules_ReturnsValidationParameters()
        {
            // Arrange
            var provider  = new DataAnnotationsModelMetadataProvider();
            var metadata  = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new RangeAttribute(typeof(decimal), "0", "100");
            var adapter   = new RangeAttributeAdapter(attribute);
            var context   = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("range", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(0m, rule.ValidationParameters["min"]);
            Assert.Equal(100m, rule.ValidationParameters["max"]);
            Assert.Equal(@"The field Length must be between 0 and 100.", rule.ErrorMessage);
        }
        public CachedDataAnnotationsModelMetadata(DataAnnotationsModelMetadataProvider provider,
                                                  Type containerType,
                                                  Type modelType,
                                                  string propertyName,
                                                  IEnumerable <Attribute> attributes)
            : base(provider,
                   containerType,
                   modelType,
                   propertyName,
                   new CachedDataAnnotationsMetadataAttributes(attributes))
        {
            BinderMetadata = attributes.OfType <IBinderMetadata>().FirstOrDefault();

            var modelNameProvider = attributes.OfType <IModelNameProvider>().FirstOrDefault();

            ModelName = modelNameProvider?.Name;

            var bindAttribute = attributes.OfType <BindAttribute>().FirstOrDefault();

            ReadSettingsFromBindAttribute(bindAttribute);
        }
예제 #30
0
        public void AttributesOverrideMetadataBooleans(
            Attribute attribute,
            Func <ModelMetadata, bool> accessor,
            bool expectedResult)
        {
            // Arrange
            var attributes = new[] { attribute };
            var provider   = new DataAnnotationsModelMetadataProvider();
            var metadata   = new CachedDataAnnotationsModelMetadata(
                provider,
                containerType: null,
                modelType: typeof(object),
                propertyName: null,
                attributes: attributes);

            // Act
            var result = accessor(metadata);

            // Assert
            Assert.Equal(expectedResult, result);
        }