コード例 #1
0
        public void LavaHelperRemoveComments_CommentsInIncludeFile_AreRemoved()
        {
            var fileProvider = GetFileProviderWithComments();

            var input = @"
{%- include '_comments.lava' -%}
";

            var expectedOutput = @"
Line 1<br>
Line 2<br>
Line 3<br>
Line 4<br>
";

            var options = new LavaEngineConfigurationOptions
            {
                FileSystem = GetFileProviderWithComments()
            };

            TestHelper.ExecuteForActiveEngines((engine) =>
            {
                // Create a new engine instance of the same type, but with a test file system configuration.
                var testEngine = LavaService.NewEngineInstance(engine.GetType(), options);

                TestHelper.AssertTemplateOutput(testEngine, expectedOutput, input);
            });
        }
コード例 #2
0
        private static void InitializeGlobalLavaEngineInstance(Type engineType)
        {
            // Initialize the Lava engine.
            var options = new LavaEngineConfigurationOptions();

            if (engineType != typeof(RockLiquidEngine))
            {
                var defaultEnabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands").SplitDelimitedValues(",").ToList();

                options.FileSystem             = new WebsiteLavaFileSystem();
                options.CacheService           = new WebsiteLavaTemplateCacheService();
                options.DefaultEnabledCommands = defaultEnabledLavaCommands;
            }

            LavaService.SetCurrentEngine(engineType, options);

            // Subscribe to exception notifications from the Lava Engine.
            var engine = LavaService.GetCurrentEngine();

            engine.ExceptionEncountered += Engine_ExceptionEncountered;

            // Initialize Lava extensions.
            InitializeLavaFilters(engine);
            InitializeLavaTags(engine);
            InitializeLavaBlocks(engine);
            InitializeLavaShortcodes(engine);
            InitializeLavaSafeTypes(engine);
        }
コード例 #3
0
        /// <summary>
        /// Configure the DotLiquid engine with the specified options.
        /// </summary>
        public override void OnSetConfiguration(LavaEngineConfigurationOptions options)
        {
            // DotLiquid uses a RubyDateFormat by default,
            // but since we aren't using Ruby, we want to disable that
            Liquid.UseRubyDateFormat = false;

            /* 2020-05-20 MDP (actually this comment was here a long time ago)
             *  NOTE: This means that all the built in template filters,
             *  and the RockFilters, will use CSharpNamingConvention.
             *
             *  For example the dotliquid documentation says to do this for formatting dates:
             *  {{ some_date_value | date:"MMM dd, yyyy" }}
             *
             *  However, if CSharpNamingConvention is enabled, it needs to be:
             *  {{ some_date_value | Date:"MMM dd, yyyy" }}
             */

            Template.NamingConvention = new global::DotLiquid.NamingConventions.CSharpNamingConvention();

            if (options.FileSystem == null)
            {
                options.FileSystem = new DotLiquidFileSystem(new LavaNullFileSystem());
            }

            Template.FileSystem = new DotLiquidFileSystem(options.FileSystem);

            Template.RegisterSafeType(typeof(Enum), o => o.ToString());
            Template.RegisterSafeType(typeof(DBNull), o => null);
        }
コード例 #4
0
        public void WebsiteLavaTemplateCacheService_WhitespaceTemplatesWithDifferentLengths_AreCachedIndependently()
        {
            var options = new LavaEngineConfigurationOptions();

            ILavaTemplateCacheService cacheService = new WebsiteLavaTemplateCacheService();

            options.CacheService = cacheService;

            TestHelper.ExecuteForActiveEngines((defaultEngineInstance) =>
            {
                if (defaultEngineInstance.GetType() == typeof(RockLiquidEngine))
                {
                    Debug.Write("Template caching cannot be tested by this methodology for the RockLiquid implementation.");
                    return;
                }

                // Remove all existing items from the cache.
                cacheService.ClearCache();

                var engine = LavaService.NewEngineInstance(defaultEngineInstance.GetType(), options);

                // Process a zero-length whitespace template - this should be cached separately.
                var input0 = string.Empty;
                var key0   = cacheService.GetCacheKeyForTemplate(input0);

                // Verify that the template does not initially exist in the cache.
                var exists = cacheService.ContainsKey(key0);

                Assert.IsFalse(exists, "String-0 Template found in cache unexpectedly.");

                // Render the template, which will automatically add it to the cache.
                var output0 = engine.RenderTemplate(input0);

                // Verify that the template now exists in the cache.
                exists = cacheService.ContainsKey(key0);

                Assert.IsTrue(exists, "String-0 Template not found in cache.");

                // Render a whitespace template of a different length - this should be cached separately from the first template.
                // If not, the caching mechanism would cause some whitespace to be rendered incorrectly.
                var input1 = new string( ' ', 1 );
                var key1   = engine.TemplateCacheService.GetCacheKeyForTemplate(input1);

                var output1 = engine.RenderTemplate(input1);

                // Verify that the 100-character whitespace template now exists in the cache.
                exists = cacheService.ContainsKey(key1);

                Assert.IsTrue(exists, "String-1 Template not found in cache.");

                // Verify that a whitespace template of some other length is not equated with the whitespace templates we have specifically added.
                var keyX = engine.TemplateCacheService.GetCacheKeyForTemplate(new string( ' ', 9 ));

                exists = cacheService.ContainsKey(keyX);

                Assert.IsFalse(exists, "String-9 Template found in cache unexpectedly.");
            });
        }
コード例 #5
0
        /// <summary>
        /// Get the Lava Engine configuration for the currenttest environment.
        /// </summary>
        /// <returns></returns>
        private static LavaEngineConfigurationOptions GetCurrentEngineOptions()
        {
            var engineOptions = new LavaEngineConfigurationOptions
            {
                FileSystem   = new WebsiteLavaFileSystem(),
                CacheService = new WebsiteLavaTemplateCacheService(),
                TimeZone     = RockDateTime.OrgTimeZoneInfo
            };

            return(engineOptions);
        }
コード例 #6
0
        public static ILavaEngine NewEngineInstance(Type engineType, LavaEngineConfigurationOptions engineOptions)
        {
            //ILavaEngine engine;

            engineOptions = engineOptions ?? new LavaEngineConfigurationOptions();

            // Initialize the Rock variant of the DotLiquid Engine
            var engine = global::Rock.Lava.LavaService.NewEngineInstance(engineType, engineOptions);

            return(engine);
        }
コード例 #7
0
        public void FluidEngineValueConverterPerformance_DictionaryKeyResolution_OutputsPerformanceMeasures()
        {
            var totalSets             = 10;
            var totalIterationsPerSet = 1000000;

            // Create a Fluid engine with template caching disabled.
            var engineOptions = new LavaEngineConfigurationOptions {
                CacheService = new MockTemplateCacheService()
            };

            var engine = LavaService.NewEngineInstance(typeof(FluidEngine), engineOptions);

            var standardLavaDictionary = new Dictionary <string, object>();

            var formatString = new string( '0', totalIterationsPerSet.ToString().Length );

            for (int i = 0; i < totalIterationsPerSet; i++)
            {
                standardLavaDictionary.Add(i.ToString(formatString), i);
            }

            var mergeFields = new LavaDataDictionary {
                { "Dictionary", standardLavaDictionary }
            };

            var totalTime = TestHelper.ExecuteAndGetElapsedTime(() =>
            {
                engine.ClearTemplateCache();

                for (int repeatCount = 1; repeatCount <= totalSets; repeatCount++)
                {
                    var elapsedTime = TestHelper.ExecuteAndGetElapsedTime(() =>
                    {
                        for (int i = 0; i < totalIterationsPerSet; i++)
                        {
                            var template = "{{ Dictionary['" + i.ToString(formatString) + "']}}";

                            var options = new LavaTestRenderOptions {
                                MergeFields = mergeFields
                            };

                            var output = TestHelper.GetTemplateOutput(engine, template, mergeFields);

                            // Verify that the correct entry was retrieved.
                            Assert.AreEqual(i.ToString(), output);
                        }
                    });

                    Debug.Print($"Pass {repeatCount} Elapsed Time: {elapsedTime.TotalMilliseconds} ");
                }
            });

            Debug.Print($"Average Time: {totalTime.TotalMilliseconds / totalSets} ");
        }
コード例 #8
0
        private static void InitializeLavaEngines()
        {
            // Register the RockLiquid Engine (pre-v13).
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var engineOptions = new LavaEngineConfigurationOptions();

                var rockLiquidEngine = new RockLiquidEngine();

                rockLiquidEngine.Initialize(engineOptions);

                return(rockLiquidEngine);
            });

            // Register the DotLiquid Engine.
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var defaultEnabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands").SplitDelimitedValues(",").ToList();

                var engineOptions = new LavaEngineConfigurationOptions
                {
                    FileSystem             = new WebsiteLavaFileSystem(),
                    CacheService           = new WebsiteLavaTemplateCacheService(),
                    DefaultEnabledCommands = defaultEnabledLavaCommands
                };

                var dotLiquidEngine = new DotLiquidEngine();

                dotLiquidEngine.Initialize(engineOptions);

                return(dotLiquidEngine);
            });

            // Register the Fluid Engine.
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var defaultEnabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands").SplitDelimitedValues(",").ToList();

                var engineOptions = new LavaEngineConfigurationOptions
                {
                    FileSystem             = new WebsiteLavaFileSystem(),
                    CacheService           = new WebsiteLavaTemplateCacheService(),
                    DefaultEnabledCommands = defaultEnabledLavaCommands
                };

                var fluidEngine = new FluidEngine();

                fluidEngine.Initialize(engineOptions);

                return(fluidEngine);
            });
        }
コード例 #9
0
        public void Initialize(bool testRockLiquidEngine, bool testDotLiquidEngine, bool testFluidEngine)
        {
            // Verify the test environment: RockLiquidEngine and DotLiquidEngine are mutually exclusive test environments.
            if (testRockLiquidEngine && testDotLiquidEngine)
            {
                throw new Exception("RockLiquidEngine/DotLiquidEngine cannot be tested simultaneously because they require different global configurations of the DotLiquid library.");
            }

            RockLiquidEngineIsEnabled = testRockLiquidEngine;
            DotLiquidEngineIsEnabled  = testDotLiquidEngine;
            FluidEngineIsEnabled      = testFluidEngine;

            RegisterLavaEngines();

            if (RockLiquidEngineIsEnabled)
            {
                // Initialize the Rock variant of the DotLiquid Engine
                var engineOptions = new LavaEngineConfigurationOptions();

                _rockliquidEngine = LavaService.NewEngineInstance(typeof(RockLiquidEngine), engineOptions);

                // Register the common Rock.Lava filters first, then overwrite with the web-based RockFilters as needed.
                RegisterFilters(_rockliquidEngine);
            }

            if (DotLiquidEngineIsEnabled)
            {
                // Initialize the DotLiquid Engine
                var engineOptions = new LavaEngineConfigurationOptions();

                _dotliquidEngine = LavaService.NewEngineInstance(typeof(DotLiquidEngine), engineOptions);

                RegisterFilters(_dotliquidEngine);
            }

            if (FluidEngineIsEnabled)
            {
                // Initialize Fluid Engine
                var engineOptions = new LavaEngineConfigurationOptions();

                _fluidEngine = LavaService.NewEngineInstance(typeof(FluidEngine), engineOptions);

                RegisterFilters(_fluidEngine);
            }
        }
コード例 #10
0
        /// <summary>
        /// Apply Lava Engine configuration options to the Fluid engine.
        /// </summary>
        /// <param name="options"></param>
        private void ApplyEngineConfigurationOptions(LavaEngineConfigurationOptions options)
        {
            var templateOptions = GetTemplateOptions();

            // Set Fluid to use the local server culture for formatting dates, times and currencies.
            templateOptions.CultureInfo = options.Culture ?? CultureInfo.CurrentCulture;

            // Set Fluid to use the Rock Organization timezone.
            templateOptions.TimeZone = options.TimeZone ?? RockDateTime.OrgTimeZoneInfo;

            TemplateOptions.Default.TimeZone = templateOptions.TimeZone;

            if (options.FileSystem == null)
            {
                options.FileSystem = new LavaNullFileSystem();
            }

            templateOptions.FileProvider = new FluidFileSystem(options.FileSystem);
        }
コード例 #11
0
        public void Configuration_SetDefaultEntityCommandExecute_IsEnabledForNewDefaultContext()
        {
            var options = new LavaEngineConfigurationOptions
            {
                DefaultEnabledCommands = new List <string> {
                    "Execute"
                }
            };

            TestHelper.ExecuteForActiveEngines((engine) =>
            {
                var testEngine = LavaService.NewEngineInstance(engine.GetType(), options);

                var context = testEngine.NewRenderContext();

                var enabledCommands = context.GetEnabledCommands();

                Assert.That.Contains(enabledCommands, "Execute");
            });
        }
コード例 #12
0
        public static void Initialize(bool testRockLiquidEngine, bool testDotLiquidEngine, bool testFluidEngine)
        {
            // Verify the test environment: RockLiquidEngine and DotLiquidEngine are mutually exclusive test environments.
            if (testRockLiquidEngine && testDotLiquidEngine)
            {
                throw new Exception("RockLiquidEngine/DotLiquidEngine cannot be tested simultaneously because they require different global configurations of the DotLiquid library.");
            }

            RockLiquidEngineIsEnabled = testRockLiquidEngine;
            DotLiquidEngineIsEnabled  = testDotLiquidEngine;
            FluidEngineIsEnabled      = testFluidEngine;

            RegisterLavaEngines();

            var engineOptions = new LavaEngineConfigurationOptions();

            engineOptions.ExceptionHandlingStrategy = ExceptionHandlingStrategySpecifier.RenderToOutput;
            engineOptions.FileSystem   = new MockFileProvider();
            engineOptions.CacheService = new MockTemplateCacheService();

            if (RockLiquidEngineIsEnabled)
            {
                // Initialize the Rock variant of the DotLiquid Engine.
                _rockliquidEngine = global::Rock.Lava.LavaService.NewEngineInstance(typeof(RockLiquidEngine), engineOptions);
            }

            if (DotLiquidEngineIsEnabled)
            {
                // Initialize the Lava library DotLiquid Engine.
                _dotliquidEngine = global::Rock.Lava.LavaService.NewEngineInstance(typeof(DotLiquidEngine), engineOptions);
            }

            if (FluidEngineIsEnabled)
            {
                // Initialize the Fluid Engine.
                _fluidEngine = global::Rock.Lava.LavaService.NewEngineInstance(typeof(FluidEngine), engineOptions);
            }

            _instance = new LavaIntegrationTestHelper();
        }
コード例 #13
0
        private static void RegisterLavaEngines()
        {
            // Register the RockLiquid Engine (pre-v13).
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var engineOptions = new LavaEngineConfigurationOptions();

                var rockLiquidEngine = new RockLiquidEngine();

                rockLiquidEngine.Initialize(engineOptions);

                return(rockLiquidEngine);
            });

            // Register the DotLiquid Engine.
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var engineOptions = GetCurrentEngineOptions();

                var dotLiquidEngine = new DotLiquidEngine();

                dotLiquidEngine.Initialize(engineOptions);

                return(dotLiquidEngine);
            });

            // Register the Fluid Engine.
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var engineOptions = GetCurrentEngineOptions();

                var fluidEngine = new FluidEngine();

                fluidEngine.Initialize(engineOptions);

                return(fluidEngine);
            });
        }
コード例 #14
0
        public void WebsiteLavaShortcodeProvider_ModifiedShortcode_ReturnsCorrectVersionAfterModification()
        {
            var options = new LavaEngineConfigurationOptions();

            ILavaTemplateCacheService cacheService = new WebsiteLavaTemplateCacheService();

            options.CacheService = cacheService;

            TestHelper.ExecuteForActiveEngines((defaultEngineInstance) =>
            {
                if (defaultEngineInstance.GetType() == typeof(DotLiquidEngine) ||
                    defaultEngineInstance.GetType() == typeof(RockLiquidEngine))
                {
                    Debug.Write("Shortcode caching is not currently implemented for RockLiquid/DotLiquid.");
                    return;
                }

                var engine = LavaService.NewEngineInstance(defaultEngineInstance.GetType(), options);

                var shortcodeProvider = new TestLavaDynamicShortcodeProvider();

                var rockContext          = new RockContext();
                var lavaShortCodeService = new LavaShortcodeService(rockContext);

                // Create a new Shortcode.
                var shortcodeGuid1 = TestGuids.Shortcodes.ShortcodeTest1.AsGuid();

                var lavaShortcode = lavaShortCodeService.Queryable().FirstOrDefault(x => x.Guid == shortcodeGuid1);

                if (lavaShortcode == null)
                {
                    lavaShortcode = new LavaShortcode();

                    lavaShortCodeService.Add(lavaShortcode);
                }

                lavaShortcode.Guid        = shortcodeGuid1;
                lavaShortcode.TagName     = "TestShortcode1";
                lavaShortcode.Name        = "Test Shortcode 1";
                lavaShortcode.IsActive    = true;
                lavaShortcode.Description = "Test shortcode";
                lavaShortcode.TagType     = TagType.Inline;

                lavaShortcode.Markup = "Hello!";

                rockContext.SaveChanges();

                shortcodeProvider.RegisterShortcode(engine, lavaShortcode);

                // Resolve a template using the new shortcode and verify the result.
                engine.ClearTemplateCache();

                shortcodeProvider.ClearCache();

                LavaService.SetCurrentEngine(engine);

                TestHelper.AssertTemplateOutput(engine, "Hello!", "{[ TestShortcode1 ]}");

                lavaShortcode.Markup = "Goodbye!";

                rockContext.SaveChanges();

                shortcodeProvider.ClearCache();

                engine.ClearTemplateCache();

                TestHelper.AssertTemplateOutput(engine, "Goodbye!", "{[ TestShortcode1 ]}");
            });
        }
コード例 #15
0
 /// <summary>
 /// Initializes the Lava engine.
 /// Doing this in startup will force the static Liquid class to get instantiated
 /// so that the standard filters are loaded prior to the custom RockFilter.
 /// This is to allow the custom 'Date' filter to replace the standard Date filter.
 /// </summary>
 public override void OnSetConfiguration(LavaEngineConfigurationOptions options)
 {
     ApplyEngineConfigurationOptions(options);
 }