-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathIssueTests.cs
More file actions
916 lines (761 loc) · 34.5 KB
/
Copy pathIssueTests.cs
File metadata and controls
916 lines (761 loc) · 34.5 KB
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Dynamic;
using System.IO;
using System.Linq;
using HandlebarsDotNet.Collections;
using HandlebarsDotNet.Helpers;
using HandlebarsDotNet.PathStructure;
using HandlebarsDotNet.Runtime;
using HandlebarsDotNet.StringUtils;
using HandlebarsDotNet.ValueProviders;
using Xunit;
namespace HandlebarsDotNet.Test
{
public class IssueTests
{
// Issue https://github.com/zjklee/Handlebars.CSharp/issues/7
[Fact]
public void ValueVariableShouldNotBeAccessibleFromContext()
{
var handlebars = Handlebars.Create();
var render = handlebars.Compile("{{value}}");
var output = render(new
{
anotherValue = "Test"
});
Assert.Equal("", output);
}
// Issue https://github.com/rexm/Handlebars.Net/issues/351
[Fact]
public void PerhapsNull()
{
var handlebars = Handlebars.Create();
var render = handlebars.Compile("{{#if PerhapsNull}}It's not null{{else}}It's null{{/if}}");
dynamic data = new ExpandoObject();
data.PerhapsNull = null;
var actual = render(data);
Assert.Equal("It's null", actual);
}
// Issue https://github.com/rexm/Handlebars.Net/issues/350
// the helper has priority
// https://handlebarsjs.com/guide/expressions.html#disambiguating-helpers-calls-and-property-lookup
[Fact]
public void HelperWithSameNameVariable()
{
var handlebars = Handlebars.Create();
var expected = "Helper";
handlebars.RegisterHelper("foo", (context, arguments) => expected);
var template = handlebars.Compile("{{foo}}");
var data = new {foo = "Variable"};
var actual = template(data);
Assert.Equal(expected, actual);
}
// Issue https://github.com/rexm/Handlebars.Net/issues/350
[Fact]
public void LateBoundHelperWithSameNameVariable()
{
var handlebars = Handlebars.Create();
var template = handlebars.Compile("{{amoeba}}");
Assert.Equal("Variable", template(new {amoeba = "Variable"}));
handlebars.RegisterHelper("amoeba", (writer, context, arguments) => { writer.Write("Helper"); });
Assert.Equal("Helper", template(new {amoeba = "Variable"}));
}
// Issue https://github.com/rexm/Handlebars.Net/issues/350
[Fact]
public void LateBoundHelperWithSameNameVariablePath()
{
var handlebars = Handlebars.Create();
var expected = "Variable";
var template = handlebars.Compile("{{amoeba.a}}");
var data = new {amoeba = new {a = expected}};
var actual = template(data);
Assert.Equal(expected, actual);
handlebars.RegisterHelper("amoeba", (context, arguments) => "Helper");
actual = template(data);
Assert.Equal(expected, actual);
}
// Issue https://github.com/rexm/Handlebars.Net/issues/354
[Fact]
public void BlockHelperWithInversion()
{
string source = "{{^test input}}empty{{else}}not empty{{/test}}";
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("test", (output, options, context, arguments) =>
{
if (HandlebarsUtils.IsTruthy(arguments[0]))
{
options.Template(output, context);
}
else
{
options.Inverse(output, context);
}
});
var template = handlebars.Compile(source);
Assert.Equal("empty", template(null));
Assert.Equal("empty", template(new { otherInput = 1 }));
Assert.Equal("not empty", template(new { input = 1 }));
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/383
[Fact]
public void TestNestedPartials()
{
var innerPartial = @"{{#>outer-partial}}<br />
Begin inner partial<br />
Begin inner partial block<br />
{{>@partial-block}}
End inner partial block<br />
End inner partial<br />
{{/outer-partial}}";
var outerPartial = @"Begin outer partial<br />
Begin outer partial block
{{>@partial-block}}
End outer partial block<br />
End outer partial";
var view = @"{{#>inner-partial}}
View<br />
{{/inner-partial}}";
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("outer-partial", outerPartial);
handlebars.RegisterTemplate("inner-partial", innerPartial);
var callback = handlebars.Compile(view);
string result = callback(new object());
const string expected = @"Begin outer partial<br />
Begin outer partial block
<br />
Begin inner partial<br />
Begin inner partial block<br />
View<br />
End inner partial block<br />
End inner partial<br />
End outer partial block<br />
End outer partial";
Assert.Equal(expected, result);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/515
[Fact]
public void ValidContextInNestedPartialBlock()
{
const string template = @"{{#> [a/b] c=this }}{{c.value}}{{/ [a/b] }}";
const string partial = "{{c.value}} {{> @partial-block }}";
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("a/b", @partial);
var callback = handlebars.Compile(template);
var result = callback(new { value = 42 });
const string expected = @"42 42";
Assert.Equal(expected, result);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/395
[Fact]
public void RenderingWithUnusedPartial()
{
var handlebars = Handlebars.Create();
var mainTemplate = @"
{{>Navigation}}
";
var navPartial = @"
<div>
{{#each MenuItems}}
<div>Menu Item: {{Name}}</div>
{{/each}}
</div>";
// Remove the {{#if First}} section, and the test will pass
var unusedPartial = @"
{{#each Results}}
Result
{{#if HasSinglePackage}}
HasSinglePackage
{{#if First}}
First
{{/if}}
{{/if}}
{{/each}}";
var navTemplate = handlebars.Compile(mainTemplate);
using (var reader = new StringReader(navPartial))
{
handlebars.RegisterTemplate("Navigation", handlebars.Compile(reader));
}
// Comment this section out and the test will succeed
using (var reader = new StringReader(unusedPartial))
{
handlebars.RegisterTemplate("Unused", handlebars.Compile(reader));
}
// Attempted with concrete classes, still fails
var context = new
{
MenuItems = new[]
{
new { Name = "Getting Started"}
}
};
var transformed = navTemplate(context).Trim();
Assert.Equal(@"<div>
<div>Menu Item: Getting Started</div>
</div>", transformed);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/394
[Fact]
public void SlashesInTemplateKey()
{
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("Foo/bar", "hello world");
var compiled = handlebars.Compile("{{#>Foo/bar }} {{/Foo/bar}}");
var result = compiled(null);
Assert.Equal("hello world", result);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/399
[Fact]
public void PassesWhenMemberAccessorIsNull()
{
var template = "{{Join ['a', \"b \", 42] ':'}}";
var handlebars = Handlebars.Create();
handlebars.RegisterHelper(new JoinHelper());
var handlebarsTemplate = handlebars.Compile(template);
var actual = handlebarsTemplate("");
Assert.Equal("a:b :42", actual);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/387
[Fact]
public void ReverseIfCondition()
{
const string template = "{{^if false}}false{{/if}}";
var handlebars = Handlebars.Create();
var handlebarsTemplate = handlebars.Compile(template);
var actual = handlebarsTemplate(null);
Assert.Equal("false", actual);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/387
[Fact]
public void ReverseUnlessCondition()
{
const string template = "{{^unless true}}false{{/unless}}";
var handlebars = Handlebars.Create();
var handlebarsTemplate = handlebars.Compile(template);
var actual = handlebarsTemplate(null);
Assert.Equal("false", actual);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/387
[Fact]
public void ReverseEach()
{
const string template = "{{^each this}}false{{else}}{{@value}}{{/each}}";
var handlebars = Handlebars.Create();
var handlebarsTemplate = handlebars.Compile(template);
var actual = handlebarsTemplate(new[]{ 1, 2 });
Assert.Equal("12", actual);
actual = handlebarsTemplate(null);
Assert.Equal("false", actual);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/402
[Fact]
public void NestedObjectIteration()
{
const string template = @"
{{#with test}}
{{#if complexItems}}
<ul>
{{#each complexItems}}
<li>{{name}} {{value}} {{evenMoreComplex.name}} {{evenMoreComplex.abbr}}</li>
{{/each}}
</ul>
{{/if}}
{{/with}}";
var data = new
{
test = new
{
complexItems = new[] {
new { name = "a", value = 1, evenMoreComplex = new { name = "zzz", abbr = "z" } },
new { name = "b", value = 2, evenMoreComplex = new { name = "yyy", abbr = "y" } },
new { name = "c", value = 3, evenMoreComplex = new { name = "xxx", abbr = "x" } }
},
}
};
var handlebars = Handlebars.Create();
var handlebarsTemplate = handlebars.Compile(template);
var result = handlebarsTemplate(data);
const string expected = "<ul><li>a 1 zzz z</li><li>b 2 yyy y</li><li>c 3 xxx x</li></ul>";
var actual = result
.Replace("\n", string.Empty)
.Replace("\r", string.Empty)
.Replace("\t", string.Empty);
Assert.Equal(expected, actual);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/422
[Fact]
public void CallPartialInEach()
{
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("testPartial", " 42 ");
var source = "{{#each Fruits}}{{> testPartial aPartialParameter=\"couldBeAnything\"}}{{/each}}";
var template = handlebars.Compile(source);
var data = new
{
Fruits = new[] {"apple", "banana" }
};
var actual = template(data);
var expected = " 42 42 ";
Assert.Equal(expected, actual);
}
private class JoinHelper : IHelperDescriptor<HelperOptions>
{
public PathInfo Name { get; } = "join";
public object Invoke(in HelperOptions options, in Context context, in Arguments arguments)
{
return this.ReturnInvoke(options, context, arguments);
}
public void Invoke(in EncodedTextWriter output, in HelperOptions options, in Context context, in Arguments arguments)
{
var undefinedBindingResult = arguments.At<UndefinedBindingResult>(0);
var separator = arguments.At<string>(1);
var values = Substring.TrimStart(undefinedBindingResult.Value, '[');
values = Substring.TrimEnd(values, ']');
var substrings = Substring.Split(values, ',');
var extendedEnumerator = ExtendedEnumerator<Substring>.Create(substrings);
while (extendedEnumerator.MoveNext())
{
var substring = extendedEnumerator.Current.Value;
substring = Substring.Trim(substring, ' ');
substring = Substring.Trim(substring, '"');
substring = Substring.Trim(substring, '\'');
output.Write(substring);
if (!extendedEnumerator.Current.IsLast)
{
output.Write(separator);
}
}
}
}
// discussion: https://github.com/Handlebars-Net/Handlebars.Net/discussions/404
[Fact]
public void SwitchCaseTest()
{
const string template = @"
{{~#switch propertyValue}}
{{~#case 'a'}}a == {{@switchValue}}{{/case~}}
{{~#case 'b'}}b == {{@switchValue}}{{/case~}}
{{~#default}}the value is not provided{{/default~}}
{{/switch~}}";
var handlebars = Handlebars.Create();
handlebars.RegisterHelper(new CaseHelper());
handlebars.RegisterHelper(new SwitchHelper());
handlebars.RegisterHelper(new DefaultCaseHelper());
var handlebarsTemplate = handlebars.Compile(template);
var a = handlebarsTemplate(new {propertyValue = "a"});
var b = handlebarsTemplate(new {propertyValue = "b"});
var c = handlebarsTemplate(new {propertyValue = "c"});
Assert.Equal("a == a", a);
Assert.Equal("b == b", b);
Assert.Equal("the value is not provided", c);
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/300
[Fact]
public void PartialLayoutAndInlineBlock()
{
string layout = "{{#>body}}{{fallback}}{{/body}}";
string page = @"{{#>layout}}{{#*inline ""body""}}{{truebody}}{{/inline}}{{/body}}{{/layout}}";
var handlebars = Handlebars.Create();
var template = handlebars.Compile(page);
var data = new
{
fallback = "aaa",
truebody = "Hello world"
};
using (var reader = new StringReader(layout))
{
var partialTemplate = handlebars.Compile(reader);
handlebars.RegisterTemplate("layout", partialTemplate);
}
var result = template(data);
Assert.Equal("Hello world", result);
}
private class SwitchHelper : IHelperDescriptor<BlockHelperOptions>
{
public PathInfo Name { get; } = "switch";
public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments)
{
return this.ReturnInvoke(options, context, arguments);
}
public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments)
{
var switchFrame = options.CreateFrame();
var data = new DataValues(switchFrame);
data["switchValue"] = arguments[0];
data["__switchBlock"] = BoxedValues.True;
data["__switchCaseMatched"] = BoxedValues.False;
options.Template(output, switchFrame);
}
}
private class CaseHelper : IHelperDescriptor<BlockHelperOptions>
{
public PathInfo Name { get; } = "case";
public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments)
{
return this.ReturnInvoke(options, context, arguments);
}
public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments)
{
if (!(bool) options.Data["__switchBlock"]) throw new InvalidOperationException();
if((bool) options.Data["__switchCaseMatched"]) return;
var value = options.Data["switchValue"];
if(!Equals(value, arguments[0])) return;
var data = new DataValues(options.Frame);
data["__switchCaseMatched"] = BoxedValues.True;
options.Template(output, options.Frame); // execute `case` in switch context
}
}
private class DefaultCaseHelper : IHelperDescriptor<BlockHelperOptions>
{
public PathInfo Name { get; } = "default";
public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments)
{
return this.ReturnInvoke(options, context, arguments);
}
public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments)
{
if (!(bool) options.Data["__switchBlock"]) throw new InvalidOperationException();
if((bool) options.Data["__switchCaseMatched"]) return;
options.Template(output, options.Frame); // execute `default` in switch context
}
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/408
[Theory]
[ClassData(typeof(CollectionsOutOfRangeGenerator))]
public void Empty_string_if_index_is_out_of_range(IEnumerable input)
{
var handlebars = Handlebars.Create();
var render = handlebars.Compile("{{input.[1]}}");
object data = new { input };
var actual = render(data);
Assert.Equal("", actual);
}
private class EscapeExpressionGenerator : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
const string OKAY = "OKAY";
var chars = " !\"#%&'()*+,./;<=>@[\\]^`{|}~".ToCharArray();
var words = new[] { "true", "false","null", "undefined", "foo" };
var testList = new List<string>();
var theContext = new Dictionary<string, object>();
foreach (var word in words)
{
foreach (var @char in chars)
{
//You can't use the same identifier you use for literal notation.
if (@char == '[' || @char == ']') continue;
var theKeyWord = $"{word}{@char}{word}";
var testSegment = $"[{theKeyWord}]";
testList.Add(testSegment);
theContext[theKeyWord]=OKAY;
}
}
for (var index = 0; index < testList.Count; index++)
{
yield return new object[] { $"{{{{ { testList[index] } }}}}", OKAY, theContext };
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
private class CollectionsOutOfRangeGenerator : IEnumerable<object[]>
{
private readonly List<IEnumerable> _data = new List<IEnumerable>
{
new[] { "one" },
new List<string>{ "one" },
new HashSet<string>{ "one" },
new CustomReadOnlyList(new[] { "one" }),
Enumerable.Range(0, 1).Select(i => "one")
};
public IEnumerator<object[]> GetEnumerator() => _data.Select(o => new object[] { o }).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private class CustomReadOnlyList : IReadOnlyList<string>
{
private readonly IReadOnlyList<string> _readOnlyListImplementation;
public CustomReadOnlyList(IReadOnlyList<string> readOnlyListImplementation)
{
_readOnlyListImplementation = readOnlyListImplementation;
}
public IEnumerator<string> GetEnumerator()
{
return _readOnlyListImplementation.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _readOnlyListImplementation).GetEnumerator();
}
public int Count => _readOnlyListImplementation.Count;
public string this[int index] => _readOnlyListImplementation[index];
}
}
// issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/412
[Fact]
public void StructReflectionAccessor()
{
const string template = "{{Name}}";
var handlebars = Handlebars.Create();
var handlebarsTemplate = handlebars.Compile(template);
var actual = handlebarsTemplate(new CustomStruct
{
Name = "Foo"
});
Assert.Equal("Foo", actual);
}
private struct CustomStruct
{
public string Name { get; set; }
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/432
[Fact]
public void WeirdBehaviour()
{
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("displayListItem", "{{this}},");
handlebars.RegisterTemplate("displayList", "{{#each this}}{{> displayListItem}}{{/each}}");
var template = handlebars.Compile("{{> displayList TheList}}");
var actual1 = template(new ClassWithAList());
var actual2 = template(new ClassWithAListAndOtherMembers());
var expected = "";
Assert.Equal(expected, actual1);
Assert.Equal(expected, actual2);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/457
[Fact]
public void StringLength()
{
var handlebars = Handlebars.Create();
var render = handlebars.Compile("{{str.length}}");
object data = new { str = "string" };
var actual = render(data);
Assert.Equal("6", actual);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/470
[Theory]
[ClassData(typeof(EscapeExpressionGenerator))]
public void SegmentLiteralNotationTest(string template, string expected, Dictionary<string, object> context)
{
var handlebars = Handlebars.Create();
var renderer = handlebars.Compile(template);
var actual = renderer(context);
Assert.Equal(expected, actual);
}
private class ClassWithAList
{
public IEnumerable<string> TheList { get; set; }
}
private class ClassWithAListAndOtherMembers
{
public IEnumerable<string> TheList { get; set; }
public bool SomeBool { get; set; }
public string SomeString { get; set; } = "I shouldn't show up!";
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/468
// Issue refers to chinese characters, bug tested here affects any
// html char and any non-ascii character.
[Theory]
[InlineData(true, "<", "<")]
[InlineData(false, "<", "<")]
public void ConfigNoEscapeHtmlCharsShouldNotBeEscapedAfterWritingTripleCurlyValue(bool noEscape, string inputChar, string expectedChar)
{
// Affects any value written after execution of expression built in
// class UnencodedStatementVisitor when config NoEscape is true.
// Using triple curly brackets to trigger this case.
var template = "{{{ArbitraryText}}} {{HtmlSymbol}}";
var value = new
{
ArbitraryText = "text",
HtmlSymbol = inputChar
};
var expected = $"text {expectedChar}";
var config = new HandlebarsConfiguration
{
NoEscape = noEscape
};
var actual = Handlebars.Create(config).Compile(template).Invoke(value);
Assert.Equal(expected, actual);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/500
// Issue refers to the last letter being cut off when using
// keys set in context
[Fact]
public void LastLetterCutOff()
{
var context = ImmutableDictionary<string, object>.Empty
.Add("Name", "abcd");
var template = "{{.Name}}";
var compiledTemplate = Handlebars.Compile(template);
string templateOutput = compiledTemplate(context);
Assert.Equal("abcd", templateOutput);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/535
// Issue refers to invalid template causing OutOfMemoryException
[Fact]
public void UnrecognisedExpressionThrowsOutOfMemoryException()
{
var source = "{{Name | invalid}}";
Assert.Throws<HandlebarsCompilerException>(()=> Handlebars.Compile(source));
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/539
// Parent context (../) resolves to wrong value inside a custom block helper used within #each
[Fact]
public void Issue539_ParentContextInsideCustomBlockHelperInEach()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("ifCond", (writer, options, context, parameters) =>
{
if (parameters.Length == 3 && parameters[0]?.ToString() == parameters[2]?.ToString())
options.Template(writer, context);
else
options.Inverse(writer, context);
});
var source = @"{{#each loop}}{{#ifCond another '===' 'value'}}{{../this.foo}}{{/ifCond}}{{/each}}";
var template = handlebars.Compile(source);
var data = new { foo = "bar", loop = new object[] { new { another = "value" } } };
var result = template(data);
Assert.Equal("bar", result.Trim());
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/584
[Fact]
public void Issue584_EscapedDoubleQuoteInHelperStringArgument()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("myHelper", (writer, context, args) =>
{
writer.WriteSafeString(args[0]?.ToString() + "|" + args[1]?.ToString());
});
// Double-quoted string arg with escaped double-quote inside
var template = handlebars.Compile("{{myHelper name \"hello \\\"world\\\"\"}}");
var data = new { name = "test" };
var result = template(data);
Assert.Equal("test|hello \"world\"", result);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/584
[Fact]
public void Issue584_SingleQuoteStringArgStillWorks()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("myHelper", (context, args) => args[0]?.ToString());
var template = handlebars.Compile("{{myHelper 'hello world'}}");
var result = template(new { });
Assert.Equal("hello world", result);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/466
// Dictionary keys were inaccessible in nested #each when data is a mix of Dictionary and List
[Fact]
public void Issue466_NestedEachWithMixedDictionaryAndList()
{
var handlebars = Handlebars.Create();
var source = "{{#each this.users}}{{#each friends}}{{emailAddress}} {{/each}}{{/each}}";
var template = handlebars.Compile(source);
var friends = new List<Dictionary<object, object>>
{
new Dictionary<object, object> { { "emailAddress", "test@example.com" } }
};
var users = new List<Dictionary<object, object>>
{
new Dictionary<object, object> { { "friends", friends } }
};
var data = new Dictionary<object, object> { { "users", users } };
var result = template(data);
Assert.Contains("test@example.com", result);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/541
// DictionarySlim.AddOrReplace was missing a return after updating an existing key's value,
// causing it to always call AddValue even when the key already existed.
// Under sustained load (many IHandlebars instances each registering the same helper names),
// this caused unbounded growth in the internal dictionary leading to OutOfMemoryException.
[Fact]
public void RegisterHelperRepeatedly_ShouldNotCauseUnboundedGrowth()
{
// Each iteration creates a new IHandlebars instance and registers the same helper name.
// With the bug present, every RegisterHelper call adds a new entry even for the same key,
// causing unbounded growth in the internal DictionarySlim.
// With the fix, AddOrReplace correctly updates in-place and the count stays bounded.
const int iterations = 1000;
for (var i = 0; i < iterations; i++)
{
var hbs = Handlebars.Create();
hbs.RegisterHelper("myHelper", (output, context, arguments) =>
{
output.WriteSafeString("hello");
});
// Registering the same helper name again on the same instance should replace, not grow.
hbs.RegisterHelper("myHelper", (output, context, arguments) =>
{
output.WriteSafeString("world");
});
var template = hbs.Compile("{{myHelper}}");
var result = template(new { });
Assert.Equal("world", result);
}
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/541
// Tests that registering the same helper name multiple times on a single IHandlebars instance
// does not grow the internal helpers dictionary (AddOrReplace must truly replace, not append).
[Fact]
public void RegisterHelper_SameNameRepeatedly_ShouldNotGrowHelpersCount()
{
var hbs = Handlebars.Create();
// Register the same helper name many times.
for (var i = 0; i < 100; i++)
{
var captured = i;
hbs.RegisterHelper("myHelper", (output, context, arguments) =>
{
output.WriteSafeString(captured.ToString());
});
}
// With the bug, AddOrReplace was not returning after finding the key, so each
// registration added a new entry — the count would be 100 instead of 1.
// With the fix, each registration replaces the existing entry.
Assert.Single(hbs.Configuration.Helpers);
// Also verify the last-registered implementation is active.
var template = hbs.Compile("{{myHelper}}");
var result = template(new { });
Assert.Equal("99", result);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/519
[Fact]
public void Issue519_PartialBlockUsableAsBlockAndInIf()
{
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("myPartial",
@"Conditional:{{#if @partial-block}} {{> @partial-block}}{{/if}}
Plain: {{> @partial-block}}
Block:{{#> @partial-block }}{{/@partial-block}}");
var render = handlebars.Compile("{{#> myPartial}}Block content{{/myPartial}}");
var actual = render(new { });
Assert.Contains("Conditional: Block content", actual);
Assert.Contains("Plain: Block content", actual);
Assert.Contains("Block:Block content", actual);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/458
// System.NotImplementedException: byref delegate on Xamarin.iOS / Mono
// The Mono runtime does not support delegates with byref (in/ref) parameters.
// TemplateDelegate previously used `in EncodedTextWriter` which produced a
// byref delegate incompatible with Mono's AOT/JIT compiler.
[Fact]
public void Issue458_BasicTemplateCompilationAndRender()
{
// Validates the scenario that fails on Mono: simple compile + render
var handlebars = Handlebars.Create();
var render = handlebars.Compile("{{input}}");
object data = new { input = 42 };
var actual = render(data);
Assert.Equal("42", actual);
}
// Issue: https://github.com/Handlebars-Net/Handlebars.Net/issues/458
// Ensures block helpers still work after the byref delegate fix
[Fact]
public void Issue458_BlockHelperTemplateCompilationAndRender()
{
var handlebars = Handlebars.Create();
var render = handlebars.Compile("{{#if show}}visible{{/if}}");
var actual = render(new { show = true });
Assert.Equal("visible", actual);
}
}
}