Ejemplo n.º 1
0
        public async Task ReregisteringAntiforgeryTokenInsideFormTagHelper_DoesNotAddDuplicateAntiforgeryTokenFields()
        {
            // Arrange
            var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
            var outputFile        = "compiler/resources/TagHelpersWebSite.Employee.DuplicateAntiforgeryTokenRegistration.html";
            var expectedContent   =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            // Act
            var response = await Client.GetAsync("http://localhost/Employee/DuplicateAntiforgeryTokenRegistration");

            var responseContent = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);

            responseContent = responseContent.Trim();

            var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(
                responseContent, "/Employee/DuplicateAntiforgeryTokenRegistration");

#if GENERATE_BASELINES
            // Reverse usual substitution and insert a format item into the new file content.
            responseContent = responseContent.Replace(forgeryToken, "{0}");
            ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
            expectedContent = string.Format(expectedContent, forgeryToken);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
                responseContent,
                ignoreLineEndingDifferences: true);
#endif
        }
Ejemplo n.º 2
0
        public async Task ViewsWithModelMetadataAttributes_CanRenderForm()
        {
            // Arrange
            var outputFile      = "compiler/resources/TagHelpersWebSite.Employee.Create.html";
            var expectedContent =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            // Act
            var response = await Client.GetAsync("http://localhost/Employee/Create");

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var responseContent = await response.Content.ReadAsStringAsync();

#if GENERATE_BASELINES
            ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(expectedContent),
                responseContent,
                ignoreLineEndingDifferences: true);
#endif
        }
Ejemplo n.º 3
0
        public async Task CheckIfObjectIsDeserialized_WithErrors()
        {
            // Arrange
            var sampleId          = 0;
            var sampleName        = "user";
            var sampleAlias       = "a";
            var sampleDesignation = "HelloWorld!";
            var sampleDescription = "sample user";
            var input             = "{ Id:" + sampleId + ", Name:'" + sampleName + "', Alias:'" + sampleAlias +
                                    "' ,Designation:'" + sampleDesignation + "', description:'" + sampleDescription + "'}";
            var content = new StringContent(input, Encoding.UTF8, "application/json");

            // Act
            var response = await Client.PostAsync("http://localhost/Validation/Index", content);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            // Mono issue - https://github.com/aspnet/External/issues/29
            Assert.Equal(PlatformNormalizer.NormalizeContent(
                             "The field Id must be between 1 and 2000.," +
                             "The field Name must be a string or array type with a minimum length of '5'.," +
                             "The field Alias must be a string with a minimum length of 3 and a maximum length of 15.," +
                             "The field Designation must match the regular expression " +
                             (TestPlatformHelper.IsMono ? "[0-9a-zA-Z]*." : "'[0-9a-zA-Z]*'.")),
                         await response.Content.ReadAsStringAsync());
        }
Ejemplo n.º 4
0
        public void CheckBoxForWithNonNullContainer_UsesPropertyValue(bool value, string expectedChecked)
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input {0}data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");

            expected = string.Format(expected, expectedChecked);

            var viewData = GetTestModelViewData();

            viewData.Model = new TestModel
            {
                Property1 = value,
            };

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData);

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 5
0
 private static void AssertRequiredError(string key, ModelError error)
 {
     // Mono issue - https://github.com/aspnet/External/issues/19
     Assert.Equal(PlatformNormalizer.NormalizeContent(
                      string.Format("The {0} field is required.", key)), error.ErrorMessage);
     Assert.Null(error.Exception);
 }
Ejemplo n.º 6
0
        public async Task HtmlGenerationWebSite_GeneratesExpectedResults(string action, string antiforgeryPath)
        {
            // This uses FileVersionProvider which uses Uri.TryCreate - https://github.com/aspnet/External/issues/21
            if (TestPlatformHelper.IsMono && (action == "Link" || action == "Script" || action == "Image"))
            {
                return;
            }

            // Arrange
            var server            = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client            = server.CreateClient();
            var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
            var outputFile        = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".html";
            var expectedContent   =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            // Act
            // The host is not important as everything runs in memory and tests are isolated from each other.
            var response = await client.GetAsync("http://localhost/HtmlGeneration_Home/" + action);

            var responseContent = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);

            responseContent = responseContent.Trim();
            if (antiforgeryPath == null)
            {
#if GENERATE_BASELINES
                ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
                // Mono issue - https://github.com/aspnet/External/issues/19
                Assert.Equal(
                    PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
                    responseContent,
                    ignoreLineEndingDifferences: true);
#endif
            }
            else
            {
                var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, antiforgeryPath);
#if GENERATE_BASELINES
                // Reverse usual substitution and insert a format item into the new file content.
                responseContent = responseContent.Replace(forgeryToken, "{0}");
                ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
                expectedContent = string.Format(expectedContent, forgeryToken);
                // Mono issue - https://github.com/aspnet/External/issues/19
                Assert.Equal(
                    PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
                    responseContent,
                    ignoreLineEndingDifferences: true);
#endif
            }
        }
Ejemplo n.º 7
0
        public void Editor_AppliesNonDefaultEditFormat(string dataTypeName, Html5DateRenderingMode renderingMode)
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expectedInput = PlatformNormalizer.NormalizeContent(
                "<input class=\"HtmlEncode[[text-box single-line]]\" data-val=\"HtmlEncode[[true]]\" " +
                "data-val-required=\"HtmlEncode[[The DateTimeOffset field is required.]]\" id=\"HtmlEncode[[FieldPrefix]]\" " +
                "name=\"HtmlEncode[[FieldPrefix]]\" type=\"HtmlEncode[[" +
                dataTypeName +
                "]]\" value=\"HtmlEncode[[Formatted as 2000-01-02T03:04:05.0600000+00:00]]\" />");

            var offset = TimeSpan.FromHours(0);
            var model  = new DateTimeOffset(
                year: 2000,
                month: 1,
                day: 2,
                hour: 3,
                minute: 4,
                second: 5,
                millisecond: 60,
                offset: offset);
            var viewEngine = new Mock <ICompositeViewEngine>();

            viewEngine
            .Setup(v => v.FindPartialView(It.IsAny <ActionContext>(), It.IsAny <string>()))
            .Returns(ViewEngineResult.NotFound("", Enumerable.Empty <string>()));


            var provider = new TestModelMetadataProvider();

            provider.ForType <DateTimeOffset>().DisplayDetails(dd =>
            {
                dd.DataTypeName            = dataTypeName;
                dd.EditFormatString        = "Formatted as {0:O}"; // What [DataType] does for given type.
                dd.HasNonDefaultEditFormat = true;
            });

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(
                model,
                null,
                viewEngine.Object,
                provider);

            helper.Html5DateRenderingMode = renderingMode; // Ignored due to HasNonDefaultEditFormat.
            helper.ViewData.TemplateInfo.HtmlFieldPrefix = "FieldPrefix";

            // Act
            var result = helper.Editor("");

            // Assert
            Assert.Equal(expectedInput, result.ToString());
        }
        public async Task ModelMetaDataTypeAttribute_InvalidPropertiesAndSubPropertiesOnBaseClass_HasModelStateErrors()
        {
            // Arrange
            var input          = "{ \"Price\": 2, \"ProductDetails\": {\"Detail1\": \"d1\"}}";
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BindingSource = BindingSource.Body
                },
                ParameterType = typeof(ProductViewModel)
            };

            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 <ProductViewModel>(modelBindingResult.Model);

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

            Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["CompanyName"]);
            Assert.Equal("The field Price must be between 20 and 100.", modelStateErrors["Price"]);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Category field is required."),
                modelStateErrors["Category"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Contact Us field is required."),
                modelStateErrors["Contact"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Detail2 field is required."),
                modelStateErrors["ProductDetails.Detail2"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Detail3 field is required."),
                modelStateErrors["ProductDetails.Detail3"]);
        }
Ejemplo n.º 9
0
        public void HiddenGeneratesUnobtrusiveValidation()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property2 field is required.]]"" " +
                @"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[hidden]]"" value="""" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithModelStateAndModelAndViewDataValues());

            // Act
            var result = helper.Hidden("Property2", value: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
        }
Ejemplo n.º 10
0
        public void PasswordFor_GeneratesUnobtrusiveValidationAttributes()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property2 field is required.]]"" " +
                @"id=""HtmlEncode[[Property2]]"" name=""HtmlEncode[[Property2]]"" type=""HtmlEncode[[password]]"" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetViewDataWithErrors());

            // Act
            var result = helper.PasswordFor(m => m.Property2, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result));
        }
        public void CheckBoxGeneratesUnobtrusiveValidationAttributes()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Name field is required.]]"" id=""HtmlEncode[[Name]]""" +
                @" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());

            // Act
            var html = helper.CheckBox("Name", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 12
0
        public async Task EditorTemplateWithNoModel_RendersWithCorrectMetadata()
        {
            // Arrange
            var expected = PlatformNormalizer.NormalizeContent(
                "<label class=\"control-label col-md-2\" for=\"Name\">ItemName</label>" + Environment.NewLine +
                "<input id=\"Name\" name=\"Name\" type=\"text\" value=\"\" />" + Environment.NewLine + Environment.NewLine +
                "<label class=\"control-label col-md-2\" for=\"Id\">ItemNo</label>" + Environment.NewLine +
                "<input data-val=\"true\" data-val-required=\"The ItemNo field is required.\" id=\"Id\" name=\"Id\" type=\"text\" value=\"\" />" +
                Environment.NewLine + Environment.NewLine);

            // Act
            var response = await Client.GetStringAsync("http://localhost/HtmlGeneration_Home/ItemUsingSharedEditorTemplate");

            // Assert
            Assert.Equal(expected, response);
        }
        public void CheckBoxFor_WithComplexExpressions_DoesNotUseValuesFromViewDataDictionary()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[ComplexProperty_Property1]]"" name=""HtmlEncode[[ComplexProperty." +
                @"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]"" " +
                @"type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());

            // Act
            var html = helper.CheckBoxFor(m => m.ComplexProperty.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 14
0
        public async Task FromBodyOnTopLevelProperty_RequiredOnSubProperty_AddsModelStateError(string inputText)
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor
            {
                BindingInfo = new BindingInfo
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person2),
                Name          = "param-name",
            };

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

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

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

            Assert.NotNull(boundPerson);

            Assert.False(modelState.IsValid);
            Assert.Equal(2, modelState.Keys.Count);
            var address = Assert.Single(modelState, kvp => kvp.Key == "CustomParameter.Address").Value;

            Assert.Equal(ModelValidationState.Unvalidated, address.ValidationState);

            var street = Assert.Single(modelState, kvp => kvp.Key == "CustomParameter.Address.Street").Value;

            Assert.Equal(ModelValidationState.Invalid, street.ValidationState);
            var error = Assert.Single(street.Errors);

            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(PlatformNormalizer.NormalizeContent("The Street field is required."), error.ErrorMessage);
        }
        public void CheckBoxForOverridesCalculatedParametersWithValuesFromHtmlAttributes()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                @"data-val-required=""HtmlEncode[[The Property3 field is required.]]"" " +
                @"id=""HtmlEncode[[Property3]]"" name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
                @"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            // Act
            var html = helper.CheckBoxFor(m => m.Property3, new { @checked = "checked", value = "false" });

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public void CheckBoxCheckedWithOnlyName_GeneratesExpectedValue()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                @"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property1]]"" " +
                @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" " +
                @"value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            // Act
            var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 17
0
        public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs()
        {
            // Arrange
            var server          = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client          = server.CreateClient();
            var outputFile      = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html";
            var expectedContent =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            var request             = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customer/HtmlGeneration_Customer");
            var nameValueCollection = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Number", string.Empty),
                new KeyValuePair <string, string>("Name", string.Empty),
                new KeyValuePair <string, string>("Email", string.Empty),
                new KeyValuePair <string, string>("PhoneNumber", string.Empty),
                new KeyValuePair <string, string>("Password", string.Empty)
            };

            request.Content = new FormUrlEncodedContent(nameValueCollection);

            // Act
            var response = await client.SendAsync(request);

            var responseContent = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            responseContent = responseContent.Trim();
            var forgeryToken =
                AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, "Customer/HtmlGeneration_Customer");

#if GENERATE_BASELINES
            // Reverse usual substitution and insert a format item into the new file content.
            responseContent = responseContent.Replace(forgeryToken, "{0}");
            ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
            expectedContent = string.Format(expectedContent, forgeryToken);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
                responseContent,
                ignoreLineEndingDifferences: true);
#endif
        }
        public void CheckBoxFor_WithObjectAttribute_MapsUnderscoresInNamesToDashes()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
                @"Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
                @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper         = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 19
0
        public void CheckBoxWithComplexExpressionsEvaluatesValuesInViewDataDictionary()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                @"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[ComplexProperty_Property1]]"" " +
                @"name=""HtmlEncode[[ComplexProperty." +
                @"Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input name=""HtmlEncode[[ComplexProperty.Property1]]""" +
                @" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetModelWithValidationViewData());

            // Act
            var html = helper.CheckBox("ComplexProperty.Property1", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
        public void CheckBoxForWithNullContainer_TreatsBooleanAsFalse()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var viewData = GetTestModelViewData();
            var helper   = DefaultTemplatesUtilities.GetHtmlHelper(viewData);

            viewData.ModelState.SetModelValue("Property1", new string[] { "false" }, "false");

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 21
0
        public async Task HomeController_Index_ReturnsExpectedContent()
        {
            // Arrange
            var resetResponse = await Client.PostAsync("http://localhost/Home/Reset", content : null);

            // Guard 1 (start from scratch)
            AssertRedirectsToHome(resetResponse);

            var createBillyContent  = CreateUserFormContent("Billy", "2000-11-28", 0, "hello");
            var createBillyResponse = await Client.PostAsync("http://localhost/Home/Create", createBillyContent);

            // Guard 2 (ensure user 0 exists)
            AssertRedirectsToHome(createBillyResponse);

            var createBobbyContent  = CreateUserFormContent("Bobby", "1999-10-27", 1, "howdy");
            var createBobbyResponse = await Client.PostAsync("http://localhost/Home/Create", createBobbyContent);

            // Guard 3 (ensure user 1 exists)
            AssertRedirectsToHome(createBobbyResponse);

            var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
            var outputFile        = "compiler/resources/TagHelperSample.Web.Home.Index.html";
            var resourceAssembly  = typeof(TagHelperSampleTest).GetTypeInfo().Assembly;
            var expectedContent   = await ResourceFile.ReadResourceAsync(resourceAssembly, outputFile, sourceFile : false);

            // Act
            var response = await Client.GetAsync("http://localhost/");

            var responseContent = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);

#if GENERATE_BASELINES
            ResourceFile.UpdateFile(resourceAssembly, outputFile, expectedContent, responseContent);
#else
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(expectedContent),
                responseContent,
                ignoreLineEndingDifferences: true);
#endif
        }
Ejemplo n.º 22
0
        public void CheckBoxReplacesUnderscoresInHtmlAttributesWithDashes()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                @"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property1]]"" " +
                @"name=""HtmlEncode[[Property1]]"" Property1-Property3=""HtmlEncode[[Property3ObjValue]]"" " +
                @"type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
                @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper         = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            var htmlAttributes = new { Property1_Property3 = "Property3ObjValue" };

            // Act
            var html = helper.CheckBox("Property1", isChecked: true, htmlAttributes: htmlAttributes);

            // Assert
            Assert.Equal(expected, html.ToString());
        }
Ejemplo n.º 23
0
        public async Task TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();
            var input  = "[ { \"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " +
                         "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"} }," +
                         "{\"Price\": 2, \"Contact\": \"acvrdzersaererererfdsfdsfdsfsdf\", " +
                         "\"ProductDetails\": {\"Detail1\": \"d1\", \"Detail2\": \"d2\", \"Detail3\": \"d3\"} }]";
            var content = new StringContent(input, Encoding.UTF8, "application/json");
            var url     =
                "http://localhost/ModelMetadataTypeValidation/TryValidateModelWithCollectionsModel";

            // Act
            var response = await client.PostAsync(url, content);

            // Assert
            var body = await response.Content.ReadAsStringAsync();

            var json = JsonConvert.DeserializeObject <Dictionary <string, string> >(body);

            Assert.Equal("CompanyName cannot be null or empty.", json["[0].CompanyName"]);
            Assert.Equal("The field Price must be between 20 and 100.", json["[0].Price"]);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Category field is required."),
                json["[0].Category"]);
            AssertErrorEquals(
                "The field Contact Us must be a string with a maximum length of 20." +
                "The field Contact Us must match the regular expression " +
                (TestPlatformHelper.IsMono ? "^[0-9]*$." : "'^[0-9]*$'."),
                json["[0].Contact"]);
            Assert.Equal("CompanyName cannot be null or empty.", json["[1].CompanyName"]);
            Assert.Equal("The field Price must be between 20 and 100.", json["[1].Price"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Category field is required."),
                json["[1].Category"]);
            AssertErrorEquals(
                "The field Contact Us must be a string with a maximum length of 20." +
                "The field Contact Us must match the regular expression " +
                (TestPlatformHelper.IsMono ? "^[0-9]*$." : "'^[0-9]*$'."),
                json["[1].Contact"]);
        }
Ejemplo n.º 24
0
        public void CheckBoxUsesAttemptedValueFromModelState()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Boolean field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var valueProviderResult = new ValueProviderResult("false", "false", CultureInfo.InvariantCulture);
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            helper.ViewData.ModelState.SetModelValue("Property1", valueProviderResult);

            // Act
            var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 25
0
        public async Task BindPropertyFromHeader_NoData_UsesFullPathAsKeyForModelStateErrors()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person)
            };

            // Do not add any headers.
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext();
            var modelState       = new ModelStateDictionary();

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

            // Assert

            // ModelBindingResult
            Assert.NotNull(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);

            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(PlatformNormalizer.NormalizeContent("The Street field is required."), error.ErrorMessage);
        }
        public void CheckBoxExplicitParametersOverrideDictionary_ForValueInModel()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input checked=""HtmlEncode[[checked]]"" data-val=""HtmlEncode[[true]]"" " +
                @"data-val-required=""HtmlEncode[[The Boolean field is required.]]"" id=""HtmlEncode[[Property3]]"" " +
                @"name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[checkbox]]"" " +
                @"value=""HtmlEncode[[false]]"" /><input name=""HtmlEncode[[Property3]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");

            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            // Act
            var html = helper.CheckBox("Property3",
                                       isChecked: true,
                                       htmlAttributes: new { @checked = "unchecked", value = "false" });

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
        public void CheckBoxFor_WithAttributeDictionary_GeneratesExpectedAttributes()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Property1 field is required.]]"" " +
                @"id=""HtmlEncode[[Property1]]"" name=""HtmlEncode[[Property1]]"" " +
                @"Property3=""HtmlEncode[[Property3Value]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" /><input " +
                @"name=""HtmlEncode[[Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var helper     = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());
            var attributes = new Dictionary <string, object> {
                { "Property3", "Property3Value" }
            };

            // Act
            var html = helper.CheckBoxFor(m => m.Property1, attributes);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }
Ejemplo n.º 28
0
        public async Task FromBodyAndRequiredOnProperty_EmptyBody_AddsModelStateError()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter      = new ParameterDescriptor()
            {
                Name        = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = "CustomParameter",
                },
                ParameterType = typeof(Person)
            };

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

            var modelState = new ModelStateDictionary();

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

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

            Assert.NotNull(boundPerson);
            var key = Assert.Single(modelState.Keys);

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

            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(PlatformNormalizer.NormalizeContent("The Address field is required."), error.ErrorMessage);
        }
Ejemplo n.º 29
0
        public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expectedMessage = PlatformNormalizer.NormalizeContent("The MyProperty field is required.");
            var binders         = new IModelBinder[]
            {
                new TypeConverterModelBinder(),
                new ComplexModelDtoModelBinder(),
                new MutableObjectModelBinder()
            };

            var validator            = new DataAnnotationsModelValidatorProvider();
            var model                = new MyModel();
            var modelStateDictionary = new ModelStateDictionary();
            var values               = new Dictionary <string, object>
            {
                { "", null }
            };
            var valueProvider         = new TestValueProvider(values);
            var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();

            // Act
            var result = await ModelBindingHelper.TryUpdateModelAsync(
                model,
                "",
                Mock.Of <HttpContext>(),
                modelStateDictionary,
                modelMetadataProvider,
                GetCompositeBinder(binders),
                valueProvider,
                new List <IInputFormatter>(),
                new DefaultObjectValidator(new IExcludeTypeValidationFilter[0], modelMetadataProvider),
                validator);

            // Assert
            Assert.False(result);
            var error = Assert.Single(modelStateDictionary["MyProperty"].Errors);

            Assert.Equal(expectedMessage, error.ErrorMessage);
        }
        public void CheckBoxForGeneratesUnobtrusiveValidationAttributes()
        {
            // Arrange
            // Mono issue - https://github.com/aspnet/External/issues/19
            var expected = PlatformNormalizer.NormalizeContent(
                @"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[The Name field is required.]]"" id=""HtmlEncode[[Name]]""" +
                @" name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" +
                @"<input name=""HtmlEncode[[Name]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />");
            var metadataProvider   = TestModelMetadataProvider.CreateDefaultProvider();
            var viewDataDictionary = new ViewDataDictionary <ModelWithValidation>(metadataProvider)
            {
                Model = new ModelWithValidation()
            };
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewDataDictionary);

            // Act
            var html = helper.CheckBoxFor(m => m.Name, htmlAttributes: null);

            // Assert
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
        }