AreEqual() public static méthode

public static AreEqual ( string expectedValue, string actualValue ) : void
expectedValue string
actualValue string
Résultat void
        public void TestNullableArgument()
        {
            var template  = Template.Parse("{{ tester 'input1' 1 }}");
            var context   = new TemplateContext();
            var testerObj = new ScriptObjectWithNullable();

            context.PushGlobal(testerObj);
            var result = template.Render(context);

            TextAssert.AreEqual("input1 Value: 1", result);
        }
Exemple #2
0
        public void TestFunctionArrayEachAndFunctionCall()
        {
            var template = Template.Parse(@"{{
func f; ret $0 + 1; end
[1, 2, 3] | array.each @f
}} EOL");

            var result = template.Render();

            TextAssert.AreEqual("[2, 3, 4] EOL", result);
        }
Exemple #3
0
        public void TestIncludeNamedArguments()
        {
            var template = Template.Parse(@"{{ include 'named_arguments' this_arg: 5 }}");
            var context  = new TemplateContext();

            context.TemplateLoader = new CustomTemplateLoader();

            var text     = template.Render(context).Replace("\r\n", "\n");
            var expected = @"5";

            TextAssert.AreEqual(expected, text);
        }
Exemple #4
0
        public void TestLoopWithInclude()
        {
            var context = new TemplateContext()
            {
                TemplateLoader = new LoaderLoopWithInclude()
            };
            var template = Template.Parse(@"{{ for my_loop_variable in 1..3; include 'test'; end; }}");

            var result = template.Render(context);

            TextAssert.AreEqual("123", result);
        }
Exemple #5
0
        public void TestPipeAndFunction()
        {
            var template = Template.Parse(@"
{{- func format_number
    ret $0 | math.format '0.00' | string.replace '.' ''
end -}}
{{ 123 | format_number -}}
");
            var result   = template.Render();

            TextAssert.AreEqual("12300", result);
        }
Exemple #6
0
        public void Test(TestFilePath testFilePath)
        {
            var inputName = testFilePath.FilePath;
            var baseDir   = Path.GetFullPath(Path.Combine(BaseDirectory, RelativeBasePath));

            var inputFile = Path.Combine(baseDir, inputName);
            var inputText = File.ReadAllText(inputFile);

            var expectedOutputFile = Path.ChangeExtension(inputFile, OutputEndFileExtension);

            Assert.True(File.Exists(expectedOutputFile), $"Expecting output result file [{expectedOutputFile}] for input file [{inputName}]");
            var expectedOutputText = File.ReadAllText(expectedOutputFile, Encoding.UTF8);

            var template = Template.Parse(inputText, "text");

            var result = string.Empty;

            if (template.HasErrors)
            {
                for (int i = 0; i < template.Messages.Count; i++)
                {
                    var message = template.Messages[i];
                    if (i > 0)
                    {
                        result += "\n";
                    }
                    result += message;
                }
            }
            else
            {
                Assert.NotNull(template.Page);

                try
                {
                    result = template.Render();
                }
                catch (ScriptRuntimeException exception)
                {
                    result = GetReason(exception);
                }
            }
            Console.WriteLine("Result");
            Console.WriteLine("======================================");
            Console.WriteLine(result);
            Console.WriteLine("Expected");
            Console.WriteLine("======================================");
            Console.WriteLine(expectedOutputText);

            TextAssert.AreEqual(expectedOutputText, result);
        }
Exemple #7
0
        public void TestJekyllInclude()
        {
            var input    = "{% include /this/is/a/test.htm %}";
            var template = Template.ParseLiquid(input, lexerOptions: new LexerOptions()
            {
                EnableIncludeImplicitString = true, Lang = ScriptLang.Liquid
            });
            var context = new TemplateContext {
                TemplateLoader = new LiquidCustomTemplateLoader()
            };
            var result = template.Render(context);

            TextAssert.AreEqual("/this/is/a/test.htm", result);
        }
Exemple #8
0
        public void TestQueryableRIndex()
        {
            var context = new TemplateContext();

            context.CurrentGlobal.Import("data", new Func <IQueryable <int> >(() => Enumerable.Range(0, 5).AsQueryable()));

            var template = Template.Parse(@"{{
for item in data
for.rindex
end
}}");
            var result   = template.Render(context);

            TextAssert.AreEqual("43210", result);
        }
Exemple #9
0
        public void TestQueryableOffset()
        {
            var context = new TemplateContext();

            context.CurrentGlobal.Import("data", new Func <IQueryable <int> >(() => Enumerable.Range(0, 10).AsQueryable()));

            var template = Template.Parse(@"{{
for item in data offset:2
item
end
}}");
            var result   = template.Render(context);

            TextAssert.AreEqual("23456789", result);
        }
Exemple #10
0
        public void TestQueryableChanged()
        {
            var context = new TemplateContext();

            context.CurrentGlobal.Import("data", new Func <IQueryable <int> >(() => new[] { 0, 0, 1, 1, 2 }.AsQueryable()));

            var template = Template.Parse(@"{{
for item in data
for.changed
end
}}");
            var result   = template.Render(context);

            TextAssert.AreEqual("truefalsetruefalsetrue", result);
        }
Exemple #11
0
        public void TestIndentSkippedWithGreedyOnPreviousLine()
        {
            var input    = @"{{ a_multi_line_value = ""test1\ntest2\ntest3\n"" -}}
   {{ a_multi_line_value }}Hello
";
            var template = Template.Parse(input);
            var result   = template.Render();

            result = TextAssert.Normalize(result);

            TextAssert.AreEqual(TextAssert.Normalize(@"test1
test2
test3
Hello
"), result);
        }
Exemple #12
0
        public void TestQueryableLast()
        {
            var context = new TemplateContext();

            context.CurrentGlobal.Import("data", new Func <IQueryable <int> >(() => Enumerable.Range(0, 5).AsQueryable()));

            var template = Template.Parse(@"{{
for item in data
for.last
end
}}");
            var result   = template.Render(context);

            // last will always be false with iqueryable
            TextAssert.AreEqual("falsefalsefalsefalsetrue", result);
        }
Exemple #13
0
        public void TestEosWithEnd2()
        {
            var templateText  = @"
{{-
foo = (do; ret 'fo'; end) + (do; ret 'o'; end)
-}}
{{foo}}";
            var template      = Template.Parse(templateText);
            var templateText2 = template.ToText();
            var template2     = Template.Parse(templateText2);
            var templateText3 = template2.ToText();

            Console.WriteLine(templateText3);
            TextAssert.AreEqual(templateText2, templateText3);
            TextAssert.AreEqual(template.Render(), template2.Render());
        }
Exemple #14
0
        public void InvalidPipe()
        {
            var parsedTemplate = Template.ParseLiquid("{{ 22.00 | a | b | string.upcase }}");

            Assert.False(parsedTemplate.HasErrors);

            var scriptObject = new ScriptObject();

            scriptObject.Import(typeof(MyPipeFunctions));
            var context = new TemplateContext();

            context.PushGlobal(scriptObject);

            var result = parsedTemplate.Render(context);

            TextAssert.AreEqual("22AB", result);
        }
Exemple #15
0
        public void TestIndentedIncludes2()
        {
            var template = Template.Parse(@"Test
{{ include 'header' }}
");
            var context  = new TemplateContext();

            context.TemplateLoader    = new CustomTemplateLoader();
            context.IndentWithInclude = true;

            var text     = template.Render(context).Replace("\r\n", "\n");
            var expected = @"Test
This is a header
".Replace("\r\n", "\n");

            TextAssert.AreEqual(expected, text);
        }
Exemple #16
0
        public void TestPipeAndFunctionAndLoop()
        {
            var template = Template.Parse(@"
{{- func format_number
    ret $0 | math.format '0.00' | string.replace '.' ''
end -}}
{{
for $i in 1..3
    temp_variable = $i | format_number
end
-}}
{{ temp_variable -}}
");
            var result   = template.Render();

            TextAssert.AreEqual("300", result);
        }
Exemple #17
0
        public void TestQueryableLoopLimit()
        {
            var context = new TemplateContext
            {
                LoopLimit = 5
            };

            context.CurrentGlobal.Import("data", new Func <IQueryable <int> >(() => Enumerable.Range(0, 10).AsQueryable()));

            var template  = Template.Parse(@"{{
for item in data
item
end
}}");
            var exception = Assert.Throws <ScriptRuntimeException>(() => template.Render(context));

            TextAssert.AreEqual("<input>(2,1) : error : Exceeding number of iteration limit `5` for loop statement.", exception.Message);
        }
Exemple #18
0
        public void TestDynamicVariable()
        {
            var template = Template.Parse("Test with a dynamic {{ myvar }}");

            var context = new TemplateContext
            {
                TryGetVariable = variable =>
                {
                    Assert.AreEqual("myvar", variable.Name);
                    return("yes");
                }
            };

            context.Evaluate(template.Page);
            var result = context.Output.ToString();

            TextAssert.AreEqual("Test with a dynamic yes", result);
        }
Exemple #19
0
        public void TestQueryableLoopLimitQueryableDisable()
        {
            var context = new TemplateContext
            {
                LoopLimit          = 5,
                LoopLimitQueryable = 0,
            };

            context.CurrentGlobal.Import("data", new Func <IQueryable <int> >(() => Enumerable.Range(0, 10).AsQueryable()));

            var template = Template.Parse(@"{{
for item in data
item
end
}}");
            var result   = template.Render(context);

            TextAssert.AreEqual("0123456789", result);
        }
Exemple #20
0
        public void TestPropertyInheritance()
        {
            var scriptObject = new ScriptObject
            {
                { "a", new MyObject {
                      PropertyA = "ClassA"
                  } },
                { "b", new MyObject2 {
                      PropertyA = "ClassB", PropertyC = "ClassB-PropC"
                  } }
            };

            var context = new TemplateContext();

            context.PushGlobal(scriptObject);

            var result = Template.Parse("{{a.property_a}}-{{b.property_a}}-{{b.property_c}}").Render(context);

            TextAssert.AreEqual("ClassA-ClassB-ClassB-PropC", result);
        }
Exemple #21
0
        public void TestLoopVariable()
        {
            var template = Template.Parse(@"
{{- for x in [1,2,3,4,5]
y = x
end -}}
x and y = {{ x }} and {{ y }}
{{~ for y in [6,7,8,9,0]
z = y
end ~}}
y and z = {{ y }} and {{ z -}}
");
            var expected = @"x and y =  and 5
y and z = 5 and 0";

            var tc     = new TemplateContext();
            var result = template.Render(tc);

            TextAssert.AreEqual(expected, result);
        }
Exemple #22
0
        public void TestEosWithEnd()
        {
            var templateText  = @"
{{-
func foo
   if b
-}}
bar
{{-
    end
end
-}}{{foo}}";
            var template      = Template.Parse(templateText);
            var templateText2 = template.ToText();
            var template2     = Template.Parse(templateText2);
            var templateText3 = template2.ToText();

            TextAssert.AreEqual(templateText2, templateText3);
            TextAssert.AreEqual(template.Render(), template2.Render());
        }
Exemple #23
0
        public void TestJson()
        {
            // issue: https://github.com/lunet-io/scriban/issues/11
            // fixed: https://github.com/lunet-io/scriban/issues/15

            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("Column1");
            dataTable.Columns.Add("Column2");

            DataRow dataRow = dataTable.NewRow();

            dataRow["Column1"] = "Hello";
            dataRow["Column2"] = "World";
            dataTable.Rows.Add(dataRow);

            dataRow            = dataTable.NewRow();
            dataRow["Column1"] = "Bonjour";
            dataRow["Column2"] = "le monde";
            dataTable.Rows.Add(dataRow);

            string json = JsonConvert.SerializeObject(dataTable);

            Console.WriteLine("Json: " + json);

            var parsed = JsonConvert.DeserializeObject(json);

            Console.WriteLine("Parsed: " + parsed);

            string myTemplate = @"
[
  { {{~ for tbr in tb }}
    ""N"": {{tbr.Column1}},
    ""M"": {{tbr.Column2}}
    {{~ end ~}}
  },
]
{{tb}}
";

            // Parse the template
            var template = Template.Parse(myTemplate);

            // Render
            var context = new TemplateContext {
                MemberRenamer = member => member.Name
            };
            var scriptObject = new ScriptObject();

            scriptObject.Import(new { tb = parsed });
            context.PushGlobal(scriptObject);
            var result = template.Render(context);

            context.PopGlobal();

            var expected =
                @"
[
  {
    ""N"": Hello,
    ""M"": World

    ""N"": Bonjour,
    ""M"": le monde
  },
]
[[[Hello], [World]], [[Bonjour], [le monde]]]
";

            TextAssert.AreEqual(expected, result);
        }
Exemple #24
0
        public static void AssertTemplate(string expected, string input, ScriptLang lang = ScriptLang.Default, bool isRoundtripTest = false, bool supportExactRoundtrip = true, object model = null, bool specialLiquid = false, bool expectParsingErrorForRountrip = false, bool supportRoundTrip = true)
        {
            bool isLiquid = lang == ScriptLang.Liquid;

            var parserOptions = new ParserOptions()
            {
                LiquidFunctionsToScriban = isLiquid,
            };
            var lexerOptions = new LexerOptions()
            {
                Lang = lang
            };

            if (isRoundtripTest)
            {
                lexerOptions.KeepTrivia = true;
            }

            if (specialLiquid)
            {
                parserOptions.ExpressionDepthLimit = 500;
            }

#if EnableTokensOutput
            {
                Console.WriteLine("Tokens");
                Console.WriteLine("======================================");
                var lexer = new Lexer(input, options: lexerOptions);
                foreach (var token in lexer)
                {
                    Console.WriteLine($"{token.Type}: {token.GetText(input)}");
                }
                Console.WriteLine();
            }
#endif
            string roundtripText = null;

            // We loop first on input text, then on roundtrip
            while (true)
            {
                bool isRoundtrip  = roundtripText != null;
                bool hasErrors    = false;
                bool hasException = false;
                if (isRoundtrip)
                {
                    Console.WriteLine("Roundtrip");
                    Console.WriteLine("======================================");
                    Console.WriteLine(roundtripText);
                    lexerOptions.Lang = lang == ScriptLang.Scientific ? lang : ScriptLang.Default;

                    if (!isLiquid && supportExactRoundtrip)
                    {
                        Console.WriteLine("Checking Exact Roundtrip - Input");
                        Console.WriteLine("======================================");
                        TextAssert.AreEqual(input, roundtripText);
                    }
                    input = roundtripText;
                }
                else
                {
                    Console.WriteLine("Input");
                    Console.WriteLine("======================================");
                    Console.WriteLine(input);
                }

                var template = Template.Parse(input, "text", parserOptions, lexerOptions);

                var result      = string.Empty;
                var resultAsync = string.Empty;
                if (template.HasErrors)
                {
                    hasErrors = true;
                    for (int i = 0; i < template.Messages.Count; i++)
                    {
                        var message = template.Messages[i];
                        if (i > 0)
                        {
                            result += "\n";
                        }
                        result += message;
                    }
                    if (specialLiquid && !isRoundtrip)
                    {
                        throw new InvalidOperationException("Parser errors: " + result);
                    }
                }
                else
                {
                    if (isRoundtripTest)
                    {
                        result = template.ToText();
                    }
                    else
                    {
                        Assert.NotNull(template.Page);

                        if (!isRoundtrip)
                        {
                            // Dumps the roundtrip version
                            var lexerOptionsForTrivia = lexerOptions;
                            lexerOptionsForTrivia.KeepTrivia = true;
                            var templateWithTrivia = Template.Parse(input, "input", parserOptions, lexerOptionsForTrivia);
                            roundtripText = templateWithTrivia.ToText();
                        }

                        try
                        {
                            // Setup a default model context for the tests
                            if (model == null)
                            {
                                var scriptObj = new ScriptObject
                                {
                                    ["page"] = new ScriptObject {
                                        ["title"] = "This is a title"
                                    },
                                    ["user"] = new ScriptObject {
                                        ["name"] = "John"
                                    },
                                    ["product"] = new ScriptObject {
                                        ["title"] = "Orange", ["type"] = "fruit"
                                    },
                                    ["products"] = new ScriptArray()
                                    {
                                        new ScriptObject {
                                            ["title"] = "Orange", ["type"] = "fruit"
                                        },
                                        new ScriptObject {
                                            ["title"] = "Banana", ["type"] = "fruit"
                                        },
                                        new ScriptObject {
                                            ["title"] = "Apple", ["type"] = "fruit"
                                        },
                                        new ScriptObject {
                                            ["title"] = "Computer", ["type"] = "electronics"
                                        },
                                        new ScriptObject {
                                            ["title"] = "Mobile Phone", ["type"] = "electronics"
                                        },
                                        new ScriptObject {
                                            ["title"] = "Table", ["type"] = "furniture"
                                        },
                                        new ScriptObject {
                                            ["title"] = "Sofa", ["type"] = "furniture"
                                        },
                                    }
                                };
                                scriptObj.Import(typeof(SpecialFunctionProvider));
                                model = scriptObj;
                            }

                            // Render sync
                            {
                                var context = NewTemplateContext(lang);
                                context.PushOutput(new TextWriterOutput(new StringWriter()
                                {
                                    NewLine = "\n"
                                }));
                                var contextObj = new ScriptObject();
                                contextObj.Import(model);
                                context.PushGlobal(contextObj);
                                result = template.Render(context);
                            }

                            // Render async
                            {
                                var asyncContext = NewTemplateContext(lang);
                                asyncContext.PushOutput(new TextWriterOutput(new StringWriter()
                                {
                                    NewLine = "\n"
                                }));
                                var contextObj = new ScriptObject();
                                contextObj.Import(model);
                                asyncContext.PushGlobal(contextObj);
                                resultAsync = template.RenderAsync(asyncContext).Result;
                            }
                        }
                        catch (Exception exception)
                        {
                            hasException = true;
                            if (specialLiquid)
                            {
                                throw;
                            }
                            else
                            {
                                result = GetReason(exception);
                            }
                        }
                    }
                }

                var testContext = isRoundtrip ? "Roundtrip - " : String.Empty;
                Console.WriteLine($"{testContext}Result");
                Console.WriteLine("======================================");
                Console.WriteLine(result);
                Console.WriteLine($"{testContext}Expected");
                Console.WriteLine("======================================");
                Console.WriteLine(expected);

                if (isRoundtrip && expectParsingErrorForRountrip)
                {
                    Assert.True(hasErrors, "The roundtrip test is expecting an error");
                    Assert.AreNotEqual(expected, result);
                }
                else
                {
                    TextAssert.AreEqual(expected, result);
                }

                if (!isRoundtrip && !isRoundtripTest && !hasErrors && !hasException)
                {
                    Console.WriteLine("Checking async");
                    Console.WriteLine("======================================");
                    TextAssert.AreEqual(expected, resultAsync);
                }

                if (!supportRoundTrip || isRoundtripTest || isRoundtrip || hasErrors)
                {
                    break;
                }
            }
        }
Exemple #25
0
        public void TestFrontMatterOnly()
        {
            var options = new ParserOptions();

            var input = @"+++
variable = 1
name = 'yes'
+++
This is after the frontmatter: {{ name }}
{{
variable + 1
}}";

            input = input.Replace("\r\n", "\n");

            var lexer = new Lexer(input, null, new LexerOptions()
            {
                Mode = ScriptMode.FrontMatterOnly
            });
            var parser = new Parser(lexer, options);

            var page = parser.Run();

            foreach (var message in parser.Messages)
            {
                Console.WriteLine(message);
            }
            Assert.False(parser.HasErrors);

            // Check that the parser finished parsing on the first code exit }}
            // and hasn't tried to run the lexer on the remaining text
            Assert.AreEqual(new TextPosition(34, 4, 0), parser.CurrentSpan.Start);

            var startPositionAfterFrontMatter = page.FrontMatter.TextPositionAfterEndMarker;

            // Make sure that we have a front matter
            Assert.NotNull(page.FrontMatter);
            Assert.Null(page.Body);

            var context = new TemplateContext();

            // Evaluate front-matter
            var frontResult = context.Evaluate(page.FrontMatter);

            Assert.Null(frontResult);

            lexer = new Lexer(input, null, new LexerOptions()
            {
                StartPosition = startPositionAfterFrontMatter
            });
            parser = new Parser(lexer);
            page   = parser.Run();
            foreach (var message in parser.Messages)
            {
                Console.WriteLine(message);
            }
            Assert.False(parser.HasErrors);
            context.Evaluate(page);
            var pageResult = context.Output.ToString();

            TextAssert.AreEqual("This is after the frontmatter: yes\n2", pageResult);
        }