Ejemplo n.º 1
0
        public static string HtmlContentToString(IHtmlContent content, IHtmlEncoder encoder = null)
        {
            if (encoder == null)
            {
                encoder = new CommonTestEncoder();
            }

            using (var writer = new StringWriter())
            {
                content.WriteTo(writer, encoder);
                return(writer.ToString());
            }
        }
Ejemplo n.º 2
0
        public static string HtmlContentToString(IHtmlContent content, IHtmlEncoder encoder = null)
        {
            if (encoder == null)
            {
                encoder = new CommonTestEncoder();
            }

            using (var writer = new StringWriter())
            {
                content.WriteTo(writer, encoder);
                return writer.ToString();
            }
        }
Ejemplo n.º 3
0
        public void Activate_InstantiatesNewViewDataDictionaryType_IfTheTypeDoesNotMatch()
        {
            // Arrange
            var activator = new RazorPageActivator(new EmptyModelMetadataProvider());
            var instance  = new TestRazorPage();

            var myService       = new MyService();
            var helper          = Mock.Of <IHtmlHelper <object> >();
            var htmlEncoder     = new CommonTestEncoder();
            var serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.Setup(p => p.GetService(typeof(MyService)))
            .Returns(myService);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlHelper <object>)))
            .Returns(helper);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlEncoder)))
            .Returns(htmlEncoder);
            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(c => c.RequestServices)
            .Returns(serviceProvider.Object);

            var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
            var viewData      = new ViewDataDictionary <object>(new EmptyModelMetadataProvider())
            {
                Model = new MyModel()
            };
            var viewContext = new ViewContext(actionContext,
                                              Mock.Of <IView>(),
                                              viewData,
                                              Mock.Of <ITempDataDictionary>(),
                                              TextWriter.Null,
                                              new HtmlHelperOptions());

            // Act
            activator.Activate(instance, viewContext);

            // Assert
            Assert.IsType <ViewDataDictionary <MyModel> >(viewContext.ViewData);
        }
Ejemplo n.º 4
0
        public void Activate_ActivatesAndContextualizesPropertiesOnViews()
        {
            // Arrange
            var activator = new RazorPageActivator(new EmptyModelMetadataProvider());
            var instance  = new TestRazorPage();

            var myService       = new MyService();
            var helper          = Mock.Of <IHtmlHelper <object> >();
            var htmlEncoder     = new CommonTestEncoder();
            var serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.Setup(p => p.GetService(typeof(MyService)))
            .Returns(myService);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlHelper <object>)))
            .Returns(helper);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlEncoder)))
            .Returns(htmlEncoder);
            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(c => c.RequestServices)
            .Returns(serviceProvider.Object);

            var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
            var viewContext   = new ViewContext(actionContext,
                                                Mock.Of <IView>(),
                                                new ViewDataDictionary(new EmptyModelMetadataProvider()),
                                                Mock.Of <ITempDataDictionary>(),
                                                TextWriter.Null,
                                                new HtmlHelperOptions());

            // Act
            activator.Activate(instance, viewContext);

            // Assert
            Assert.Same(helper, instance.Html);
            Assert.Same(myService, instance.MyService);
            Assert.Same(viewContext, myService.ViewContext);
            Assert.Null(instance.MyService2);
        }
Ejemplo n.º 5
0
        public void Activate_DeterminesModelTypeFromProperty()
        {
            // Arrange
            var activator       = new RazorPageActivator(new EmptyModelMetadataProvider());
            var instance        = new DoesNotDeriveFromRazorPageOfTButHasModelProperty();
            var myService       = new MyService();
            var helper          = Mock.Of <IHtmlHelper <object> >();
            var htmlEncoder     = new CommonTestEncoder();
            var serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.Setup(p => p.GetService(typeof(MyService)))
            .Returns(myService);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlHelper <object>)))
            .Returns(helper);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlEncoder)))
            .Returns(htmlEncoder);
            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(c => c.RequestServices)
            .Returns(serviceProvider.Object);

            var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
            var viewData      = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var viewContext   = new ViewContext(actionContext,
                                                Mock.Of <IView>(),
                                                viewData,
                                                Mock.Of <ITempDataDictionary>(),
                                                TextWriter.Null,
                                                new HtmlHelperOptions());

            // Act
            activator.Activate(instance, viewContext);

            // Assert
            Assert.IsType <ViewDataDictionary <string> >(viewContext.ViewData);
        }
Ejemplo n.º 6
0
        public async Task RenderAsync_DoesNotCopyContentOnceRazorTextWriterIsNoLongerBuffering()
        {
            // Arrange
            var htmlEncoder = new CommonTestEncoder();
            var expected = "HtmlEncode[[layout-1" +
                           Environment.NewLine +
                           "]]body content" +
                           Environment.NewLine +
                           "section-content-1" +
                           Environment.NewLine +
                           "section-content-2";

            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "layout-1";
                v.WriteLiteral("body content" + Environment.NewLine);
                v.DefineSection("foo", async _ =>
                {
                    v.WriteLiteral("section-content-1" + Environment.NewLine);
                    await v.FlushAsync();
                    v.WriteLiteral("section-content-2");
                });
            });

            var layout1 = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("layout-1" + Environment.NewLine);
                v.RenderBodyPublic();
                v.Write(v.RenderSection("foo"));
            });

            var viewEngine = new Mock<IRazorViewEngine>();
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "layout-1"))
                       .Returns(new RazorPageResult("layout-1", layout1));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of<IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     new CommonTestEncoder(),
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Ejemplo n.º 7
0
        public async Task RenderAsync_ExecutesNestedLayoutsWithNestedSections()
        {
            // Arrange
            var htmlEncoder = new CommonTestEncoder();
            var expected = "HtmlEncode[[BaseLayout" +
                           Environment.NewLine +
                           "]]HtmlEncode[[NestedLayout" +
                           Environment.NewLine +
                           "]]BodyContent" +
                           "foo-content" +
                           Environment.NewLine +
                           "HtmlEncode[[]]" +
                           Environment.NewLine;

            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "~/Shared/Layout1.cshtml";
                v.WriteLiteral("BodyContent");
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync("foo-content");
                });
            });
            var nestedLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "~/Shared/Layout2.cshtml";
                v.Write("NestedLayout" + Environment.NewLine);
                v.RenderBodyPublic();
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync(htmlEncoder.HtmlEncode(v.RenderSection("foo").ToString()));
                });
            });
            nestedLayout.Path = "~/Shared/Layout2.cshtml";

            var baseLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("BaseLayout" + Environment.NewLine);
                v.RenderBodyPublic();
                v.Write(v.RenderSection("foo"));
            });
            baseLayout.Path = "~/Shared/Layout1.cshtml";

            var viewEngine = new Mock<IRazorViewEngine>();
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "~/Shared/Layout1.cshtml"))
                       .Returns(new RazorPageResult("~/Shared/Layout1.cshtml", nestedLayout));
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "~/Shared/Layout2.cshtml"))
                       .Returns(new RazorPageResult("~/Shared/Layout2.cshtml", baseLayout));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of<IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     new CommonTestEncoder(),
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Ejemplo n.º 8
0
        public async Task RenderAsync_WithNestedSectionsOfTheSameName_ThrowsIfSectionsWereDefinedButNotRendered()
        {
            // Arrange
            var htmlEncoder = new CommonTestEncoder();
            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "~/Shared/Layout1.cshtml";
                v.WriteLiteral("BodyContent");
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync("foo-content");
                });
            })
            {
                Path = "Page"
            };

            var nestedLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "~/Shared/Layout2.cshtml";
                v.Write("NestedLayout" + Environment.NewLine);
                v.RenderBodyPublic();
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync("dont-render-inner-foo");
                });
            })
            {
                Path = "/Shared/Layout1.cshtml"
            };

            var baseLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("BaseLayout" + Environment.NewLine);
                v.RenderBodyPublic();
                v.RenderSection("foo");
            })
            {
                Path = "/Shared/Layout2.cshtml"
            };

            var viewEngine = new Mock<IRazorViewEngine>();
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "~/Shared/Layout1.cshtml"))
                       .Returns(new RazorPageResult("~/Shared/Layout1.cshtml", nestedLayout));
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "~/Shared/Layout2.cshtml"))
                       .Returns(new RazorPageResult("~/Shared/Layout2.cshtml", baseLayout));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of<IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     new CommonTestEncoder(),
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act and Assert
            var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => view.RenderAsync(viewContext));
            Assert.Equal("The following sections have been defined but have not been rendered by the page at " +
                "'/Shared/Layout1.cshtml': 'foo'.", ex.Message);
        }
Ejemplo n.º 9
0
        public async Task RenderAsync_SucceedsIfRenderBodyIsNotInvoked_ButAllSectionsAreRendered()
        {
            // Arrange
            var expected = string.Join(
                Environment.NewLine,
                "layout-section-content",
                "page-section-content");

            var htmlEncoder = new CommonTestEncoder();
            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "NestedLayout";
                v.WriteLiteral("Page body content that will not be written");
                v.DefineSection("sectionA", async writer =>
                {
                    await writer.WriteAsync("page-section-content");
                });
            });
            var nestedLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "Layout";
                v.WriteLiteral("Nested layout content that will not be written");
                v.DefineSection("sectionB", async writer =>
                {
                    await writer.WriteLineAsync("layout-section-content");
                    await v.RenderSectionAsync("sectionA");
                });
            });
            nestedLayout.Path = "NestedLayout";
            var baseLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.RenderSection("sectionB");
            });
            baseLayout.Path = "Layout";

            var viewEngine = new Mock<IRazorViewEngine>();
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "NestedLayout"))
                       .Returns(new RazorPageResult("NestedLayout", nestedLayout));
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "Layout"))
                       .Returns(new RazorPageResult("Layout", baseLayout));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of<IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     new CommonTestEncoder(),
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Ejemplo n.º 10
0
        public async Task RenderAsync_SucceedsIfNestedSectionsAreRendered()
        {
            // Arrange
            var expected = string.Join(
                Environment.NewLine,
                "layout-section-content",
                "page-section-content");

            var htmlEncoder = new CommonTestEncoder();
            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "~/Shared/Layout1.cshtml";
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteAsync("page-section-content");
                });
            });
            var nestedLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = "~/Shared/Layout2.cshtml";
                v.RenderBodyPublic();
                v.DefineSection("foo", async writer =>
                {
                    await writer.WriteLineAsync("layout-section-content");
                    await v.RenderSectionAsync("foo");
                });
            })
            {
                Path = "/Shared/Layout1.cshtml"
            };
            var baseLayout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.RenderBodyPublic();
                v.RenderSection("foo");
            })
            {
                Path = "/Shared/Layout2.cshtml"
            };

            var viewEngine = new Mock<IRazorViewEngine>();
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "~/Shared/Layout1.cshtml"))
                       .Returns(new RazorPageResult("~/Shared/Layout1.cshtml", nestedLayout));
            viewEngine.Setup(p => p.FindPage(It.IsAny<ActionContext>(), "~/Shared/Layout2.cshtml"))
                       .Returns(new RazorPageResult("~/Shared/Layout2.cshtml", baseLayout));

            var view = new RazorView(viewEngine.Object,
                                     Mock.Of<IRazorPageActivator>(),
                                     CreateViewStartProvider(),
                                     page,
                                     new CommonTestEncoder(),
                                     isPartial: false);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Ejemplo n.º 11
0
        public async Task RenderAsync_ExecutesLayoutPages()
        {
            // Arrange
            var htmlEncoder = new CommonTestEncoder();
            var htmlEncodedNewLine = htmlEncoder.HtmlEncode(Environment.NewLine);
            var expected = "HtmlEncode[[layout-content" +
                           Environment.NewLine +
                           "]]head-content" +
                           htmlEncodedNewLine +
                           "body-content" +
                           htmlEncodedNewLine +
                           "foot-content";

            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.WriteLiteral("body-content");
                v.Layout = LayoutPath;
                v.DefineSection("head", async writer =>
                {
                    await writer.WriteAsync("head-content");
                });
                v.DefineSection("foot", async writer =>
                {
                    await writer.WriteAsync("foot-content");
                });
            });
            var layout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("layout-content" + Environment.NewLine);
                v.Write(v.RenderSection("head"));
                v.Write(Environment.NewLine);
                v.RenderBodyPublic();
                v.Write(Environment.NewLine);
                v.Write(v.RenderSection("foot"));
            });
            var activator = new Mock<IRazorPageActivator>();
            activator.Setup(a => a.Activate(page, It.IsAny<ViewContext>()))
                     .Verifiable();
            activator.Setup(a => a.Activate(layout, It.IsAny<ViewContext>()))
                     .Verifiable();
            var viewEngine = new Mock<IRazorViewEngine>();

            var view = new RazorView(viewEngine.Object,
                                     activator.Object,
                                     CreateViewStartProvider(),
                                     page,
                                     new CommonTestEncoder(),
                                     isPartial: false);
            var viewContext = CreateViewContext(view);
            viewEngine.Setup(p => p.FindPage(viewContext, LayoutPath))
                       .Returns(new RazorPageResult(LayoutPath, layout))
                       .Verifiable();

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            // Verify the activator was invoked for the primary page and layout page.
            activator.Verify();
            Assert.Equal(expected, viewContext.Writer.ToString());
            viewEngine.Verify();
        }
Ejemplo n.º 12
0
        public async Task RenderAsync_AsPartial_ExecutesLayout_ButNotViewStartPages()
        {
            // Arrange
            var htmlEncoder = new CommonTestEncoder();
            var expected = string.Join(Environment.NewLine,
                                       "HtmlEncode[[layout-content",
                                       "]]HtmlEncode[[page-content]]");
            var page = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Layout = LayoutPath;
                v.Write("page-content");
            });

            var layout = new TestableRazorPage(v =>
            {
                v.HtmlEncoder = htmlEncoder;
                v.Write("layout-content" + Environment.NewLine);
                v.RenderBodyPublic();
            });
            var pageFactory = new Mock<IRazorPageFactory>();
            pageFactory.Setup(p => p.CreateInstance(LayoutPath))
                       .Returns(layout);

            var viewEngine = new Mock<IRazorViewEngine>();
            viewEngine.Setup(v => v.FindPage(It.IsAny<ActionContext>(), LayoutPath))
                      .Returns(new RazorPageResult(LayoutPath, layout));

            var viewStartProvider = CreateViewStartProvider();
            var view = new RazorView(viewEngine.Object,
                                     Mock.Of<IRazorPageActivator>(),
                                     viewStartProvider,
                                     page,
                                     new CommonTestEncoder(),
                                     isPartial: true);
            var viewContext = CreateViewContext(view);

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            Mock.Get(viewStartProvider)
                .Verify(v => v.GetViewStartPages(It.IsAny<string>()), Times.Never());
            Assert.Equal(expected, viewContext.Writer.ToString());
        }
Ejemplo n.º 13
0
 public TestableRazorPage(Action<TestableRazorPage> executeAction)
 {
     _executeAction = executeAction;
     HtmlEncoder = new CommonTestEncoder();
 }
Ejemplo n.º 14
0
        public void AddCustomLocalizers_BeforeAddLocalizationServices_AddsNeededServices()
        {
            // Arrange
            var collection  = new ServiceCollection();
            var testEncoder = new CommonTestEncoder();

            // Act
            collection.Add(ServiceDescriptor.Singleton(typeof(IHtmlLocalizerFactory), typeof(TestHtmlLocalizerFactory)));
            collection.Add(ServiceDescriptor.Transient(typeof(IHtmlLocalizer <>), typeof(TestHtmlLocalizer <>)));
            collection.Add(ServiceDescriptor.Transient(typeof(IViewLocalizer), typeof(TestViewLocalizer)));
            collection.Add(ServiceDescriptor.Instance(typeof(IHtmlEncoder), testEncoder));

            MvcLocalizationServices.AddLocalizationServices(
                collection,
                LanguageViewLocationExpanderFormat.Suffix,
                setupAction: null);

            // Assert
            Assert.Collection(collection,
                              service =>
            {
                Assert.Equal(typeof(IHtmlLocalizerFactory), service.ServiceType);
                Assert.Equal(typeof(TestHtmlLocalizerFactory), service.ImplementationType);
                Assert.Equal(ServiceLifetime.Singleton, service.Lifetime);
            },
                              service =>
            {
                Assert.Equal(typeof(IHtmlLocalizer <>), service.ServiceType);
                Assert.Equal(typeof(TestHtmlLocalizer <>), service.ImplementationType);
                Assert.Equal(ServiceLifetime.Transient, service.Lifetime);
            },
                              service =>
            {
                Assert.Equal(typeof(IViewLocalizer), service.ServiceType);
                Assert.Equal(typeof(TestViewLocalizer), service.ImplementationType);
                Assert.Equal(ServiceLifetime.Transient, service.Lifetime);
            },
                              service =>
            {
                Assert.Equal(typeof(IHtmlEncoder), service.ServiceType);
                Assert.Same(testEncoder, service.ImplementationInstance);
            },
                              service =>
            {
                Assert.Equal(typeof(IConfigureOptions <RazorViewEngineOptions>), service.ServiceType);
                Assert.Equal(ServiceLifetime.Singleton, service.Lifetime);
            },
                              service =>
            {
                Assert.Equal(typeof(IStringLocalizerFactory), service.ServiceType);
                Assert.Equal(typeof(ResourceManagerStringLocalizerFactory), service.ImplementationType);
                Assert.Equal(ServiceLifetime.Singleton, service.Lifetime);
            },
                              service =>
            {
                Assert.Equal(typeof(IStringLocalizer <>), service.ServiceType);
                Assert.Equal(typeof(StringLocalizer <>), service.ImplementationType);
                Assert.Equal(ServiceLifetime.Transient, service.Lifetime);
            },
                              service =>
            {
                Assert.Equal(typeof(IOptions <>), service.ServiceType);
                Assert.Equal(ServiceLifetime.Singleton, service.Lifetime);
            });
        }
Ejemplo n.º 15
0
 public TestableRazorPage()
 {
     HtmlEncoder = new CommonTestEncoder();
 }