Ejemplo n.º 1
0
        public void WHEN_Template_Use_SubTemplate_Dependencies_SHOULD_Contains_All_TemplateNames_From_the_Tree()
        {
            //Arrange
            var controllerContext = new Mock <ControllerContext>(MockBehavior.Strict);
            var cachedView        = new HandlebarsView((w, o) => { }, GetRandom.String(32), new Dictionary <string, HandlebarsView>());

            cachedView.Dependencies.Add("SubLevel1", cachedView);
            cachedView.Dependencies.Add("SubLevel2", cachedView);
            cachedView.Dependencies.Add("OtherLeaf", cachedView);

            var cacheProvider = CacheProviderFactory.CreateForHandlebars(cachedView);
            var viewEngine    = new UnitTestableHandlebarsViewEngine(cacheProvider.Object);

            viewEngine.ViewLocationFormats        = new string[] { "~/ViewEngine/Assets/{0}.hbs" };
            viewEngine.PartialViewLocationFormats = new string[] { "~/ViewEngine/Assets/{0}.hbs" };

            //Act
            ViewEngineResult result = viewEngine.FindPartialView(controllerContext.Object, "Root", false);

            //Assert
            result.View.Should().BeOfType <HandlebarsView>();
            result.View.As <HandlebarsView>().CompiledTemplate.Should().NotBeNull();
            result.View.As <HandlebarsView>().VirtualPath.Should().NotBeNull();
            result.View.As <HandlebarsView>().Dependencies.Should().ContainKey("SubLevel1");
            result.View.As <HandlebarsView>().Dependencies.Should().ContainKey("SubLevel2");
            result.View.As <HandlebarsView>().Dependencies.Should().ContainKey("OtherLeaf");
        }
            public void UsingDeepObjectAndDictionaryIntKeys()
            {
                var dict = new Dictionary <int, object>();

                dict.Add(0, "Romeo");
                dict.Add(42, "Tango");
                dict.Add(9, "Foxtrot");
                dict.Add(13, "Mike");
                _vdd.Model = new
                {
                    firstname = "John",
                    lastname  = "Doe",
                    Dict      = dict
                };
                // overwriting the ones set in this test class' constructor
                var funcView = _handlebars.Compile("Hello, {{firstName}} {{Lastname}}!\n{{#each Dict}} {{@value}}{{/each}}");

                _compiledView = new CompiledView(funcView, fileHash: null, layout: null);
                _hbsview      = new HandlebarsView(_controllerContext, _compiledView, layouts: null);
                // end overwriting
                string html = GetHtmlFromView();

                Assert.Equal("Hello, John Doe!\n Romeo Tango Foxtrot Mike", html);
                Assert.Equal(4, dict.Keys.Count);                       // making sure the added properties in HandlebarsView weren't added to the dictionary
            }
            public void MimicRealWorld()
            {
                var hbsview = new HandlebarsView(_controllerContext, _fixture.ViewUsingViewdata, layouts: null);

                ViewDataDictionary vdd = new ViewDataDictionary();

                vdd["title"] = "Greetings";

                vdd.Model = new Person()
                {
                    FirstName = "John",
                    LastName  = "Doe"
                };
                // The lines above are equivalent to (in a controller):
                //   ViewBag.title = "Greetings";
                //   var model = new Person
                //   {
                //       FirstName = "John",
                //       LastName  = "Doe"
                //   };
                //   return View(model);

                string html;

                using (var textWriter = new StringWriter())
                {
                    ViewContext viewContext = new ViewContext(_controllerContext, hbsview, vdd, tempData: new TempDataDictionary(), writer: textWriter);

                    hbsview.Render(viewContext, textWriter);
                    html = textWriter.GetStringBuilder().ToString();
                }

                Assert.Equal("Title: Greetings. Hello, John Doe!", html);
            }
            public void NoLayoutOnlyRendersViewEvenIfViewSpecifiesLayout()
            {
                var hbsview = new HandlebarsView(_controllerContext, _fixture.ViewWithLayout, layouts: null);

                string html = GetHtmlFromView(hbsview);

                Assert.Equal("Hello World!", html);
            }
            public void LayoutsSpecifiedRendersViewAndSeveralLayouts()
            {
                var hbsview = new HandlebarsView(_controllerContext, _fixture.ViewWithLayout, layouts: new CompiledView[] { _fixture.LayoutView, _fixture.LayoutView });

                string html = GetHtmlFromView(hbsview);

                Assert.Equal("<html><html>Hello World!</html></html>", html);
            }
            private string GetHtmlFromView(HandlebarsView hbsview)
            {
                string html = null;

                using (var textWriter = new StringWriter())
                {
                    ViewContext viewContext = new ViewContext(_controllerContext, hbsview, new ViewDataDictionary(_model), tempData: new TempDataDictionary(), writer: textWriter);

                    hbsview.Render(viewContext, textWriter);
                    html = textWriter.GetStringBuilder().ToString();
                }

                return(html);
            }
Ejemplo n.º 7
0
        internal static Mock <ICacheProvider> CreateForHandlebars(HandlebarsView cachedView)
        {
            Mock <ICacheProvider> cacheProvider = new Mock <ICacheProvider>(MockBehavior.Strict);

            cacheProvider
            .Setup(provider => provider.GetOrAdd(
                       It.IsNotNull <CacheKey>(),
                       It.IsNotNull <Func <HandlebarsView> >(),
                       null,
                       null))
            .Returns(cachedView);

            return(cacheProvider);
        }
            public Models()
            {
                _controllerContext = new ControllerContext();

                _handlebars = HandlebarsDotNet.Handlebars.Create();

                _vdd = new ViewDataDictionary();

                // The view. Note that we're also testing for case-insensitivity (lastname is lowercase here, but not in the models).
                var funcView = _handlebars.Compile("Hello, {{FirstName}} {{lastname}}!");

                _compiledView = new CompiledView(funcView, fileHash: null, layout: null);

                _hbsview = new HandlebarsView(_controllerContext, _compiledView, layouts: null);
            }
Ejemplo n.º 9
0
            public void RenderSection_doesnt_throw_for_undefined_section_when_not_required()
            {
                var hbsve = new HandlebarsViewEngine();

                hbsve.RegisterSectionsHelpers();
                var handlebars = Handlebars.Create(hbsve.HandlebarsConfiguration);

                var view   = new CompiledView(handlebars.Compile("Body not rendered."), null, null);
                var layout = new CompiledView(handlebars.Compile("Name: {{rendersection \"name\" required=false}}."), null, null);

                var controllerContext = new ControllerContext();
                var hbsview           = new HandlebarsView(controllerContext, view, new[] { layout });

                var html = GetHtmlFromView(hbsview);

                Assert.Equal("Name: .", html);
            }
Ejemplo n.º 10
0
            public void Sidebar_not_defined_renders_default_content()
            {
                var hbsve = new HandlebarsViewEngine();

                hbsve.RegisterSectionsHelpers();
                var handlebars = Handlebars.Create(hbsve.HandlebarsConfiguration);

                var view   = new CompiledView(handlebars.Compile("No section here."), null, null);
                var layout = new CompiledView(handlebars.Compile(source), null, null);

                var controllerContext = new ControllerContext();
                var hbsview           = new HandlebarsView(controllerContext, view, new[] { layout });

                var html = GetHtmlFromView(hbsview);

                Assert.Equal("<p>Default sidebar content...</p>", html);
            }
Ejemplo n.º 11
0
            public void Sidebar_defined_renders_content_and_chrome()
            {
                var hbsve = new HandlebarsViewEngine();

                hbsve.RegisterSectionsHelpers();
                var handlebars = Handlebars.Create(hbsve.HandlebarsConfiguration);

                var view   = new CompiledView(handlebars.Compile("{{#definesection \"sidebar\"}}Sidebar{{/definesection}}"), null, null);
                var layout = new CompiledView(handlebars.Compile(source), null, null);

                var controllerContext = new ControllerContext();
                var hbsview           = new HandlebarsView(controllerContext, view, new[] { layout });

                var html = GetHtmlFromView(hbsview);

                Assert.Equal("<div id=\"sidebar\">Sidebar</div>", html);
            }
Ejemplo n.º 12
0
            public void DefineSection_can_append()
            {
                var hbsve = new HandlebarsViewEngine();

                hbsve.RegisterSectionsHelpers();
                var handlebars = Handlebars.Create(hbsve.HandlebarsConfiguration);

                var view    = new CompiledView(handlebars.Compile("{{#definesection \"name\"}}From view.{{/definesection}}"), null, null);
                var layout1 = new CompiledView(handlebars.Compile("{{#definesection \"name\" mode=\"append\"}}Appended.{{/definesection}}"), null, null);
                var layout2 = new CompiledView(handlebars.Compile("{{rendersection \"name\"}}"), null, null);

                var controllerContext = new ControllerContext();
                var hbsview           = new HandlebarsView(controllerContext, view, new[] { layout1, layout2 });

                var html = GetHtmlFromView(hbsview);

                Assert.Equal("From view.Appended.", html);
            }
Ejemplo n.º 13
0
        public void Handlebars_1_9_doesnt_throw_when_compiling_mustache_as_part_of_string()
        {
            var vpp = new VPP(
                new VPP.Dir("Views",
                            new VPP.Dir("Home",
                                        new VPP.File("index.hbs", "Pi is about {{formatvalue pi '{0:N}'}}")
                                        )
                            )
                );
            var hbsve = new HandlebarsViewEngine();

            hbsve.VirtualPathProvider = vpp;

            hbsve.RegisterHelper("formatvalue", (writer, context, args) =>
            {
                object val              = args[0];
                string format           = args[1] as string;
                ViewContext viewContext = HandlebarsView.GetViewContext(context);
                HtmlHelper htmlHelper   = new HtmlHelper(viewContext, viewContext.View as HandlebarsView);
                string formatted        = htmlHelper.FormatValue(val, format);
                writer.Write(formatted);
            });

            var httpContext = new Mock <HttpContextBase>();
            var controller  = new Mock <ControllerBase>();
            var routeData   = new RouteData();

            routeData.Values.Add("controller", "Home");
            var controllerContext = new ControllerContext(httpContext.Object, routeData, controller.Object);

            var viewengineResult = hbsve.FindView(controllerContext, viewName: "index", masterName: null, useCache: false);
            var hbsview          = viewengineResult.View;

            string actual = GetHtmlFromView(hbsview, new
            {
                pi = 3.14159265358979
            });

            Assert.Equal("Pi is about 3.14", actual);
        }
Ejemplo n.º 14
0
        public void WHEN_Passing_Any_TemplateName_Resulting_View_SHOULD_Be_Cached_ByTemplateName()
        {
            //Arrange
            var controllerContext = new Mock <ControllerContext>(MockBehavior.Strict);
            var cachedView        = new HandlebarsView((w, o) => { }, GetRandom.String(32), new Dictionary <string, HandlebarsView>());
            var monitor           = new CacheProviderFactory.CacheHistMonitor();
            var cacheProvider     = CacheProviderFactory.CreateForHandlebarsWithMonitor(monitor, cachedView, cachedView);
            var viewEngine        = new UnitTestableHandlebarsViewEngine(cacheProvider.Object);

            string templateNameA = "SubLevel2";
            string templateNameB = "OtherLeaf";

            //Act
            monitor.Reset();
            monitor.CacheMissCount.ShouldBeEquivalentTo(0, "Otherwise this test is irrelevent");
            monitor.CacheHitCount.ShouldBeEquivalentTo(0, "Otherwise this test is irrelevent");

            var result1A = viewEngine.FindPartialView(controllerContext.Object, templateNameA, false);

            monitor.CacheMissCount.ShouldBeEquivalentTo(1, "First attempt to load the TemplateA should cache miss");

            var result2A = viewEngine.FindPartialView(controllerContext.Object, templateNameA, false);

            monitor.CacheHitCount.ShouldBeEquivalentTo(1, "Second attempt to load the TemplateA should cache hit");

            monitor.Reset();
            for (int i = 0; i < 10; i++)
            {
                var result3A = viewEngine.FindPartialView(controllerContext.Object, templateNameA, false);
            }
            monitor.CacheMissCount.ShouldBeEquivalentTo(0, "Subsequent attempt to load the TemplateA should not cache miss");
            monitor.CacheHitCount.Should().BeGreaterOrEqualTo(10, "Subsequent attempt to load the TemplateA should cache hit");

            //--
            monitor.Reset();
            var result1B = viewEngine.FindPartialView(controllerContext.Object, templateNameB, false);

            monitor.CacheMissCount.ShouldBeEquivalentTo(1, "First attempt to load the CultureB should cache miss, key is culture dependant");
            monitor.CacheHitCount.ShouldBeEquivalentTo(0, "First attempt to load the CultureB should not cache hit, key is culture dependant");
        }
Ejemplo n.º 15
0
        internal static Mock <ICacheProvider> CreateForHandlebarsWithMonitor <T>(CacheHistMonitor monitor, T mockedOutput, HandlebarsView cachedView)
        {
            Mock <ICacheProvider> cacheProvider = new Mock <ICacheProvider>(MockBehavior.Strict);

            cacheProvider
            .Setup(provider => provider.GetOrAdd(
                       It.IsNotNull <CacheKey>(),
                       It.IsNotNull <Func <HandlebarsView> >(),
                       null,
                       null))
            .Returns <CacheKey, object, object, CacheKey>((c, o, a, b) =>
            {
                if (monitor.CacheKeys.Contains(c.GetFullCacheKey()))
                {
                    //Note: output object will be trash in test only.
                    monitor.CacheHitCount++;
                    return(cachedView);
                }
                else
                {
                    monitor.CacheMissCount++;
                    monitor.CacheKeys.Add(c.GetFullCacheKey());
                    return(cachedView);
                }
            });

            return(cacheProvider);
        }