Esempio n. 1
0
        public async Task ModelMetaDataTypeAttribute_InvalidPropertiesAndSubPropertiesOnBaseClass_ReturnsErrors()
        {
            // Arrange
            var input   = "{ \"Price\": 2, \"ProductDetails\": {\"Detail1\": \"d1\"}}";
            var content = new StringContent(input, Encoding.UTF8, "application/json");

            var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata";

            // 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(6, json.Count);
            Assert.Equal("CompanyName cannot be null or empty.", json["CompanyName"]);
            Assert.Equal("The field Price must be between 20 and 100.", json["Price"]);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(PlatformNormalizer.NormalizeContent("The Category field is required."), json["Category"]);
            Assert.Equal(PlatformNormalizer.NormalizeContent("The Contact Us field is required."), json["Contact"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Detail2 field is required."),
                json["ProductDetails.Detail2"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Detail3 field is required."),
                json["ProductDetails.Detail3"]);
        }
Esempio n. 2
0
        public async Task NoRequestContentType_Throws_IfMultipleActionsWithConstraints()
        {
            // Arrange
            var server  = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client  = server.CreateClient();
            var request = new HttpRequestMessage(
                HttpMethod.Post,
                "http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct");

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

            var exception = response.GetServerException();

            // Assert
            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            Assert.Equal(typeof(AmbiguousActionException).FullName, exception.ExceptionType);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                "Multiple actions matched. The following actions matched route data and had all constraints " +
                "satisfied:" + PlatformNormalizer.GetNewLinesAsUnderscores(2) + "ActionConstraintsWebSite." +
                "ConsumesAttribute_NoFallBackActionController." +
                "CreateProduct" + PlatformNormalizer.GetNewLinesAsUnderscores(1) + "ActionConstraintsWebSite." +
                "ConsumesAttribute_NoFallBackActionController.CreateProduct",
                exception.ExceptionMessage);
        }
Esempio n. 3
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
        }
Esempio n. 4
0
        public void GetInheritedChunks_ReturnsEmptySequenceIfNoGlobalsArePresent()
        {
            // Arrange
            var fileProvider = new TestFileProvider();

            fileProvider.AddFile(@"/_ViewImports.cs", string.Empty);
            fileProvider.AddFile(@"/Views/_Layout.cshtml", string.Empty);
            fileProvider.AddFile(@"/Views/home/_not-viewimports.cshtml", string.Empty);
            var cache = new DefaultChunkTreeCache(fileProvider);

            using (var host = new MvcRazorHost(cache))
            {
                var defaultChunks = new Chunk[]
                {
                    new InjectChunk("MyTestHtmlHelper", "Html"),
                    new UsingChunk {
                        Namespace = "AppNamespace.Model"
                    },
                };
                var utility = new ChunkInheritanceUtility(host, cache, defaultChunks);

                // Act
                var chunkTrees = utility.GetInheritedChunkTreeResults(PlatformNormalizer.NormalizePath(@"Views\home\Index.cshtml"));

                // Assert
                Assert.Empty(chunkTrees);
            }
        }
Esempio n. 5
0
        public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
        {
            // Arrange
            var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata         = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");

            var attribute = new CompareAttribute("OtherProperty");
            var adapter   = new CompareAttributeAdapter(attribute, stringLocalizer: null);

            var serviceCollection = new ServiceCollection();
            var requestServices   = serviceCollection.BuildServiceProvider();

            var context = new ClientModelValidationContext(metadata, metadataProvider, requestServices);

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

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

            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(
                    "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match."),
                rule.ErrorMessage);
        }
Esempio n. 6
0
        public async Task TryValidateModel_ClearParameterValidationError_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\"}}";
            var content = new StringContent(input, Encoding.UTF8, "application/json");
            var url     =
                "http://localhost/ModelMetadataTypeValidation/" +
                "TryValidateModelAfterClearingValidationErrorInParameter?theImpossibleString=test";

            // 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(4, json.Count);
            Assert.Equal("CompanyName cannot be null or empty.", json["CompanyName"]);
            Assert.Equal("The field Price must be between 20 and 100.", json["Price"]);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Category field is required."),
                json["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["Contact"]);
        }
        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));
        }
Esempio n. 8
0
        public async Task RemoteAttribute_LeadsToExpectedValidationAttributes(string areaName, string pathSegment)
        {
            // Arrange
            var outputFile      = "compiler/resources/ValidationWebSite." + areaName + ".RemoteAttribute_Home.Create.html";
            var expectedContent =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            var url = "http://localhost" + pathSegment + "/RemoteAttribute_Home/Create";

            // Act
            var response = await Client.GetAsync(url);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);
            Assert.Equal("utf-8", response.Content.Headers.ContentType.CharSet);

            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
        }
        public void CheckBox_WithCanRenderAtEndOfFormSet_DoesNotGenerateInlineHiddenTag()
        {
            // 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]]"" />");
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData());

            helper.ViewContext.FormContext.CanRenderAtEndOfForm = true;

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

            // Assert
            Assert.True(helper.ViewContext.FormContext.HasEndOfFormContent);
            Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html));
            var writer    = new StringWriter();
            var hiddenTag = Assert.Single(helper.ViewContext.FormContext.EndOfFormContent);

            hiddenTag.WriteTo(writer, new HtmlTestEncoder());
            Assert.Equal("<input name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />",
                         writer.ToString());
        }
Esempio n. 10
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
        }
Esempio n. 11
0
        public async Task ModelMetaDataTypeAttribute_InvalidComplexTypePropertyOnBaseClass_ReturnsErrors()
        {
            // Arrange
            var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
            var client = server.CreateClient();
            var input  = "{ \"Contact\":\"4255678765\", \"Category\":\"Technology\"," +
                         "\"CompanyName\":\"Microsoft\", \"Country\":\"USA\",\"Price\": 21 }";
            var content = new StringContent(input, Encoding.UTF8, "application/json");

            var url = "http://localhost/ModelMetadataTypeValidation/ValidateProductViewModelIncludingMetadata";

            // 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(1, json.Count);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The ProductDetails field is required."),
                json["ProductDetails"]);
        }
Esempio n. 12
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);
 }
Esempio n. 13
0
        public void TryValidateModel_CollectionsModel_ReturnsErrorsForInvalidProperties()
        {
            // Arrange
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext();
            var modelState       = operationContext.ActionContext.ModelState;
            var model            = new List <ProductViewModel>();

            model.Add(new ProductViewModel()
            {
                Price          = 2,
                Contact        = "acvrdzersaererererfdsfdsfdsfsdf",
                ProductDetails = new ProductDetails()
                {
                    Detail1 = "d1",
                    Detail2 = "d2",
                    Detail3 = "d3"
                }
            });
            model.Add(new ProductViewModel()
            {
                Price          = 2,
                Contact        = "acvrdzersaererererfdsfdsfdsfsdf",
                ProductDetails = new ProductDetails()
                {
                    Detail1 = "d1",
                    Detail2 = "d2",
                    Detail3 = "d3"
                }
            });
            var oldModel = model;

            // Act
            var result = TryValidateModel(model, prefix: string.Empty, operationContext: operationContext);

            // Assert
            Assert.False(result);
            Assert.False(modelState.IsValid);
            var modelStateErrors = GetModelStateErrors(modelState);

            Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[0].CompanyName"]);
            Assert.Equal("The field Price must be between 20 and 100.", modelStateErrors["[0].Price"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Category field is required."),
                modelStateErrors["[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]*$'."),
                modelStateErrors["[0].Contact"]);
            Assert.Equal("CompanyName cannot be null or empty.", modelStateErrors["[1].CompanyName"]);
            Assert.Equal("The field Price must be between 20 and 100.", modelStateErrors["[1].Price"]);
            Assert.Equal(
                PlatformNormalizer.NormalizeContent("The Category field is required."),
                modelStateErrors["[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]*$'."),
                modelStateErrors["[1].Contact"]);
        }
Esempio n. 14
0
        public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName_WithoutLocalizer()
        {
            // Arrange
            var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata         = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");

            var attribute = new CompareAttribute("OtherProperty");
            var adapter   = new CompareAttributeAdapter(attribute, stringLocalizer: null);

            // Mono issue - https://github.com/aspnet/External/issues/19
            var expectedMessage = PlatformNormalizer.NormalizeContent(
                "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match.");

            var actionContext = new ActionContext();
            var context       = new ClientModelValidationContext(
                actionContext,
                metadata,
                metadataProvider,
                new AttributeDictionary());

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp => { Assert.Equal("data-val-equalto", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
                kvp =>
            {
                Assert.Equal("data-val-equalto-other", kvp.Key);
                Assert.Equal(kvp.Value, "*.OtherProperty");
            });
        }
Esempio n. 15
0
        public async Task OverrideAppWideDefaultsInViewAndPartialView()
        {
            // Arrange
            var expected =
                @"<div class=""validation-summary-errors""><ValidationSummaryInView>MySummary</ValidationSummaryInView>
<ul><li style=""display:none""></li>
</ul></div>
<ValidationInView class=""field-validation-error"" data-valmsg-for=""Error"" data-valmsg-replace=""true"">An error occurred.</ValidationInView>
<input id=""Prefix!Property1"" name=""Prefix.Property1"" type=""text"" value="""" />
<div class=""editor-label""><label for=""MyDate"">MyDate</label></div>
<div class=""editor-field""><input class=""text-box single-line"" data-val=""true"" data-val-required=""The MyDate field is required."" id=""MyDate"" name=""MyDate"" type=""datetime"" value=""02/01/2000 03:04:05 &#x2B;00:00"" /> <ValidationInView class=""field-validation-valid"" data-valmsg-for=""MyDate"" data-valmsg-replace=""true""></ValidationInView></div>

True
<div class=""validation-summary-errors""><ValidationSummaryInPartialView>MySummary</ValidationSummaryInPartialView>
<ul><li style=""display:none""></li>
</ul></div>
<ValidationInPartialView class=""field-validation-error"" data-valmsg-for=""Error"" data-valmsg-replace=""true"">An error occurred.</ValidationInPartialView>
<input id=""Prefix!Property1"" name=""Prefix.Property1"" type=""text"" value="""" />
<div class=""editor-label""><label for=""MyDate"">MyDate</label></div>
<div class=""editor-field""><input class=""text-box single-line"" id=""MyDate"" name=""MyDate"" type=""datetime"" value=""02/01/2000 03:04:05 &#x2B;00:00"" /> <ValidationInPartialView class=""field-validation-valid"" data-valmsg-for=""MyDate"" data-valmsg-replace=""true""></ValidationInPartialView></div>

True";

            // Act
            var body = await Client.GetStringAsync("http://localhost/HtmlHelperOptions/OverrideAppWideDefaultsInView");

            // Assert
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(expected),
                body.Trim(),
                ignoreLineEndingDifferences: true);
        }
Esempio n. 16
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());
        }
Esempio n. 17
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
            }
        }
Esempio n. 18
0
        public void MergeInheritedChunks_MergesDefaultInheritedChunks()
        {
            // Arrange
            var fileProvider = new TestFileProvider();

            fileProvider.AddFile(PlatformNormalizer.NormalizePath(@"Views\_ViewImports.cshtml"),
                                 "@inject DifferentHelper<TModel> Html");
            var cache         = new DefaultChunkTreeCache(fileProvider);
            var host          = new MvcRazorHost(cache);
            var defaultChunks = new Chunk[]
            {
                new InjectChunk("MyTestHtmlHelper", "Html"),
                new UsingChunk {
                    Namespace = "AppNamespace.Model"
                },
            };
            var inheritedChunkTrees = new ChunkTree[]
            {
                new ChunkTree
                {
                    Chunks = new Chunk[]
                    {
                        new UsingChunk {
                            Namespace = "InheritedNamespace"
                        },
                        new LiteralChunk {
                            Text = "some text"
                        }
                    }
                },
                new ChunkTree
                {
                    Chunks = new Chunk[]
                    {
                        new UsingChunk {
                            Namespace = "AppNamespace.Model"
                        },
                    }
                }
            };

            var utility   = new ChunkInheritanceUtility(host, cache, defaultChunks);
            var chunkTree = new ChunkTree();

            // Act
            utility.MergeInheritedChunkTrees(chunkTree,
                                             inheritedChunkTrees,
                                             "dynamic");

            // Assert
            Assert.Equal(3, chunkTree.Chunks.Count);
            Assert.Same(inheritedChunkTrees[0].Chunks[0], chunkTree.Chunks[0]);
            Assert.Same(inheritedChunkTrees[1].Chunks[0], chunkTree.Chunks[1]);
            Assert.Same(defaultChunks[0], chunkTree.Chunks[2]);
        }
Esempio n. 19
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"]);
        }
Esempio n. 21
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));
        }
Esempio n. 22
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));
        }
        public void GetViewStartLocations_SkipsCurrentPath_IfCurrentIsViewStart(string inputPath)
        {
            // Arrange
            var expected = new[]
            {
                PlatformNormalizer.NormalizePath(@"Views\_ViewStart.cshtml"),
                @"_ViewStart.cshtml"
            };

            // Act
            var result = ViewHierarchyUtility.GetViewStartLocations(inputPath);

            // Assert
            Assert.Equal(expected, result);
        }
        public void GetViewImportsLocations_ReturnsPotentialViewStartLocations_PathStartswithSlash(string inputPath)
        {
            // Arrange
            var expected = new[]
            {
                PlatformNormalizer.NormalizePath(@"Views\Home\_ViewImports.cshtml"),
                PlatformNormalizer.NormalizePath(@"Views\_ViewImports.cshtml"),
                @"_ViewImports.cshtml"
            };

            // Act
            var result = ViewHierarchyUtility.GetViewImportsLocations(inputPath);

            // Assert
            Assert.Equal(expected, 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));
        }
Esempio n. 26
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 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));
        }
        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));
        }
Esempio n. 29
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 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));
        }