Beispiel #1
0
        public async Task KeyValuePairModelBinder_BindsKeyValuePairOfSimpleType_EmptyPrefix_Success()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(KeyValuePair <string, int>)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = new QueryString("?Key=key0&Value=10");
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType <KeyValuePair <string, int> >(modelBindingResult.Model);

            Assert.Equal(new KeyValuePair <string, int>("key0", 10), model);

            Assert.Equal(2, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);

            var entry = Assert.Single(modelState, kvp => kvp.Key == "Key").Value;

            Assert.Equal("key0", entry.AttemptedValue);
            Assert.Equal("key0", entry.RawValue);

            entry = Assert.Single(modelState, kvp => kvp.Key == "Value").Value;
            Assert.Equal("10", entry.AttemptedValue);
            Assert.Equal("10", entry.RawValue);
        }
        public async Task BinderTypeOnParameterType_WithDataEmptyPrefixAndVersion20_GetsBound(
            BindingInfo bindingInfo)
        {
            // Arrange
            var testContext = ModelBindingTestHelper.GetTestContext(
                // ParameterBinder will use ModelMetadata for typeof(Address), not Parameter1's ParameterInfo.
                updateOptions: options => options.AllowValidatingTopLevelNodes = false);

            var modelState      = testContext.ModelState;
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(testContext.HttpContext.RequestServices);
            var parameter       = new ParameterDescriptor
            {
                Name          = "Parameter1",
                BindingInfo   = bindingInfo,
                ParameterType = typeof(Address),
            };

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var address = Assert.IsType <Address>(modelBindingResult.Model);

            Assert.Equal("SomeStreet", address.Street);

            // ModelState
            Assert.True(modelState.IsValid);
            var kvp = Assert.Single(modelState);

            Assert.Equal("Street", kvp.Key);
            var entry = kvp.Value;

            Assert.NotNull(entry);
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.NotNull(entry.RawValue); // Value is set by test model binder, no need to validate it.
        }
Beispiel #3
0
        public async Task DictionaryModelBinder_BindsDictionaryOfComplexType_ExplicitPrefix_Success(
            string queryString)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "parameter",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "prefix",
                },
                ParameterType = typeof(Dictionary <string, Person>)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = new QueryString(queryString);
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType <Dictionary <string, Person> >(modelBindingResult.Model);

            Assert.Equal(new Dictionary <string, Person> {
                { "key0", new Person {
                      Id = 10
                  } },
            }, model);

            Assert.NotEmpty(modelState);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
        public async Task ArrayModelBinder_BindsArrayOfSimpleType_WithPrefix_Success()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(int[])
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = new QueryString("?parameter[0]=10&parameter[1]=11");
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType <int[]>(modelBindingResult.Model);

            Assert.Equal(new int[] { 10, 11 }, model);

            Assert.Equal(2, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);

            var entry = Assert.Single(modelState, kvp => kvp.Key == "parameter[0]").Value;

            Assert.Equal("10", entry.AttemptedValue);
            Assert.Equal("10", entry.RawValue);

            entry = Assert.Single(modelState, kvp => kvp.Key == "parameter[1]").Value;
            Assert.Equal("11", entry.AttemptedValue);
            Assert.Equal("11", entry.RawValue);
        }
        public async Task ModelMetadataTypeAttribute_InvalidClassAttributeOnBaseClassProduct_HasModelStateErrors()
        {
            // Arrange
            var input = "{ \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
                        "\"CompanyName\":\"Microsoft\", \"Country\":\"UK\",\"Version\":\"2\"," +
                        "\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }";
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BindingSource = BindingSource.Body
                },
                ParameterType = typeof(SoftwareViewModel)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(input));
                request.ContentType = "application/json";
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var boundPerson = Assert.IsType <SoftwareViewModel>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.False(modelState.IsValid);
            var modelStateErrors = CreateValidationDictionary(modelState);

            Assert.Single(modelStateErrors);
            Assert.Equal("Product must be made in the USA if it is not named.", modelStateErrors[""]);
        }
        public async Task FromBodyAllowingEmptyInputOnActionParameter_EmptyBody_BindsToNullValue()
        {
            // Arrange
            var parameter = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo
                {
                    BinderModelName = "CustomParameter",
                    BindingSource   = BindingSource.Body
                },
                ParameterType = typeof(Person)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(string.Empty));
                request.ContentType = "application/json";
            });

            var httpContext = testContext.HttpContext;
            var modelState  = testContext.ModelState;

            var optionsAccessor = testContext.GetService <IOptions <MvcOptions> >();

            optionsAccessor.Value.AllowEmptyInputInBodyModelBinding = true;

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(optionsAccessor.Value);

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            Assert.Null(modelBindingResult.Model);

            Assert.True(modelState.IsValid);
            Assert.Empty(modelState);
        }
        public async Task FromBodyOnParameterType_WithData_Succeeds(BindingInfo bindingInfo)
        {
            // Arrange
            var inputText        = "{ \"Street\" : \"someStreet\" }";
            var metadataProvider = new TestModelMetadataProvider();

            metadataProvider
            .ForType <Address6>()
            .BindingDetails(binding => binding.BindingSource = BindingSource.Body);

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(metadataProvider);
            var parameter       = new ParameterDescriptor
            {
                Name          = "parameter-name",
                BindingInfo   = bindingInfo,
                ParameterType = typeof(Address6),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(inputText));
                request.ContentType = "application/json";
            });

            testContext.MetadataProvider = metadataProvider;
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var address = Assert.IsType <Address6>(modelBindingResult.Model);

            Assert.Equal("someStreet", address.Street, StringComparer.Ordinal);

            Assert.True(modelState.IsValid);
            Assert.Empty(modelState);
        }
        public async Task BindModelAsync_WithBindProperty_EnforcesBindRequired(int?input, bool isValid)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = nameof(TestController.BindRequiredProp),
                ParameterType = typeof(string),
                BindingInfo   = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Method = "POST";

                if (input.HasValue)
                {
                    request.QueryString = new QueryString($"?{parameter.Name}={input.Value}");
                }
            });

            var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var modelMetadata         = modelMetadataProvider
                                        .GetMetadataForProperty(typeof(TestController), parameter.Name);

            // Act
            var result = await parameterBinder.BindModelAsync(
                parameter,
                testContext,
                modelMetadataProvider,
                modelMetadata);

            // Assert
            Assert.Equal(input.HasValue, result.IsModelSet);
            Assert.Equal(isValid, testContext.ModelState.IsValid);
            if (isValid)
            {
                Assert.Equal(input.Value, Assert.IsType <int>(result.Model));
            }
        }
        public async Task BindPropertyFromHeader_WithData_WithEmptyPrefix_GetsBound()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "Parameter1",
                BindingInfo   = new BindingInfo(),
                ParameterType = typeof(Person)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request => request.Headers.Add("Header", new[] { "someValue" }));
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <Person>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.NotNull(boundPerson.Address);
            Assert.Equal("someValue", boundPerson.Address.Street);

            // ModelState
            Assert.True(modelState.IsValid);
            var entry = Assert.Single(modelState);

            Assert.Equal("Address.Header", entry.Key);
            Assert.Empty(entry.Value.Errors);
            Assert.Equal(ModelValidationState.Valid, entry.Value.ValidationState);
            Assert.Equal("someValue", entry.Value.AttemptedValue);
            Assert.Equal(new string[] { "someValue" }, entry.Value.RawValue);
        }
        public async Task BindParameter_WithEmptyData_DoesNotBind(Type parameterType)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo(),

                ParameterType = parameterType
            };
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("Parameter1", "");
            });
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.False(modelBindingResult.IsModelSet);

            // Model
            Assert.Null(modelBindingResult.Model);

            // ModelState
            Assert.False(modelState.IsValid);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("Parameter1", key);
            Assert.Equal("", modelState[key].AttemptedValue);
            Assert.Equal("", modelState[key].RawValue);
            var error = Assert.Single(modelState[key].Errors);

            Assert.Equal("The value '' is invalid.", error.ErrorMessage, StringComparer.Ordinal);
            Assert.Null(error.Exception);
        }
        public async Task BindPropertyFromHeader_NoData_UsesFullPathAsKeyForModelStateErrors()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person)
            };

            // Do not add any headers.
            var testContext = ModelBindingTestHelper.GetTestContext();
            var modelState  = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <Person>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);

            // ModelState
            Assert.False(modelState.IsValid);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("CustomParameter.Address.Header", key);
            var error = Assert.Single(modelState[key].Errors);

            Assert.Equal(ValidationAttributeUtil.GetRequiredErrorMessage("Street"), error.ErrorMessage);
        }
        public async Task ModelMetadataTypeAttribute_InvalidComplexTypePropertyOnBaseClass_HasModelStateErrors()
        {
            // Arrange
            var input = "{ \"Contact\":\"4255678765\", \"Category\":\"Technology\"," +
                        "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21 }";
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BindingSource = BindingSource.Body
                },
                ParameterType = typeof(ProductViewModel)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(input));
                request.ContentType = "application/json";
            });

            var modelState = testContext.ModelState;

            var productDetailsRequired = ValidationAttributeUtil.GetRequiredErrorMessage("ProductDetails");

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var boundPerson = Assert.IsType <ProductViewModel>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.False(modelState.IsValid);
            var modelStateErrors = CreateValidationDictionary(modelState);

            Assert.Equal(productDetailsRequired, modelStateErrors["ProductDetails"]);
        }
        public async Task ComplexModel_EmptyPrefixSelected_NoMatchingValueProviderValue_WithFilteredValueProviders_NoValues()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(Person5),
                BindingInfo   = new BindingInfo()
                {
                    BindingSource = BindingSource.Query,
                },
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                // This value won't be used to select a prefix, because we're only looking at the query string.
                request.Form = new FormCollection(new Dictionary <string, StringValues>()
                {
                    { "parameter", string.Empty },
                });
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType <Person5>(modelBindingResult.Model);

            Assert.Null(model.Name);

            Assert.Equal(0, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
        public async Task CollectionModelBinder_BindsParameterToExpectedType(
            Type parameterType,
            Dictionary <string, StringValues> formContent,
            Type expectedType)
        {
            // Arrange
            var expectedCollection = new List <string> {
                "hello", "world"
            };
            var parameter = new ParameterDescriptor
            {
                Name          = "parameter",
                ParameterType = parameterType,
            };

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var testContext     = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Form = new FormCollection(formContent);
            });
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            Assert.IsType(expectedType, modelBindingResult.Model);

            var model = modelBindingResult.Model as IEnumerable <string>;

            Assert.NotNull(model); // Guard
            Assert.Equal(expectedCollection, model);

            Assert.True(modelState.IsValid);
            Assert.NotEmpty(modelState);
            Assert.Equal(0, modelState.ErrorCount);
        }
        public async Task BindProperty_WithData_WithPrefix_GetsBound()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter",
                },

                ParameterType = typeof(Person)
            };

            var testContext = ModelBindingTestHelper.GetTestContext();
            var modelState  = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <Person>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.False(boundPerson.Token.IsCancellationRequested);
            testContext.HttpContext.Abort();
            Assert.True(boundPerson.Token.IsCancellationRequested);

            // ModelState
            Assert.True(modelState.IsValid);

            Assert.Empty(modelState.Keys);
        }
Beispiel #16
0
        public async Task ActionParameter_BindingToStructModel_ThrowsException()
        {
            // Arrange
            var parameterType   = typeof(PointStruct);
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                ParameterType = parameterType,
                Name          = "p"
            };
            var testContext = ModelBindingTestHelper.GetTestContext();

            // Act & Assert
            var exception = await Assert.ThrowsAsync <InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));

            Assert.Equal(
                string.Format(
                    "Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
                    "value types and must have a parameterless constructor.",
                    typeof(PointStruct).FullName),
                exception.Message);
        }
        public async Task BinderTypeOnParameterType_WithData_EmptyPrefix_GetsBound(BindingInfo bindingInfo)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameters      = typeof(TestController).GetMethod(nameof(TestController.Action)).GetParameters();
            var parameter       = new ControllerParameterDescriptor
            {
                Name          = "Parameter1",
                BindingInfo   = bindingInfo,
                ParameterInfo = parameters[0],
                ParameterType = typeof(Address),
            };

            var testContext = ModelBindingTestHelper.GetTestContext();
            var modelState  = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var address = Assert.IsType <Address>(modelBindingResult.Model);

            Assert.Equal("SomeStreet", address.Street);

            // ModelState
            Assert.True(modelState.IsValid);
            var kvp = Assert.Single(modelState);

            Assert.Equal("Street", kvp.Key);
            var entry = kvp.Value;

            Assert.NotNull(entry);
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.NotNull(entry.RawValue); // Value is set by test model binder, no need to validate it.
        }
Beispiel #18
0
        public async Task BindProperty_WithData_WithPrefix_GetsBound()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter"
                },
                ParameterType = typeof(Person)
            };

            var testContext = ModelBindingTestHelper.GetTestContext();
            var modelState  = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <Person>(modelBindingResult.Model);

            Assert.NotNull(boundPerson.Address);
            Assert.Equal("SomeStreet", boundPerson.Address.Street);

            // ModelState
            Assert.True(modelState.IsValid);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("CustomParameter.Address.Street", key);
            Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState);
            Assert.NotNull(modelState[key].RawValue); // Value is set by test model binder, no need to validate it.
        }
Beispiel #19
0
        public async Task ActionParameter_BindingToAbstractionType_ThrowsException()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                ParameterType = typeof(AbstractClassWithNoDefaultConstructor),
                Name          = "p"
            };
            var testContext = ModelBindingTestHelper.GetTestContext();

            // Act & Assert
            var exception = await Assert.ThrowsAsync <InvalidOperationException>(() => parameterBinder.BindModelAsync(parameter, testContext));

            Assert.Equal(
                string.Format(
                    CultureInfo.CurrentCulture,
                    "Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
                    "value types and must have a parameterless constructor. Record types must have a single primary constructor.",
                    typeof(AbstractClassWithNoDefaultConstructor).FullName),
                exception.Message);
        }
Beispiel #20
0
        public async Task BindDateTimeParameter_WithDataFromBody_GetsBound()
        {
            // Arrange
            var input           = "\"2020-02-01\"";
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name          = "Parameter1",
                ParameterType = typeof(DateTime),
                BindingInfo   = new BindingInfo
                {
                    BindingSource = BindingSource.Body,
                }
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(input));
                request.ContentType = "application/json";
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var model = Assert.IsType <DateTime>(modelBindingResult.Model);

            Assert.Equal(new DateTime(2020, 02, 01, 0, 0, 0, DateTimeKind.Utc), model);

            // ModelState
            Assert.True(modelState.IsValid);
        }
        public async Task ModelMetadataType_ValidArray_NoModelStateErrors()
        {
            // Arrange
            var input = "[" +
                        "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
                        "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21, " +
                        "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}," +
                        "{ \"Name\": \"MVC too\", \"Contact\":\"4258959020\", \"Category\":\"Technology\"," +
                        "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 22, " +
                        "\"ProductDetails\": {\"Detail1\": \"d2\", \"Detail2\": \"d3\", \"Detail3\": \"d4\"}}" +
                        "]";
            var argumentBinding = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name          = "Parameter1",
                ParameterType = typeof(IEnumerable <ProductViewModel>),
                BindingInfo   = new BindingInfo
                {
                    BindingSource = BindingSource.Body,
                },
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(input));
                request.ContentType = "application/json;charset=utf-8";
            });
            var modelState = testContext.ModelState;

            // Act
            var result = await argumentBinding.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelState.IsValid);
            Assert.True(result.IsModelSet);
            var products = Assert.IsAssignableFrom <IEnumerable <ProductViewModel> >(result.Model);

            Assert.Equal(2, products.Count());
        }
Beispiel #22
0
        public async Task BindsJQueryFormatData_FromRequestBody()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(Customer)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body = new MemoryStream(Encoding.UTF8.GetBytes(
                                                    "Name=James&Address[0][City]=Redmond&Address[0][State][ShortName]=WA&Address[0][State][LongName]=Washington"));
                request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType <Customer>(modelBindingResult.Model);

            Assert.Equal("James", model.Name);
            Assert.NotNull(model.Address);
            var address = Assert.Single(model.Address);

            Assert.Equal("Redmond", address.City);
            Assert.NotNull(address.State);
            Assert.Equal("WA", address.State.ShortName);
            Assert.Equal("Washington", address.State.LongName);
            Assert.True(modelState.IsValid);
        }
        public async Task ComplexModel_PrefixSelected_ByValueProvider()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(Person1),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                // This will cause selection of the "parameter" prefix.
                request.QueryString = new QueryString("?parameter=");

                // This value won't be used, because we select the "parameter" prefix.
                request.Form = new FormCollection(new Dictionary <string, StringValues>()
                {
                    { "Name", "Billy" },
                });
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType <Person1>(modelBindingResult.Model);

            Assert.Null(model.Name);

            Assert.Equal(0, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
Beispiel #24
0
        public async Task ActionParameter_NonSettableArrayModel_WithPrefix_DoesNotGetBound()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Address",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "prefix"
                },
                ParameterType = typeof(Person5)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            Assert.NotNull(modelBindingResult.Model);
            var boundModel = Assert.IsType <Person5>(modelBindingResult.Model);

            // Arrays should not be updated.
            Assert.Empty(boundModel.Address);

            // ModelState
            Assert.True(modelState.IsValid);
            Assert.Empty(modelState.Keys);
        }
Beispiel #25
0
        public async Task ActionParameter_EnforcesBindRequired(int?input, bool isValid)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = BindingAndValidationController.BindRequiredParamInfo.Name,
                ParameterType = typeof(int)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                if (input.HasValue)
                {
                    request.QueryString = QueryString.Create(parameter.Name, input.Value.ToString());
                }
            });

            var modelState            = testContext.ModelState;
            var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var modelMetadata         = modelMetadataProvider
                                        .GetMetadataForParameter(BindingAndValidationController.BindRequiredParamInfo);

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(
                parameter,
                testContext,
                modelMetadataProvider,
                modelMetadata);

            // Assert
            Assert.Equal(input.HasValue, modelBindingResult.IsModelSet);
            Assert.Equal(isValid, modelState.IsValid);
            if (isValid)
            {
                Assert.Equal(input.Value, Assert.IsType <int>(modelBindingResult.Model));
            }
        }
        public async Task BindProperty_FormFileCollectionInCollection_OutOfOrderFile()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name          = "house",
                BindingInfo   = new BindingInfo(),
                ParameterType = typeof(House)
            };

            var data        = "Some Data Is Better Than No Data.";
            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                UpdateRequest(request, data + 1, "house.Garage.Cars[800].Specs");
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var house = Assert.IsType <House>(modelBindingResult.Model);

            Assert.NotNull(house.Garage);
            Assert.Empty(house.Garage.Cars);

            // ModelState
            Assert.True(modelState.IsValid);
            Assert.Empty(modelState);
        }
        public async Task CollectionModelBinder_BindsListOfSimpleType_WithExplicitPrefix_Success(string queryString)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "parameter",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "prefix",
                },
                ParameterType = typeof(List <int>)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = new QueryString(queryString);
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType <List <int> >(modelBindingResult.Model);

            Assert.Equal(new List <int>()
            {
                10, 11
            }, model);

            Assert.Equal(2, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
        public async Task BindModelAsync_WithBindProperty_DoesNotBindModel_WhenRequestIsGet()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name          = "parameter",
                ParameterType = typeof(Person),
                BindingInfo   = BindingInfo.GetBindingInfo(new[] { new BindPropertyAttribute() }),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Method      = "GET";
                request.QueryString = new QueryString("?parameter.Name=Joey");
            });

            // Act
            var result = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.False(result.IsModelSet);
        }
Beispiel #29
0
        public async Task BindParameter_WithEmptyData_BindsReferenceAndNullableObjects(Type parameterType)
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo(),

                ParameterType = parameterType
            };
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("Parameter1", string.Empty);
            });
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            Assert.Null(modelBindingResult.Model);

            // ModelState
            Assert.True(modelState.IsValid);
            var key = Assert.Single(modelState.Keys);

            Assert.Equal("Parameter1", key);
            Assert.Equal(string.Empty, modelState[key].AttemptedValue);
            Assert.Equal(string.Empty, modelState[key].RawValue);
            Assert.Empty(modelState[key].Errors);
        }
        public async Task FromBodyAndRequiredOnInnerValueTypeProperty_NotBound_JsonFormatterSuccessful()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person5)
            };

            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes("{ \"Number\": 5 }"));
                request.ContentType = "application/json";
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            var boundPerson = Assert.IsType <Person5>(modelBindingResult.Model);

            Assert.NotNull(boundPerson.Address);
            Assert.Equal(5, boundPerson.Address.Number);
            Assert.Equal(0, boundPerson.Address.RequiredNumber);

            Assert.True(modelState.IsValid);
            Assert.Empty(modelState);
        }