forked from sebastienros/fluid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParserTests.cs
1082 lines (901 loc) · 35.3 KB
/
ParserTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Fluid.Ast;
using Fluid.Parser;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Fluid.Tests
{
public class ParserTests
{
#if COMPILED
private static FluidParser _parser = new FluidParser().Compile();
#else
private static FluidParser _parser = new FluidParser();
#endif
private static IReadOnlyList<Statement> Parse(string source)
{
_parser.TryParse(source, out var template, out var errors);
return ((FluidTemplate)template).Statements;
}
private async Task CheckAsync(string source, string expected, Action<TemplateContext> init = null)
{
_parser.TryParse("{% if " + source + " %}true{% else %}false{% endif %}", out var template, out var messages);
var context = new TemplateContext();
init?.Invoke(context);
var result = await template.RenderAsync(context);
Assert.Equal(expected, result);
}
[Fact]
public void ShouldFiltersWithNamedArguments()
{
var statements = Parse("{{ a | b: c:1, 'value', d: 3 }}");
Assert.Single(statements);
var outputStatement = statements[0] as OutputStatement;
Assert.NotNull(outputStatement);
var filterExpression = outputStatement.Expression as FilterExpression;
Assert.NotNull(filterExpression);
Assert.Equal("b", filterExpression.Name);
var input = filterExpression.Input as MemberExpression;
Assert.NotNull(input);
Assert.Equal("c", filterExpression.Parameters[0].Name);
Assert.Null(filterExpression.Parameters[1].Name);
Assert.Equal("d", filterExpression.Parameters[2].Name);
}
[Fact]
public void ShouldParseText()
{
var statements = Parse("Hello World");
var textStatement = statements[0] as TextSpanStatement;
Assert.Single(statements);
Assert.NotNull(textStatement);
Assert.Equal("Hello World", textStatement.Text.ToString());
}
[Fact]
public void ShouldParseOutput()
{
var statements = Parse("{{ 1 }}");
var outputStatement = statements[0] as OutputStatement;
Assert.Single(statements);
Assert.NotNull(outputStatement);
}
[Theory]
[InlineData("{{ a }}")]
[InlineData("{{ a.b }}")]
[InlineData("{{ a.b[1] }}")]
public void ShouldParseOutputWithMember(string source)
{
var statements = Parse(source);
var outputStatement = statements[0] as OutputStatement;
Assert.Single(statements);
Assert.NotNull(outputStatement);
}
[Fact]
public void ShouldParseForTag()
{
var statements = Parse("{% for a in b %}{% endfor %}");
Assert.IsType<ForStatement>(statements.ElementAt(0));
}
[Fact]
public void ShouldParseForElseTag()
{
var statements = Parse("{% for a in b %}x{% else %}y{% endfor %}");
Assert.IsType<ForStatement>(statements.ElementAt(0));
var forStatement = statements.ElementAt(0) as ForStatement;
Assert.True(forStatement.Statements.Count == 1);
Assert.NotNull(forStatement.Else);
Assert.True((forStatement.Else is ElseStatement s) && s.Statements.Count == 1);
}
[Fact]
public void ShouldParseForLimitLiteral()
{
var statements = Parse("{% for item in items limit: 1 %}x{% endfor %}");
Assert.IsType<ForStatement>(statements.ElementAt(0));
var forStatement = statements.ElementAt(0) as ForStatement;
Assert.True(forStatement.Statements.Count == 1);
Assert.True(forStatement.Limit is LiteralExpression);
}
[Fact]
public void ShouldParseForLimitMember()
{
var statements = Parse("{% for item in items limit: limit %}x{% endfor %}");
Assert.IsType<ForStatement>(statements.ElementAt(0));
var forStatement = statements.ElementAt(0) as ForStatement;
Assert.True(forStatement.Statements.Count == 1);
Assert.True(forStatement.Limit is MemberExpression);
}
[Fact]
public void ShouldReadSingleCharInTag()
{
var statements = Parse(@"{% for a in b %};{% endfor %}");
Assert.Single(statements);
var text = ((ForStatement)statements[0]).Statements[0] as TextSpanStatement;
Assert.Equal(";", text.Text.ToString());
}
[Fact]
public void ShouldParseRaw()
{
var statements = Parse(@"{% raw %} on {{ this }} and {{{ that }}} {% endraw %}");
Assert.Single(statements);
Assert.IsType<RawStatement>(statements.ElementAt(0));
Assert.Equal(" on {{ this }} and {{{ that }}} ", (statements.ElementAt(0) as RawStatement).Text.ToString());
}
[Fact]
public void ShouldParseRawWithBlocks()
{
var statements = Parse(@"{% raw %} {%if true%} {%endif%} {% endraw %}");
Assert.Single(statements);
Assert.IsType<RawStatement>(statements.ElementAt(0));
Assert.Equal(" {%if true%} {%endif%} ", (statements.ElementAt(0) as RawStatement).Text.ToString());
}
[Fact]
public void ShouldParseEmptyRawTags()
{
var statements = Parse(@"{% raw %}{% endraw %}");
Assert.Single(statements);
Assert.IsType<RawStatement>(statements.ElementAt(0));
Assert.Equal("", (statements.ElementAt(0) as RawStatement).Text.ToString());
}
[Fact]
public void ShouldParseEmptyCommentTags()
{
var statements = Parse(@"{% comment %}{% endcomment %}");
Assert.Single(statements);
Assert.IsType<CommentStatement>(statements.ElementAt(0));
Assert.Equal("", (statements.ElementAt(0) as CommentStatement).Text.ToString());
}
[Fact]
public void ShouldParseComment()
{
var statements = Parse(@"{% comment %} on {{ this }} and {{{ that }}} {% endcomment %}");
Assert.Single(statements);
Assert.IsType<CommentStatement>(statements.ElementAt(0));
Assert.Equal(" on {{ this }} and {{{ that }}} ", (statements.ElementAt(0) as CommentStatement).Text.ToString());
}
[Fact]
public void ShouldParseCommentWithBlocks()
{
var statements = Parse(@"{% comment %} {%if true%} {%endif%} {% endcomment %}");
Assert.Single(statements);
Assert.IsType<CommentStatement>(statements.ElementAt(0));
Assert.Equal(" {%if true%} {%endif%} ", (statements.ElementAt(0) as CommentStatement).Text.ToString());
}
[Fact]
public void ShouldParseIfTag()
{
var statements = Parse("{% if true %}yes{% endif %}");
Assert.IsType<IfStatement>(statements.ElementAt(0));
Assert.True(statements.ElementAt(0) is IfStatement s && s.Statements.Count == 1);
}
[Fact]
public void ShouldParseIfElseTag()
{
var statements = Parse("{% if true %}yes{%else%}no{% endif %}");
var ifStatement = statements.ElementAt(0) as IfStatement;
Assert.NotNull(ifStatement);
Assert.Single(ifStatement.Statements);
Assert.NotNull(ifStatement.Else);
Assert.Empty(ifStatement.ElseIfs);
}
[Fact]
public void ShouldParseIfElseIfTag()
{
var statements = Parse("{% if true %}yes{%elsif a%}maybe{%else%}no{%endif%}");
var ifStatement = statements.ElementAt(0) as IfStatement;
Assert.NotNull(ifStatement);
Assert.Single(ifStatement.Statements);
Assert.NotNull(ifStatement.Else);
Assert.NotNull(ifStatement.ElseIfs);
}
[Theory]
[InlineData("abc { def")]
[InlineData("abc } def")]
[InlineData("abc }} def")]
[InlineData("abc { def }}")]
[InlineData("abc %} def")]
[InlineData("abc %}")]
[InlineData("%} def")]
[InlineData("abc }%} def")]
public void ShouldSucceedParseValidTemplate(string source)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result);
Assert.NotNull(template);
Assert.Null(errors);
}
[Theory]
[InlineData("abc {% {{ %} def")]
[InlineData("abc {% { %} def")]
public void ShouldFailParseInvalidTemplate(string source)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.False(result);
}
[Theory]
[InlineData("{% assign _foo = 1 %}")]
[InlineData("{% assign __foo = 1 %}")]
[InlineData("{% assign fo-o = 1 %}")]
[InlineData("{% assign fo_o = 1 %}")]
[InlineData("{% assign fo--o = 1 %}")]
[InlineData("{% assign fo__o = 1 %}")]
public void ShouldAcceptDashesInIdentifiers(string source)
{
var result = _parser.TryParse(source, out var template, out var error);
Assert.True(result);
}
[Theory]
[InlineData("{% assign 1f = 123 %}{{ 1f }}")]
[InlineData("{% assign 123f = 123 %}{{ 123f }}")]
[InlineData("{% assign 1_ = 123 %}{{ 1_ }}")]
[InlineData("{% assign 1-1 = 123 %}{{ 1-1 }}")]
public void ShouldAcceptDigitsAtStartOfIdentifiers(string source)
{
var result = _parser.TryParse(source, out var template, out var error);
Assert.True(result, error);
Assert.Equal("123", template.Render());
}
[Theory]
[InlineData(@"abc
{% {{ %}
def", "at (")]
[InlineData(@"{% assign username = ""John G. Chalmers-Smith"" %}
{% if username and username.size > 10 %}
Wow, {{ username }}, you have a long name!
{% else %}
Hello there {{ { }}!
{% endif %}", "at (")]
[InlineData(@"{% assign username = ""John G. Chalmers-Smith"" %}
{% if username and
username.size > 5 &&
username.size < 10 %}
Wow, {{ username }}, you have a longish name!
{% else %}
Hello there!
{% endif %}", "at (")]
public void ShouldFailParseInvalidTemplateWithCorrectLineNumber(string source, string expectedErrorEndString)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.Contains(expectedErrorEndString, errors);
}
[Theory]
[InlineData("{% for a in b %}")]
[InlineData("{% if true %}")]
[InlineData("{% unless true %}")]
[InlineData("{% case a %}")]
[InlineData("{% capture myVar %}")]
public void ShouldFailNotClosedBlock(string source)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.False(result);
Assert.NotNull(errors);
}
[Theory]
[InlineData("{% for a in b %} {% endfor %}")]
[InlineData("{% if true %} {% endif %}")]
[InlineData("{% unless true %} {% endunless %}")]
[InlineData("{% case a %} {% when 'cake' %} blah {% endcase %}")]
[InlineData("{% capture myVar %} capture me! {% endcapture %}")]
public void ShouldSucceedClosedBlock(string source)
{
var result = _parser.TryParse(source, out var template, out var error);
Assert.True(result);
Assert.NotNull(template);
Assert.Null(error);
}
[Fact]
public void ShouldAllowNewLinesInCase()
{
var result = _parser.TryParse(@"
{% case food %}
{% when 'cake' %}
yum
{% when 'rock' %}
yuck
{% endcase %}
", out var template, out var errors);
var context = new TemplateContext();
context.SetValue("food", "cake");
Assert.True(result);
Assert.NotNull(template);
Assert.Null(errors);
}
[Theory]
[InlineData("{{ 20 | divided_by: 7.0 | round: 2 }}", "2.86")]
[InlineData("{{ 20 | divided_by: 7 | round: 2 }}", "2")]
public void ShouldParseIntegralNumbers(string source, string expected)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal(expected, rendered);
}
[Fact]
public void ShouldIndexStringSegment()
{
var segment = new StringSegment("012345");
Assert.Equal('0', segment.Index(0));
Assert.Equal('5', segment.Index(-1));
segment = segment.Subsegment(1, 4);
Assert.Equal('1', segment.Index(0));
Assert.Equal('4', segment.Index(-1));
}
[Fact]
public void ShouldParseCurlyBraceInOutputStatements()
{
Parse("{{ 'on {0}' }}");
}
[Fact]
public void ShouldBeAbleToCompareNilValues()
{
// [1, 2, 3] | map will return [nil, nil, nil] then | uniq will try to call NilValue.GetHashCode()
var model = new
{
Doubles = new List<double> { 1.1, 2.2, 3.3 }
};
var template = "{{Doubles |map |uniq}}";
if (_parser.TryParse(template, out var result))
{
result.Render(new TemplateContext(model));
}
}
[Fact]
public void ShouldRegisterModelType()
{
var model = new
{
name = "Tobi"
};
var source = "{{name}}";
_parser.TryParse(source, out var template);
var rendered = template.Render(new TemplateContext(model));
Assert.Equal("Tobi", rendered);
}
[Theory]
[InlineData("{% for %}")]
[InlineData("{% case %}")]
[InlineData("{% if %}")]
[InlineData("{% unless %}")]
[InlineData("{% comment %}")]
[InlineData("{% raw %}")]
[InlineData("{% capture %}")]
public void ShouldThrowParseExceptionMissingTag(string template)
{
Assert.Throws<ParseException>(() => _parser.Parse(template));
}
[Theory]
[InlineData("{{ 'a\\nb' }}", "a\nb")]
[InlineData("{{ 'a\\tb' }}", "a\tb")]
public void ShouldParseEscapeSequences(string source, string expected)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result, errors);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal(expected, rendered);
}
[Theory]
[InlineData("{{ 'a\nb' }}", "a\nb")]
[InlineData("{{ 'a\r\nb' }}", "a\r\nb")]
public void ShouldParseLineBreaksInStringLiterals(string source, string expected)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result, errors);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal(expected, rendered);
}
[Theory]
[InlineData("{{ -3 }}", "-3")]
public void ShouldParseNegativeNumbers(string source, string expected)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal(expected, rendered);
}
[Theory]
[InlineData("{% assign my_integer = 7 %}{{ 20 | divided_by: my_integer }}", "2")]
[InlineData("{% assign my_integer = 7 %}{% assign my_float = my_integer | times: 1.0 %}{{ 20 | divided_by: my_float | round: 5 }}", "2.85714")]
[InlineData("{{ 183.357 | times: 12 }}", "2200.284")]
public void ShouldChangeVariableType(string source, string expected)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal(expected, rendered);
}
[Theory]
[InlineData("{% assign my_string = 'abcd' %}{{ my_string.size }}", "4")]
public void SizeAppliedToStrings(string source, string expected)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal(expected, rendered);
}
[Theory]
[InlineData("{{ '{{ {% %} }}' }}{% assign x = '{{ {% %} }}' %}{{ x }}", "{{ {% %} }}{{ {% %} }}")]
public void StringsCanContainCurlies(string source, string expected)
{
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal(expected, rendered);
}
[Fact]
public void ShouldSkipNewLinesInTags()
{
var source = @"{%
if
true
or
false
-%}
true
{%-
endif
%}";
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result, errors);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal("true", rendered);
}
[Fact]
public void ShouldSkipNewLinesInOutput()
{
var source = @"{{
true
}}";
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result, errors);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal("true", rendered);
}
[Theory]
[InlineData("'' == p", "false")]
[InlineData("p == ''", "false")]
[InlineData("p != ''", "true")]
[InlineData("p == nil", "true")]
[InlineData("p != nil", "false")]
[InlineData("nil == p", "true")]
[InlineData("p == blank", "true")]
[InlineData("blank == p ", "true")]
[InlineData("empty == blank", "true")]
[InlineData("blank == empty", "true")]
[InlineData("nil == blank", "true")]
[InlineData("blank == nil", "true")]
[InlineData("blank == ''", "true")]
[InlineData("'' == blank", "true")]
[InlineData("nil == ''", "false")]
[InlineData("'' == nil", "false")]
[InlineData("empty == ''", "true")]
[InlineData("'' == empty", "true")]
[InlineData("e == ''", "true")]
[InlineData("'' == e", "true")]
[InlineData("e == blank", "true")]
[InlineData("blank == e", "true")]
[InlineData("empty == nil", "false")]
[InlineData("nil == empty", "false")]
[InlineData("p != nil and p != ''", "false")]
[InlineData("p != '' and p != nil", "false")]
[InlineData("e != nil and e != ''", "false")]
[InlineData("e != '' and e != nil", "false")]
[InlineData("f != nil and f != ''", "true")]
[InlineData("f != '' and f != nil", "true")]
[InlineData("e == nil", "false")]
[InlineData("nil == e", "false")]
[InlineData("e == empty ", "true")]
[InlineData("empty == e ", "true")]
[InlineData("empty == f", "false")]
[InlineData("f == empty", "false")]
[InlineData("p == empty", "false")]
[InlineData("empty == p", "false")]
public Task EmptyShouldEqualToNil(string source, string expected)
{
return CheckAsync(source, expected, t => t.SetValue("e", "").SetValue("f", "hello"));
}
[Theory]
[InlineData("zero == empty", "false")]
[InlineData("empty == zero", "false")]
[InlineData("zero == blank", "false")]
[InlineData("blank == zero", "false")]
[InlineData("one == empty", "false")]
[InlineData("empty == one", "false")]
[InlineData("one == blank", "false")]
[InlineData("blank == one", "false")]
public Task EmptyShouldNotEqualNumbers(string source, string expected)
{
return CheckAsync(source, expected, t => t.SetValue("zero", 0).SetValue("one", 1));
}
[Theory]
[InlineData("blank == false", "true")]
[InlineData("empty == false", "false")]
public Task BlankShouldComparesToFalse(string source, string expected)
{
return CheckAsync(source, expected, t => t.SetValue("zero", 0).SetValue("one", 1));
}
[Fact]
public void ModelShouldNotImpactBlank()
{
var source = "{% assign a = ' ' %}{{ a == blank }}";
var model = new { a = " ", b = "" };
var context = new TemplateContext(model);
var template = _parser.Parse(source);
Assert.Equal("true", template.Render(context));
}
[Fact]
public void CycleShouldHandleNumbers()
{
var source = @"{% for i in (1..100) limit:9%}{% cycle 1, 2 ,3 %}<br />{% endfor %}";
var result = _parser.TryParse(source, out var template, out var errors);
Assert.True(result);
Assert.NotNull(template);
Assert.Null(errors);
var rendered = template.Render();
Assert.Equal("1<br />2<br />3<br />1<br />2<br />3<br />1<br />2<br />3<br />", rendered);
}
[Fact]
public void ShouldAssignWithLogicalExpression()
{
var source = @"{%- assign condition_temp = HasInheritance == false or ConvertConstructorInterfaceData | append: 'o' %}{{ condition_temp }}";
Assert.True(_parser.TryParse(source, out var template, out var _));
Assert.True(((FluidTemplate)template).Statements.Count == 2);
var rendered = template.Render();
Assert.Equal("falseo", rendered);
}
[Fact]
public void ShouldParseRecursiveIfs()
{
var source = @"
{%- if true %}
a1
{%- if true %}
b1
{%- if true %}
c1
{%- endif %}
{%- if true %}
c2
{%- endif %}
{%- endif %}
{%- if true %}
b2
{%- endif %}
a2
{%- endif %}
";
Assert.True(_parser.TryParse(source, out var template, out var _));
var rendered = template.Render();
Assert.Contains("a1", rendered);
Assert.Contains("b1", rendered);
Assert.Contains("c1", rendered);
Assert.Contains("c2", rendered);
Assert.Contains("b2", rendered);
Assert.Contains("a2", rendered);
}
[Fact]
public void ShouldParseNJsonSchema()
{
var source = @"
{%- if HasDescription %}
/** {{ Description }} */
{%- endif %}
{% if ExportTypes %}export {% endif %}{% if IsAbstract %}abstract {% endif %}class {{ ClassName }}{{ Inheritance }} {
{%- for property in Properties %}
{%- if property.HasDescription %}
/** {{ property.Description }} */
{%- endif %}
{% if property.IsReadOnly %}readonly {% endif %}{{ property.PropertyName }}{% if property.IsOptional %}?{% elsif RequiresStrictPropertyInitialization and property.HasDefaultValue == false %}!{% endif %}: {{ property.Type }}{{ property.TypePostfix }};
{%- endfor %}
{%- if HasIndexerProperty %}
[key: string]: {{ IndexerPropertyValueType }};
{%- endif %}
{%- if HasDiscriminator %}
protected _discriminator: string;
{%- endif %}
{%- assign condition_temp = HasInheritance == false or ConvertConstructorInterfaceData %}
{%- if GenerateConstructorInterface or HasBaseDiscriminator %}
constructor({% if GenerateConstructorInterface %}data?: I{{ ClassName }}{% endif %}) {
{%- if HasInheritance %}
super({% if GenerateConstructorInterface %}data{% endif %});
{%- endif %}
{%- if GenerateConstructorInterface and condition_temp %}
if (data) {
{%- if HasInheritance == false %}
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
{%- endif %}
{%- if ConvertConstructorInterfaceData %}
{%- for property in Properties %}
{%- if property.SupportsConstructorConversion %}
{%- if property.IsArray %}
if (data.{{ property.PropertyName }}) {
this.{{ property.PropertyName }} = [];
for (let i = 0; i < data.{{ property.PropertyName }}.length; i++) {
let item = data.{{ property.PropertyName }}[i];
this.{{ property.PropertyName }}[i] = item && !(<any>item).toJSON ? new {{ property.ArrayItemType }}(item) : <{{ property.ArrayItemType }}>item;
}
}
{%- elsif property.IsDictionary %}
if (data.{{ property.PropertyName }}) {
this.{{ property.PropertyName }} = {};
for (let key in data.{{ property.PropertyName }}) {
if (data.{{ property.PropertyName }}.hasOwnProperty(key)) {
let item = data.{{ property.PropertyName }}[key];
this.{{ property.PropertyName }}[key] = item && !(<any>item).toJSON ? new {{ property.DictionaryItemType }}(item) : <{{ property.DictionaryItemType }}>item;
}
}
}
{%- else %}
this.{{ property.PropertyName }} = data.{{ property.PropertyName }} && !(<any>data.{{ property.PropertyName }}).toJSON ? new {{ property.Type }}(data.{{ property.PropertyName }}) : <{{ property.Type }}>this.{{ property.PropertyName }};
{%- endif %}
{%- endif %}
{%- endfor %}
{%- endif %}
}
{%- endif %}
{%- if HasDefaultValues %}
{% if GenerateConstructorInterface %}if (!data) {% endif %}{
{%- for property in Properties %}
{%- if property.HasDefaultValue %}
this.{{ property.PropertyName }} = {{ property.DefaultValue }};
{%- endif %}
{%- endfor %}
}
{%- endif %}
{%- if HasBaseDiscriminator %}
this._discriminator = ""{{ DiscriminatorName }}"";
{%- endif %}
}
{%- endif %}
init(_data?: any{% if HandleReferences %}, _mappings?: any{% endif %}) {
{%- if HasInheritance %}
super.init(_data);
{%- endif %}
{%- if HasIndexerProperty or HasProperties %}
if (_data) {
{%- if HasIndexerProperty %}
for (var property in _data) {
if (_data.hasOwnProperty(property))
this[property] = _data[property];
}
{%- endif %}
{%- for property in Properties %}
{{ property.ConvertToClassCode | tab }}
{%- endfor %}
}
{%- endif %}
}
static fromJS(data: any{% if HandleReferences %}, _mappings?: any{% endif %}): {{ ClassName }}{% if HandleReferences %} | null{% endif %} {
data = typeof data === 'object' ? data : {};
{%- if HandleReferences %}
{%- if HasBaseDiscriminator %}
{%- for derivedClass in DerivedClasses %}
if (data[""{{ BaseDiscriminator }}""] === ""{{ derivedClass.Discriminator }}"")
{%- if derivedClass.IsAbstract %}
throw new Error(""The abstract class '{{ derivedClass.ClassName }}' cannot be instantiated."");
{%- else %}
return createInstance<{{ derivedClass.ClassName }}>(data, _mappings, {{ derivedClass.ClassName }});
{%- endif %}
{%- endfor %}
{%- endif %}
{%- if IsAbstract %}
throw new Error(""The abstract class '{{ ClassName }}' cannot be instantiated."");
{%- else %}
return createInstance<{{ ClassName }}>(data, _mappings, {{ ClassName }});
{%- endif %}
{%- else %}
{%- if HasBaseDiscriminator %}
{%- for derivedClass in DerivedClasses %}
if (data[""{{ BaseDiscriminator }}""] === ""{{ derivedClass.Discriminator }}"") {
{%- if derivedClass.IsAbstract %}
throw new Error(""The abstract class '{{ derivedClass.ClassName }}' cannot be instantiated."");
{%- else %}
let result = new {{ derivedClass.ClassName }}();
result.init(data);
return result;
{%- endif %}
}
{%- endfor %}
{%- endif %}
{%- if IsAbstract %}
throw new Error(""The abstract class '{{ ClassName }}' cannot be instantiated."");
{%- else %}
let result = new {{ ClassName }}();
result.init(data);
return result;
{%- endif %}
{%- endif %}
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
{%- if HasIndexerProperty %}
for (var property in this) {
if (this.hasOwnProperty(property))
data[property] = this[property];
}
{%- endif %}
{%- if HasDiscriminator %}
data[""{{ BaseDiscriminator }}""] = this._discriminator;
{%- endif %}
{%- for property in Properties %}
{{ property.ConvertToJavaScriptCode | tab }}
{%- endfor %}
{%- if HasInheritance %}
super.toJSON(data);
{%- endif %}
return data;
}
{%- if GenerateCloneMethod %}
clone(): {{ ClassName }} {
{%- if IsAbstract %}
throw new Error(""The abstract class '{{ ClassName }}' cannot be instantiated."");
{%- else %}
const json = this.toJSON();
let result = new {{ ClassName }}();
result.init(json);
return result;
{%- endif %}
}
{%- endif %}
}
{%- if GenerateConstructorInterface %}
{%- if HasDescription %}
/** {{ Description }} */
{%- endif %}
{% if ExportTypes %}export {% endif %}interface I{{ ClassName }}{{ InterfaceInheritance }} {
{%- for property in Properties %}
{%- if property.HasDescription %}
/** {{ property.Description }} */
{%- endif %}
{{ property.PropertyName }}{% if property.IsOptional %}?{% endif %}: {{ property.ConstructorInterfaceType }}{{ property.TypePostfix }};
{%- endfor %}
{%- if HasIndexerProperty %}
[key: string]: {{ IndexerPropertyValueType }};
{%- endif %}
}
{%- endif %}
";
Assert.True(_parser.TryParse(source, out var template, out var _));
var rendered = template.Render();
Assert.Equal(@"
class {
init(_data?: any) {
}
static fromJS(data: any): {
data = typeof data === 'object' ? data : {};
let result = new ();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
return data;
}
}
", rendered);
}
[Theory]
[InlineData("{{1}}", "1")]
[InlineData("{{-1-}}", "1")]
[InlineData("{%-assign len='1,2,3'|split:','|size-%}{{len}}", "3")] // size-%} is ambiguous and can be read as "size -%}" or "size- %}"
public async Task ShouldSupportCompactNotation(string source, string expected)
{
Assert.True(_parser.TryParse(source, out var template, out var _));
var context = new TemplateContext();
var result = await template.RenderAsync(context);
Assert.Equal(expected, result);
}
[Fact]
public void ShouldParseEchoTag()
{
var source = @"{% echo 'welcome to the liquid tag' | upcase %}";
Assert.True(_parser.TryParse(source, out var template, out var errors), errors);
var rendered = template.Render();
Assert.Contains("WELCOME TO THE LIQUID TAG", rendered);
}
[Fact]
public void ShouldParseLiquidTag()
{
var source = @"
{%
liquid
echo
'welcome ' | upcase
echo 'to the liquid tag'
| upcase
%}";
Assert.True(_parser.TryParse(source, out var template, out var errors), errors);
var rendered = template.Render();
Assert.Contains("WELCOME TO THE LIQUID TAG", rendered);
}
[Fact]
public void ShouldParseLiquidTagWithBlocks()
{
var source = @"
{% liquid assign cool = true
if cool