public void ValidationSummary_InvalidModel_ReturnsExpectedDiv( bool excludePropertyErrors, bool clientValidationEnabled, string expected, string ignored) { // Arrange var model = new ValidationModel(); var html = DefaultTemplatesUtilities.GetHtmlHelper(model); html.ViewContext.ClientValidationEnabled = clientValidationEnabled; html.ViewData.ModelState.AddModelError(string.Empty, "This is my validation message"); // Act var result = html.ValidationSummary( excludePropertyErrors: excludePropertyErrors, message: null, htmlAttributes: null, tag: null); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result)); }
public void LabelHelpers_ReturnEmptyForModel_IfDisplayNameEmpty() { // Arrange var provider = new TestModelMetadataProvider(); provider .ForType <DefaultTemplatesUtilities.ObjectTemplateModel>() .DisplayDetails(dd => dd.DisplayName = () => string.Empty); var helper = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider); // Act var labelResult = helper.Label(expression: string.Empty); var labelNullResult = helper.Label(expression: null); // null is another alias for current model var labelForResult = helper.LabelFor(m => m); var labelForModelResult = helper.LabelForModel(); // Assert Assert.Empty(HtmlContentUtilities.HtmlContentToString(labelResult)); Assert.Empty(HtmlContentUtilities.HtmlContentToString(labelNullResult)); Assert.Empty(HtmlContentUtilities.HtmlContentToString(labelForResult)); Assert.Empty(HtmlContentUtilities.HtmlContentToString(labelForModelResult)); }
public void CheckBoxFor_WithAttributeDictionary_GeneratesExpectedAttributes() { // Arrange var requiredMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Property1"); var expected = $@"<input data-val=""HtmlEncode[[true]]"" data-val-required=""HtmlEncode[[{requiredMessage}]]"" " + @"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" }, { "name", "-expression-" }, // overridden }; // Act var html = helper.CheckBoxFor(m => m.Property1, attributes); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html)); }
public void CheckBoxInTemplate_GetsValueFromPropertyOfViewDataEntry() { // Arrange var expected = @"<input checked=""HtmlEncode[[checked]]"" id=""HtmlEncode[[Prefix_Property1]]"" " + @"name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[checkbox]]"" value=""HtmlEncode[[true]]"" />" + @"<input name=""HtmlEncode[[Prefix.Property1]]"" type=""HtmlEncode[[hidden]]"" value=""HtmlEncode[[false]]"" />"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(GetTestModelViewData()); helper.ViewContext.ClientValidationEnabled = false; helper.ViewData.Remove(nameof(TestModel.Property1)); helper.ViewData["Prefix"] = new TestModel { Property1 = true }; helper.ViewData.Model = new TestModel(); helper.ViewData.TemplateInfo.HtmlFieldPrefix = "Prefix"; // Act var html = helper.CheckBox("Property1", isChecked: null, htmlAttributes: null); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html)); }
public void DropDownList_FindsSelectList_UsesOptionLabel() { // Arrange var expectedHtml = "<select id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\">" + "<option value=\"\">HtmlEncode[[--select--]]</option>" + Environment.NewLine + "<option value=\"HtmlEncode[[0]]\">HtmlEncode[[Zero]]</option>" + Environment.NewLine + "<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[1]]\">HtmlEncode[[One]]</option>" + Environment.NewLine + "<option value=\"HtmlEncode[[2]]\">HtmlEncode[[Two]]</option>" + Environment.NewLine + "<option value=\"HtmlEncode[[3]]\">HtmlEncode[[Three]]</option>" + Environment.NewLine + "</select>"; var metadataProvider = new EmptyModelMetadataProvider(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary <TestModel>(metadataProvider)); helper.ViewContext.ClientValidationEnabled = false; helper.ViewData.ModelState.SetModelValue("Property1", 1, "1"); helper.ViewData["Property1"] = BasicSelectList; // Act var dropDownListResult = helper.DropDownList("Property1", "--select--"); // Assert Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(dropDownListResult)); }
public async Task ProcessAsync_SuppressesOutput_IfClientSideValiationDisabled_WithNoErrorsData( ModelStateDictionary modelStateDictionary) { // Arrange var metadataProvider = new TestModelMetadataProvider(); var htmlGenerator = new TestableHtmlGenerator(metadataProvider); var viewContext = CreateViewContext(); viewContext.ClientValidationEnabled = false; var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator) { ValidationSummary = ValidationSummary.All, ViewContext = viewContext, }; var output = new TagHelperOutput( "div", new TagHelperAttributeList(), (useCachedResult, encoder) => { throw new InvalidOperationException("getChildContentAsync called unexpectedly."); }); var context = new TagHelperContext( new TagHelperAttributeList(), items: new Dictionary <object, object>(), uniqueId: "test"); // Act await validationSummaryTagHelper.ProcessAsync(context, output); // Assert Assert.Null(output.TagName); Assert.Empty(output.Attributes); Assert.Empty(HtmlContentUtilities.HtmlContentToString(output)); }
public async Task CheckBoxHandlesMultipleAttributesSameNameCorrectly( TagHelperAttributeList outputAttributes, string expectedAttributeString) { // Arrange var originalContent = "original content"; var originalTagName = "not-input"; var expectedContent = $"{originalContent}<input {expectedAttributeString} id=\"HtmlEncode[[IsACar]]\" " + "name=\"HtmlEncode[[IsACar]]\" type=\"HtmlEncode[[checkbox]]\" value=\"HtmlEncode[[true]]\" />" + "<input name=\"HtmlEncode[[IsACar]]\" type=\"HtmlEncode[[hidden]]\" value=\"HtmlEncode[[false]]\" />"; var context = new TagHelperContext( allAttributes: new TagHelperAttributeList( Enumerable.Empty <TagHelperAttribute>()), items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( originalTagName, outputAttributes, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult <TagHelperContent>(result: null)) { TagMode = TagMode.SelfClosing, }; output.Content.AppendHtml(originalContent); var htmlGenerator = new TestableHtmlGenerator(new EmptyModelMetadataProvider()); var tagHelper = GetTagHelper(htmlGenerator, model: false, propertyName: nameof(Model.IsACar)); // Act await tagHelper.ProcessAsync(context, output); // Assert Assert.Empty(output.Attributes); // Moved to Content and cleared Assert.Equal(expectedContent, HtmlContentUtilities.HtmlContentToString(output.Content)); Assert.Equal(TagMode.SelfClosing, output.TagMode); Assert.Null(output.TagName); // Cleared }
public void DropDownListFor_NullSelectListFindsListFromViewData() { // Arrange var expectedHtml = "<select id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\">" + "<option selected=\"HtmlEncode[[selected]]\" value=\"HtmlEncode[[0]]\">HtmlEncode[[Zero]]</option>" + Environment.NewLine + "<option value=\"HtmlEncode[[1]]\">HtmlEncode[[One]]</option>" + Environment.NewLine + "<option value=\"HtmlEncode[[2]]\">HtmlEncode[[Two]]</option>" + Environment.NewLine + "<option value=\"HtmlEncode[[3]]\">HtmlEncode[[Three]]</option>" + Environment.NewLine + "</select>"; var metadataProvider = new EmptyModelMetadataProvider(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary <TestModel>(metadataProvider)); helper.ViewContext.ClientValidationEnabled = false; helper.ViewData["Property1"] = BasicSelectList; helper.ViewData.Model = new TestModel { Property1 = 0 }; // Act var dropDownListForResult = helper.DropDownListFor(m => m.Property1, selectList: null); // Assert Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(dropDownListForResult)); }
public void CheckBoxFor_UsesModelStateAttemptedValue(string attemptedValue, 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(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(viewData); var valueProviderResult = new ValueProviderResult(attemptedValue, attemptedValue, CultureInfo.InvariantCulture); viewData.ModelState.SetModelValue("Property1", valueProviderResult); // Act var html = helper.CheckBoxFor(m => m.Property1, htmlAttributes: null); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(html)); }
public void DisplayFor_FindsModel_EvenIfNullOrEmpty(string propertyValue) { // Arrange var model = new DefaultTemplatesUtilities.ObjectTemplateModel { Property1 = propertyValue, }; var viewEngine = new Mock <ICompositeViewEngine>(MockBehavior.Strict); viewEngine .Setup(v => v.GetView(/*executingFilePath*/ null, It.IsAny <string>(), /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty <string>())); viewEngine .Setup(v => v.FindView(It.IsAny <ActionContext>(), It.IsAny <string>(), /*isMainPage*/ false)) .Returns(ViewEngineResult.NotFound(string.Empty, Enumerable.Empty <string>())); var helper = DefaultTemplatesUtilities.GetHtmlHelper(model, viewEngine.Object); helper.ViewData["Property1"] = "ViewData string"; // Act var result = helper.DisplayFor(m => m.Property1); // Assert Assert.Equal(string.Empty, HtmlContentUtilities.HtmlContentToString(result)); }
public void LabelHelpers_ReturnExpectedElementForModel_IfDisplayNameEmpty_WithEmptyLabelText() { // Arrange var expectedLabel = "<label for=\"\"></label>"; var provider = new TestModelMetadataProvider(); provider .ForType <DefaultTemplatesUtilities.ObjectTemplateModel>() .DisplayDetails(dd => dd.DisplayName = () => string.Empty); var helper = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider); // Act var labelResult = helper.Label(expression: string.Empty, labelText: string.Empty); var labelNullResult = helper.Label(expression: null, labelText: string.Empty); var labelForResult = helper.LabelFor(m => m, labelText: string.Empty); var labelForModelResult = helper.LabelForModel(labelText: string.Empty); // Assert Assert.Equal(expectedLabel, HtmlContentUtilities.HtmlContentToString(labelResult)); Assert.Equal(expectedLabel, HtmlContentUtilities.HtmlContentToString(labelNullResult)); Assert.Equal(expectedLabel, HtmlContentUtilities.HtmlContentToString(labelForResult)); Assert.Equal(expectedLabel, HtmlContentUtilities.HtmlContentToString(labelForModelResult)); }
public void TextBoxFor_ComplexExpressions_UsesModelStateValueForComplexExpressions( Expression <Func <ComplexModel, string> > expression, string expected) { // Arrange var model = new ComplexModel(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(model); helper.ViewData.TemplateInfo.HtmlFieldPrefix = "pre"; helper.ViewData.ModelState.SetModelValue("pre.Property3[key]", "MProp3Val", "MProp3Val"); helper.ViewData.ModelState.SetModelValue("pre.Property4.Property5", "MProp5Val", "MProp5Val"); helper.ViewData.ModelState.SetModelValue("pre.Property4.Property6[0]", "MProp6Val", "MProp6Val"); helper.ViewData.Model.Property3["key"] = "Prop3Val"; helper.ViewData.Model.Property4.Property5 = "Prop5Val"; helper.ViewData.Model.Property4.Property6.Add("Prop6Val"); // Act var result = helper.TextBoxFor(expression); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result)); }
public void RendersScriptTagsForGlobbedSrcResults() { // Arrange var expectedContent = "<script src=\"HtmlEncode[[/js/site.js]]\"></script>" + "<script src=\"HtmlEncode[[/common.js]]\"></script>"; var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { new TagHelperAttribute("src", "/js/site.js"), new TagHelperAttribute("asp-src-include", "**/*.js") }); var output = MakeTagHelperOutput("script", attributes: new TagHelperAttributeList()); var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>( new TestFileProvider(), Mock.Of <IMemoryCache>(), PathString.Empty); globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/*.js", null)) .Returns(new[] { "/common.js" }); var helper = GetHelper(); helper.GlobbingUrlBuilder = globbingUrlBuilder.Object; helper.Src = "/js/site.js"; helper.SrcInclude = "**/*.js"; // Act helper.Process(context, output); // Assert Assert.Equal("script", output.TagName); Assert.Equal("/js/site.js", output.Attributes["src"].Value); var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder()); Assert.Equal(expectedContent, content); }
public void Label_DisplaysRightmostExpressionSegment_IfPropertiesNotFound( string expression, string expectedText, string expectedId) { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act var result = helper.Label(expression); // Assert // Label() falls back to expression name when DisplayName and PropertyName are null. Assert.Equal("<label for=\"HtmlEncode[[" + expectedId + "]]\">HtmlEncode[[" + expectedText + "]]</label>", HtmlContentUtilities.HtmlContentToString(result)); }
public void LabelHelpers_DisplayDisplayNameForProperty_IfNonNull(string displayName) { // Arrange var provider = new TestModelMetadataProvider(); provider .ForProperty <DefaultTemplatesUtilities.ObjectTemplateModel>("Property1") .DisplayDetails(dd => dd.DisplayName = () => displayName); var helper = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider); // Act var labelResult = helper.Label("Property1"); var labelForResult = helper.LabelFor(m => m.Property1); // Assert Assert.Equal("<label for=\"HtmlEncode[[Property1]]\">HtmlEncode[[" + displayName + "]]</label>", HtmlContentUtilities.HtmlContentToString(labelResult)); Assert.Equal("<label for=\"HtmlEncode[[Property1]]\">HtmlEncode[[" + displayName + "]]</label>", HtmlContentUtilities.HtmlContentToString(labelForResult)); }
public void LabelHelpers_Label_Evaluates_Expression() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); helper.ViewData["value"] = "testvalue"; // Act var labelResult = helper.Label(expression: "value"); // Assert Assert.Equal("<label for=\"HtmlEncode[[value]]\">HtmlEncode[[value]]</label>", HtmlContentUtilities.HtmlContentToString(labelResult)); }
public async Task ProcessAsync_GeneratesExpectedOutput( object model, Type containerType, Func <object> modelAccessor, string propertyPath, TagHelperOutputContent tagHelperOutputContent) { // Arrange var expectedTagName = "not-label"; var expectedAttributes = new TagHelperAttributeList { { "class", "form-control" }, { "for", tagHelperOutputContent.ExpectedId } }; var metadataProvider = new TestModelMetadataProvider(); var containerMetadata = metadataProvider.GetMetadataForType(containerType); var containerExplorer = metadataProvider.GetModelExplorerForType(containerType, model); var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text"); var modelExplorer = containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor()); var htmlGenerator = new TestableHtmlGenerator(metadataProvider); var modelExpression = new ModelExpression(propertyPath, modelExplorer); var tagHelper = new LabelTagHelper(htmlGenerator) { For = modelExpression, }; var expectedPreContent = "original pre-content"; var expectedPostContent = "original post-content"; var tagHelperContext = new TagHelperContext( tagName: "not-label", allAttributes: new TagHelperAttributeList(), items: new Dictionary <object, object>(), uniqueId: "test"); var htmlAttributes = new TagHelperAttributeList { { "class", "form-control" }, }; var output = new TagHelperOutput( expectedTagName, htmlAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.AppendHtml(tagHelperOutputContent.OriginalChildContent); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }); output.PreContent.AppendHtml(expectedPreContent); output.PostContent.AppendHtml(expectedPostContent); // LabelTagHelper checks IsContentModified so we don't want to forcibly set it if // tagHelperOutputContent.OriginalContent is going to be null or empty. if (!string.IsNullOrEmpty(tagHelperOutputContent.OriginalContent)) { output.Content.AppendHtml(tagHelperOutputContent.OriginalContent); } var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider); tagHelper.ViewContext = viewContext; // Act await tagHelper.ProcessAsync(tagHelperContext, output); // Assert Assert.Equal(expectedAttributes, output.Attributes); Assert.Equal(expectedPreContent, output.PreContent.GetContent()); Assert.Equal( tagHelperOutputContent.ExpectedContent, HtmlContentUtilities.HtmlContentToString(output.Content)); Assert.Equal(expectedPostContent, output.PostContent.GetContent()); Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode); Assert.Equal(expectedTagName, output.TagName); }
public void RenderScriptTags_FallbackSrc_WithFileVersion_EncodesAsExpected() { // Arrange var expectedContent = "<script encoded=\"contains "quotes"\" literal=\"HtmlEncode[[all HTML encoded]]\" " + "mixed=\"HtmlEncode[[HTML encoded]] and contains "quotes"\" " + "src=\"HtmlEncode[[/js/site.js?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]\"></script>" + Environment.NewLine + "<script>(isavailable()||document.write(\"<script " + "JavaScriptEncode[[encoded]]=\\\"JavaScriptEncode[[contains "quotes"]]\\\" " + "JavaScriptEncode[[literal]]=\\\"JavaScriptEncode[[HtmlEncode[[all HTML encoded]]]]\\\" " + "JavaScriptEncode[[mixed]]=\\\"JavaScriptEncode[[HtmlEncode[[HTML encoded]] and contains "quotes"]]\\\" " + "src=\\\"JavaScriptEncode[[HtmlEncode[[fallback.js?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]]]\\\">" + "<\\/script>\"));</script>"; var mixed = new DefaultTagHelperContent(); mixed.Append("HTML encoded"); mixed.AppendHtml(" and contains \"quotes\""); var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { { "asp-append-version", "true" }, { "asp-fallback-src-include", "fallback.js" }, { "asp-fallback-test", "isavailable()" }, { "encoded", new HtmlString("contains \"quotes\"") }, { "literal", "all HTML encoded" }, { "mixed", mixed }, { "src", "/js/site.js" }, }); var output = MakeTagHelperOutput( "script", attributes: new TagHelperAttributeList { { "encoded", new HtmlString("contains \"quotes\"") }, { "literal", "all HTML encoded" }, { "mixed", mixed }, }); var hostingEnvironment = MakeHostingEnvironment(); var viewContext = MakeViewContext(); var helper = new ScriptTagHelper( MakeHostingEnvironment(), MakeCache(), new HtmlTestEncoder(), new JavaScriptTestEncoder(), MakeUrlHelperFactory()) { AppendVersion = true, FallbackSrc = "fallback.js", FallbackTestExpression = "isavailable()", Src = "/js/site.js", ViewContext = viewContext, }; // Act helper.Process(context, output); // Assert Assert.Equal("script", output.TagName); Assert.Equal("/js/site.js?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk", output.Attributes["src"].Value); var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder()); Assert.Equal(expectedContent, content); }
public void LabelForModel_DisplaysSpecifiedHtmlAttributes() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act var labelForModelResult = helper.LabelForModel(labelText: "Hello", htmlAttributes: new { attr = "value" }); // Assert Assert.Equal("<label attr=\"HtmlEncode[[value]]\" for=\"\">HtmlEncode[[Hello]]</label>", HtmlContentUtilities.HtmlContentToString(labelForModelResult)); }
public void LabelHelpers_DisplayMetadataPropertyNameForProperty() { // Arrange var propertyName = "Property1"; var provider = new EmptyModelMetadataProvider(); var modelExplorer = provider .GetModelExplorerForType(typeof(DefaultTemplatesUtilities.ObjectTemplateModel), model: null) .GetExplorerForProperty(propertyName); var helper = DefaultTemplatesUtilities.GetHtmlHelper(); helper.ViewData.ModelExplorer = modelExplorer; // Act var labelResult = helper.Label(expression: string.Empty); var labelForResult = helper.LabelFor(m => m); var labelForModelResult = helper.LabelForModel(); // Assert Assert.Equal("<label for=\"\">HtmlEncode[[" + propertyName + "]]</label>", HtmlContentUtilities.HtmlContentToString(labelResult)); Assert.Equal("<label for=\"\">HtmlEncode[[" + propertyName + "]]</label>", HtmlContentUtilities.HtmlContentToString(labelForResult)); Assert.Equal("<label for=\"\">HtmlEncode[[" + propertyName + "]]</label>", HtmlContentUtilities.HtmlContentToString(labelForModelResult)); }
public void RendersLinkTagsForGlobbedHrefResults_EncodesAsExpected() { // Arrange var expectedContent = "<link encoded='contains \"quotes\"' href=\"HtmlEncode[[/css/site.css]]\" " + "literal=\"HtmlEncode[[all HTML encoded]]\" " + "mixed='HtmlEncode[[HTML encoded]] and contains \"quotes\"' />" + "<link encoded='contains \"quotes\"' href=\"HtmlEncode[[/base.css]]\" " + "literal=\"HtmlEncode[[all HTML encoded]]\" " + "mixed='HtmlEncode[[HTML encoded]] and contains \"quotes\"' />"; var mixed = new DefaultTagHelperContent(); mixed.Append("HTML encoded"); mixed.AppendHtml(" and contains \"quotes\""); var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { { "asp-href-include", "**/*.css" }, { new TagHelperAttribute("encoded", new HtmlString("contains \"quotes\""), HtmlAttributeValueStyle.SingleQuotes) }, { "href", "/css/site.css" }, { "literal", "all HTML encoded" }, { new TagHelperAttribute("mixed", mixed, HtmlAttributeValueStyle.SingleQuotes) }, }); var output = MakeTagHelperOutput( "link", attributes: new TagHelperAttributeList { { new TagHelperAttribute("encoded", new HtmlString("contains \"quotes\""), HtmlAttributeValueStyle.SingleQuotes) }, { "literal", "all HTML encoded" }, { new TagHelperAttribute("mixed", mixed, HtmlAttributeValueStyle.SingleQuotes) }, }); var hostingEnvironment = MakeHostingEnvironment(); var viewContext = MakeViewContext(); var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>( new TestFileProvider(), Mock.Of <IMemoryCache>(), PathString.Empty); globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/*.css", null)) .Returns(new[] { "/base.css" }); var helper = new LinkTagHelper( hostingEnvironment, MakeCache(), new HtmlTestEncoder(), new JavaScriptTestEncoder(), MakeUrlHelperFactory()) { GlobbingUrlBuilder = globbingUrlBuilder.Object, Href = "/css/site.css", HrefInclude = "**/*.css", ViewContext = viewContext, }; // Act helper.Process(context, output); // Assert Assert.Equal("link", output.TagName); Assert.Equal("/css/site.css", output.Attributes["href"].Value); var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder()); Assert.Equal(expectedContent, content); }
public async Task ProcessAsync_GeneratesExpectedOutput_WithDisplayName( string displayName, string originalChildContent, string htmlFieldPrefix, string expectedContent, string expectedId) { // Arrange var expectedAttributes = new TagHelperAttributeList { { "for", expectedId } }; var name = nameof(NestedModel.Text); var metadataProvider = new TestModelMetadataProvider(); metadataProvider .ForProperty <NestedModel>(name) .DisplayDetails(metadata => metadata.DisplayName = () => displayName); var htmlGenerator = new TestableHtmlGenerator(metadataProvider); var viewContext = TestableHtmlGenerator.GetViewContext( model: null, htmlGenerator: htmlGenerator, metadataProvider: metadataProvider); var viewData = new ViewDataDictionary <NestedModel>(metadataProvider, viewContext.ModelState); viewData.TemplateInfo.HtmlFieldPrefix = htmlFieldPrefix; viewContext.ViewData = viewData; var containerExplorer = metadataProvider.GetModelExplorerForType(typeof(NestedModel), model: null); var modelExplorer = containerExplorer.GetExplorerForProperty(name); var modelExpression = new ModelExpression(name, modelExplorer); var tagHelper = new LabelTagHelper(htmlGenerator) { For = modelExpression, ViewContext = viewContext, }; var tagHelperContext = new TagHelperContext( tagName: "label", allAttributes: new TagHelperAttributeList(), items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( "label", new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.AppendHtml(originalChildContent); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }); // Act await tagHelper.ProcessAsync(tagHelperContext, output); // Assert Assert.Equal(expectedAttributes, output.Attributes); Assert.Equal(expectedContent, HtmlContentUtilities.HtmlContentToString(output.Content)); }
private void AssertHtmlContentEquals(string expected, IHtmlContent actual) { Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(actual, _encoder)); }
public async Task ProcessAsync_CallsGenerateCheckBox_WithExpectedParameters() { // Arrange var originalContent = "original content"; var originalTagName = "not-input"; var expectedPreContent = "original pre-content"; var expectedContent = originalContent + "<input class=\"HtmlEncode[[form-control]]\" /><hidden />"; var expectedPostContent = "original post-content"; var context = new TagHelperContext( allAttributes: new TagHelperAttributeList( Enumerable.Empty <TagHelperAttribute>()), items: new Dictionary <object, object>(), uniqueId: "test"); var originalAttributes = new TagHelperAttributeList { { "class", "form-control" }, }; var output = new TagHelperOutput( originalTagName, originalAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }) { TagMode = TagMode.SelfClosing, }; output.PreContent.AppendHtml(expectedPreContent); output.Content.AppendHtml(originalContent); output.PostContent.AppendHtml(expectedPostContent); var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var tagHelper = GetTagHelper(htmlGenerator.Object, model: false, propertyName: nameof(Model.IsACar)); var tagBuilder = new TagBuilder("input") { Attributes = { { "class", "form-control" }, }, TagRenderMode = TagRenderMode.SelfClosing }; htmlGenerator .Setup(mock => mock.GenerateCheckBox( tagHelper.ViewContext, tagHelper.For.ModelExplorer, tagHelper.For.Name, null, // isChecked It.IsAny <object>())) // htmlAttributes .Returns(tagBuilder) .Verifiable(); htmlGenerator .Setup(mock => mock.GenerateHiddenForCheckbox( tagHelper.ViewContext, tagHelper.For.ModelExplorer, tagHelper.For.Name)) .Returns(new TagBuilder("hidden") { TagRenderMode = TagRenderMode.SelfClosing }) .Verifiable(); // Act await tagHelper.ProcessAsync(context, output); // Assert htmlGenerator.Verify(); Assert.Empty(output.Attributes); // Moved to Content and cleared Assert.Equal(expectedPreContent, output.PreContent.GetContent()); Assert.Equal(expectedContent, HtmlContentUtilities.HtmlContentToString(output.Content)); Assert.Equal(expectedPostContent, output.PostContent.GetContent()); Assert.Equal(TagMode.SelfClosing, output.TagMode); Assert.Null(output.TagName); // Cleared }
public async Task Process_GeneratesExpectedOutput( object container, Type containerType, object model, NameAndId nameAndId, string expectedContent) { // Arrange var expectedAttributes = new TagHelperAttributeList { { "class", "form-control" }, { "id", nameAndId.Id }, { "name", nameAndId.Name }, { "valid", "from validation attributes" }, }; var expectedTagName = "not-textarea"; var metadataProvider = new TestModelMetadataProvider(); var containerMetadata = metadataProvider.GetMetadataForType(containerType); var containerExplorer = metadataProvider.GetModelExplorerForType(containerType, container); var propertyMetadata = metadataProvider.GetMetadataForProperty(containerType, "Text"); var modelExplorer = containerExplorer.GetExplorerForExpression(propertyMetadata, model); var htmlGenerator = new TestableHtmlGenerator(metadataProvider) { ValidationAttributes = { { "valid", "from validation attributes" }, } }; // Property name is either nameof(Model.Text) or nameof(NestedModel.Text). var modelExpression = new ModelExpression(nameAndId.Name, modelExplorer); var tagHelper = new TextAreaTagHelper(htmlGenerator) { For = modelExpression, }; var tagHelperContext = new TagHelperContext( tagName: "text-area", allAttributes: new TagHelperAttributeList( Enumerable.Empty <TagHelperAttribute>()), items: new Dictionary <object, object>(), uniqueId: "test"); var htmlAttributes = new TagHelperAttributeList { { "class", "form-control" }, }; var output = new TagHelperOutput( expectedTagName, htmlAttributes, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }) { TagMode = TagMode.SelfClosing, }; output.Content.SetContent("original content"); var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider); tagHelper.ViewContext = viewContext; // Act await tagHelper.ProcessAsync(tagHelperContext, output); // Assert Assert.Equal(TagMode.SelfClosing, output.TagMode); Assert.Equal(expectedAttributes, output.Attributes); Assert.Equal(expectedContent, HtmlContentUtilities.HtmlContentToString(output.Content)); Assert.Equal(expectedTagName, output.TagName); }
public void LabelFor_DisplaysVariableName() { // Arrange var unknownKey = "this is a dummy parameter value"; var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act var result = helper.LabelFor(model => unknownKey); // Assert Assert.Equal("<label for=\"HtmlEncode[[unknownKey]]\">HtmlEncode[[unknownKey]]</label>", HtmlContentUtilities.HtmlContentToString(result)); }
public void LabelFor_UsesSpecifiedLabelText() { // Arrange var helper = DefaultTemplatesUtilities.GetHtmlHelper(); // Act var labelForResult = helper.LabelFor(m => m.Property1, labelText: "Hello"); // Assert Assert.Equal("<label for=\"HtmlEncode[[Property1]]\">HtmlEncode[[Hello]]</label>", HtmlContentUtilities.HtmlContentToString(labelForResult)); }
public void RenderLinkTags_FallbackHref_WithFileVersion_EncodesAsExpected() { // Arrange var expectedContent = "<link encoded=\"contains \"quotes\"\" " + "href=\"HtmlEncode[[/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]\" " + "literal=\"HtmlEncode[[all HTML encoded]]\" " + "mixed=\"HtmlEncode[[HTML encoded]] and contains \"quotes\"\" rel=\"stylesheet\" />" + Environment.NewLine + "<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"HtmlEncode[[hidden]]\" /><script>" + "!function(a,b,c,d){var e,f=document,g=f.getElementsByTagName(\"SCRIPT\"),h=g[g.length-1]." + "previousElementSibling,i=f.defaultView&&f.defaultView.getComputedStyle?f.defaultView." + "getComputedStyle(h):h.currentStyle;if(i&&i[a]!==b)for(e=0;e<c.length;e++)f.write('<link " + "href=\"'+c[e]+'\" '+d+\"/>\")}(\"JavaScriptEncode[[visibility]]\",\"JavaScriptEncode[[hidden]]\"," + "[\"JavaScriptEncode[[HtmlEncode[[/fallback.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]]]\"], " + "\"JavaScriptEncode[[encoded=\"contains \"quotes\"\" literal=\"HtmlEncode[[all HTML encoded]]\" " + "mixed=\"HtmlEncode[[HTML encoded]] and contains \"quotes\"\" rel=\"stylesheet\" ]]\");" + "</script>"; var mixed = new DefaultTagHelperContent(); mixed.Append("HTML encoded"); mixed.AppendHtml(" and contains \"quotes\""); var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { { "asp-append-version", "true" }, { "asp-fallback-href-include", "**/fallback.css" }, { "asp-fallback-test-class", "hidden" }, { "asp-fallback-test-property", "visibility" }, { "asp-fallback-test-value", "hidden" }, { "encoded", new HtmlString("contains \"quotes\"") }, { "href", "/css/site.css" }, { "literal", "all HTML encoded" }, { "mixed", mixed }, { "rel", new HtmlString("stylesheet") }, }); var output = MakeTagHelperOutput( "link", attributes: new TagHelperAttributeList { { "encoded", new HtmlString("contains \"quotes\"") }, { "literal", "all HTML encoded" }, { "mixed", mixed }, { "rel", new HtmlString("stylesheet") }, }); var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>( new TestFileProvider(), Mock.Of <IMemoryCache>(), PathString.Empty); globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/fallback.css", null)) .Returns(new[] { "/fallback.css" }); var helper = GetHelper(); helper.AppendVersion = true; helper.FallbackHrefInclude = "**/fallback.css"; helper.FallbackTestClass = "hidden"; helper.FallbackTestProperty = "visibility"; helper.FallbackTestValue = "hidden"; helper.GlobbingUrlBuilder = globbingUrlBuilder.Object; helper.Href = "/css/site.css"; // Act helper.Process(context, output); // Assert Assert.Equal("link", output.TagName); Assert.Equal("/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk", output.Attributes["href"].Value); var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder()); Assert.Equal(expectedContent, content); }
public async Task ProcessAsync_GeneratesExpectedOutput() { // Arrange var expectedTagName = "not-form"; var metadataProvider = new TestModelMetadataProvider(); var tagHelperContext = new TagHelperContext( tagName: "form", allAttributes: new TagHelperAttributeList { { "id", "myform" }, { "asp-route-name", "value" }, { "asp-action", "index" }, { "asp-controller", "home" }, { "method", "post" }, { "asp-antiforgery", true } }, items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( expectedTagName, attributes: new TagHelperAttributeList { { "id", "myform" }, }, getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something Else"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }); output.PostContent.SetContent("Something"); var urlHelper = new Mock <IUrlHelper>(); urlHelper .Setup(mock => mock.Action(It.IsAny <UrlActionContext>())).Returns("home/index"); var htmlGenerator = new TestableHtmlGenerator(metadataProvider, urlHelper.Object); var viewContext = TestableHtmlGenerator.GetViewContext( model: null, htmlGenerator: htmlGenerator, metadataProvider: metadataProvider); var expectedPostContent = "Something" + HtmlContentUtilities.HtmlContentToString( htmlGenerator.GenerateAntiforgery(viewContext), HtmlEncoder.Default); var formTagHelper = new FormTagHelper(htmlGenerator) { Action = "index", Antiforgery = true, Controller = "home", ViewContext = viewContext, RouteValues = { { "name", "value" }, }, }; // Act await formTagHelper.ProcessAsync(tagHelperContext, output); // Assert Assert.Equal(3, output.Attributes.Count); var attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("id")); Assert.Equal("myform", attribute.Value); attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("method")); Assert.Equal("post", attribute.Value); attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("action")); Assert.Equal("home/index", attribute.Value); Assert.Empty(output.PreContent.GetContent()); Assert.True(output.Content.GetContent().Length == 0); Assert.Equal(expectedPostContent, output.PostContent.GetContent()); Assert.Equal(expectedTagName, output.TagName); }
public void RendersScriptTagsForGlobbedSrcResults_EncodesAsExpected() { // Arrange var expectedContent = "<script encoded=\"contains "quotes"\" literal=\"HtmlEncode[[all HTML encoded]]\" " + "mixed=\"HtmlEncode[[HTML encoded]] and contains "quotes"\" " + "src=\"HtmlEncode[[/js/site.js]]\"></script>" + "<script encoded=\"contains "quotes"\" literal=\"HtmlEncode[[all HTML encoded]]\" " + "mixed=\"HtmlEncode[[HTML encoded]] and contains "quotes"\" " + "src=\"HtmlEncode[[/common.js]]\"></script>"; var mixed = new DefaultTagHelperContent(); mixed.Append("HTML encoded"); mixed.AppendHtml(" and contains \"quotes\""); var context = MakeTagHelperContext( attributes: new TagHelperAttributeList { { "asp-src-include", "**/*.js" }, { "encoded", new HtmlString("contains \"quotes\"") }, { "literal", "all HTML encoded" }, { "mixed", mixed }, { "src", "/js/site.js" }, }); var output = MakeTagHelperOutput( "script", attributes: new TagHelperAttributeList { { "encoded", new HtmlString("contains \"quotes\"") }, { "literal", "all HTML encoded" }, { "mixed", mixed }, }); var hostingEnvironment = MakeHostingEnvironment(); var viewContext = MakeViewContext(); var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>( new TestFileProvider(), Mock.Of <IMemoryCache>(), PathString.Empty); globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/*.js", null)) .Returns(new[] { "/common.js" }); var helper = new ScriptTagHelper( hostingEnvironment, MakeCache(), new HtmlTestEncoder(), new JavaScriptTestEncoder(), MakeUrlHelperFactory()) { GlobbingUrlBuilder = globbingUrlBuilder.Object, Src = "/js/site.js", SrcInclude = "**/*.js", ViewContext = viewContext, }; // Act helper.Process(context, output); // Assert Assert.Equal("script", output.TagName); Assert.Equal("/js/site.js", output.Attributes["src"].Value); var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder()); Assert.Equal(expectedContent, content); }