예제 #1
0
        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.Empty(modelState);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
        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 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);
        }
        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 DictionaryModelBinder_BindsDictionaryOfSimpleType_WithExplicitPrefix_Success(
            string queryString)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "parameter",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "prefix",
                },
                ParameterType = typeof(Dictionary <string, int>)
            };

            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = new QueryString(queryString);
            });

            var modelState = operationContext.ActionContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, operationContext) ?? default(ModelBindingResult);

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

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

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

            Assert.NotEmpty(modelState);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
예제 #6
0
        public async Task ComplexModel_PrefixSelected_ByValueProvider()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            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 argumentBinder.BindModelAsync(parameter, testContext) ?? default(ModelBindingResult);

            // Assert
            Assert.True(modelBindingResult.IsModelSet);
            Assert.Equal("parameter", modelBindingResult.Key);

            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);
        }
예제 #7
0
        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 testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(inputText));
                request.ContentType = "application/json";
            },
                metadataProvider: metadataProvider);

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

            // 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 BindProperty_WithData_WithPrefix_GetsBound()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter"
                },
                ParameterType = typeof(Person)
            };

            var operationContext = ModelBindingTestHelper.GetOperationBindingContext();
            var modelState       = operationContext.ActionContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, operationContext) ?? default(ModelBindingResult);

            // Assert

            // ModelBindingResult
            Assert.Equal("CustomParameter", modelBindingResult.Key);

            // 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.
        }
        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.
        }
예제 #10
0
        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());
        }
        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);
        }
        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);
        }
예제 #13
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);
        }
예제 #14
0
        public async Task BinderTypeOnProperty_WithData_EmptyPrefix_GetsBound(BindingInfo bindingInfo)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                Name          = "Parameter1",
                BindingInfo   = bindingInfo,
                ParameterType = typeof(Person3),
            };

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

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

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

            // Model
            var person = Assert.IsType <Person3>(modelBindingResult.Model);

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

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

            Assert.Equal("Address.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.
        }
예제 #15
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 CollectionModelBinder_BindsListOfSimpleType_WithExplicitPrefix_Success(string queryString)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            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 argumentBinder.BindModelAsync(parameter, testContext) ?? default(ModelBindingResult);

            // 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);
        }
예제 #17
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 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);
        }
        public async Task BindParameterFromService_WithData_GetsBound()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter",
                    BindingSource   = BindingSource.Services
                },

                // Using a service type already in defaults.
                ParameterType = typeof(JsonOutputFormatter)
            };

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

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

            // Assert

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

            // Model
            var outputFormatter = Assert.IsType <JsonOutputFormatter>(modelBindingResult.Model);

            Assert.NotNull(outputFormatter);

            // ModelState
            Assert.True(modelState.IsValid);
            Assert.Empty(modelState.Keys);
        }
예제 #20
0
        public async Task KeyValuePairModelBinder_SimpleTypes_WithNoValue_AddsError()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                Name          = "parameter",
                ParameterType = typeof(KeyValuePair <string, int>)
            };
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = new QueryString("?parameter.Key=10");
            });
            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext) ?? default(ModelBindingResult);

            // Assert
            Assert.False(modelBindingResult.IsModelSet);
            Assert.Equal(2, modelState.Count);

            Assert.False(modelState.IsValid);
            Assert.Equal(1, modelState.ErrorCount);

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

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

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

            Assert.Null(error.Exception);
            Assert.Equal("A value is required.", error.ErrorMessage);
        }
        public async Task BindParameter_WithData_GetsBound()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter",
                },

                ParameterType = typeof(CancellationToken)
            };

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

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

            // Assert

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

            // Model
            var token = Assert.IsType <CancellationToken>(modelBindingResult.Model);

            Assert.False(token.IsCancellationRequested);
            testContext.HttpContext.Abort();
            Assert.True(token.IsCancellationRequested);

            // ModelState
            Assert.True(modelState.IsValid);
            Assert.Equal(0, modelState.Count);
        }
        public async Task FromBodyAndRequiredOnInnerValueTypeProperty_NotBound_JsonFormatterSuccessful()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person5)
            };

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

            var modelState = operationContext.ActionContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, operationContext) ?? default(ModelBindingResult);

            // 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);
        }
예제 #23
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 BindParameter_WithEmptyData_BindsMutableAndNullableObjects(Type parameterType)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo(),

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

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, operationContext) ?? default(ModelBindingResult);

            // 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(new string[] { string.Empty }, modelState[key].RawValue);
            Assert.Empty(modelState[key].Errors);
        }
        public async Task ModelMetaDataTypeAttribute_ValidDerivedClass_NoModelStateErrors()
        {
            // Arrange
            var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
                        "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\", \"Version\":\"2\"," +
                        "\"DatePurchased\": \"/Date(1297246301973)/\", \"Price\" : \"110\" }";
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BindingSource = BindingSource.Body
                },
                ParameterType = typeof(SoftwareViewModel)
            };

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

            var modelState = operationContext.ActionContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, operationContext) ?? default(ModelBindingResult);

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

            Assert.NotNull(boundPerson);
            Assert.True(modelState.IsValid);
        }
        public async Task BindParameterFromService_NoService_Throws()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name        = "ControllerProperty",
                BindingInfo = new BindingInfo
                {
                    BindingSource = BindingSource.Services,
                },

                // Use a service type not available in DI.
                ParameterType = typeof(IActionResult),
            };

            var testContext = ModelBindingTestHelper.GetTestContext();

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

            Assert.Contains(typeof(IActionResult).FullName, exception.Message);
        }
예제 #27
0
        public async Task BindParameter_NoData_BindsWithEmptyCollection()
        {
            // Arrange
            var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
            var parameter       = new ParameterDescriptor
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(IFormCollection)
            };

            // No data is passed.
            var testContext = ModelBindingTestHelper.GetTestContext();

            var modelState = testContext.ModelState;

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

            // Assert

            // ModelBindingResult
            var collection = Assert.IsAssignableFrom <IFormCollection>(modelBindingResult.Model);

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

            // FormCollection
            Assert.Empty(collection);
            Assert.Empty(collection.Files);
            Assert.Empty(collection.Keys);
        }
        public async Task TryUpdateModel_SettableArrayModel_WithPrefix_CreatesArray()
        {
            // Arrange
            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
            });

            var modelState = testContext.ModelState;
            var model      = new Person4();

            // Act
            var result = await TryUpdateModelAsync(model, "prefix", testContext);

            // Assert
            Assert.True(result);

            // Model
            Assert.NotNull(model.Address);
            Assert.Single(model.Address);
            Assert.Equal("SomeStreet", model.Address[0].Street);
            Assert.Null(model.Address[0].City);

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

            var entry = Assert.Single(modelState);

            Assert.Equal("prefix.Address[0].Street", entry.Key);
            var state = entry.Value;

            Assert.Equal("SomeStreet", state.AttemptedValue);
            Assert.Equal("SomeStreet", state.RawValue);
            Assert.Empty(state.Errors);
            Assert.Equal(ModelValidationState.Valid, state.ValidationState);
        }
예제 #29
0
        public async Task BindParameter_WithData_WithPrefix_GetsBound()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderType      = typeof(SuccessModelBinder),
                    BinderModelName = "CustomParameter"
                },

                ParameterType = typeof(Person2)
            };

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

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

            // Assert

            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);
            Assert.Equal("Success", modelBindingResult.Model);

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

            Assert.Equal("CustomParameter", 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.
        }
        public async Task ModelMetaDataTypeAttribute_ValidBaseClass_NoModelStateErrors()
        {
            // Arrange
            var input = "{ \"Name\": \"MVC\", \"Contact\":\"4258959019\", \"Category\":\"Technology\"," +
                        "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21, " +
                        "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"}}";
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name          = "Parameter1",
                ParameterType = typeof(ProductViewModel),
                BindingInfo   = new BindingInfo()
                {
                    BindingSource = BindingSource.Body
                }
            };

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

            var modelState = operationContext.ActionContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, operationContext) ?? default(ModelBindingResult);

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

            Assert.True(modelState.IsValid);
            Assert.NotNull(boundPerson);
        }