-
-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathpongo2_issues_test.go
More file actions
2473 lines (2271 loc) · 69.9 KB
/
pongo2_issues_test.go
File metadata and controls
2473 lines (2271 loc) · 69.9 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
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
package pongo2_test
import (
"fmt"
"io"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/fstest"
"time"
"unicode/utf8"
"github.com/flosch/pongo2/v7"
)
func TestIssue151(t *testing.T) {
tpl, err := pongo2.FromString("{{ mydict.51232_3 }}{{ 12345_123}}{{ 995189baz }}")
if err != nil {
t.Fatal(err)
}
str, err := tpl.Execute(pongo2.Context{
"mydict": map[string]string{
"51232_3": "foo",
},
"12345_123": "bar",
"995189baz": "baz",
})
if err != nil {
t.Fatal(err)
}
if str != "foobarbaz" {
t.Fatalf("Expected output 'foobarbaz', but got '%s'.", str)
}
}
func TestIssue297(t *testing.T) {
// wordwrap wraps at character width (matching Django's behavior),
// not at word count.
tpl, err := pongo2.FromString("Testing: {{ input|wordwrap:20 }}!")
if err != nil {
t.Fatal(err)
}
str, err := tpl.Execute(pongo2.Context{"input": "one two three four five six"})
if err != nil {
t.Fatal(err)
}
expected := "Testing: one two three four\nfive six!"
if str != expected {
t.Fatalf("Expected `%s`, but got `%s`.", expected, str)
}
}
func TestIssue289(t *testing.T) {
// Test negative integer in filter argument
tpl, err := pongo2.FromString("{{ variable|add:-1 }}")
if err != nil {
t.Fatal(err)
}
str, err := tpl.Execute(pongo2.Context{"variable": 5})
if err != nil {
t.Fatal(err)
}
if str != "4" {
t.Fatalf("Expected '4', but got '%s'.", str)
}
// Test negative float in filter argument
tpl, err = pongo2.FromString("{{ variable|add:-1.5 }}")
if err != nil {
t.Fatal(err)
}
str, err = tpl.Execute(pongo2.Context{"variable": 5.0})
if err != nil {
t.Fatal(err)
}
if str != "3.500000" {
t.Fatalf("Expected '3.500000', but got '%s'.", str)
}
}
func TestIssue338(t *testing.T) {
// Test that include with 'with' clause works inside a for loop
// that iterates over a map with a single variable.
// Bug: {% for key in map %} was setting Private[""] = value for maps,
// which caused errors when include copied the context.
// See: https://github.com/flosch/pongo2/issues/338
memFS := fstest.MapFS{
"main.tpl": &fstest.MapFile{
Data: []byte(`{% for key in mymap %}{% include "field.html" with name=key id="test" %}{% endfor %}`),
},
"field.html": &fstest.MapFile{
Data: []byte(`<label for="{{ id }}">{{ name }}</label>`),
},
}
loader := pongo2.NewFSLoader(memFS)
set := pongo2.NewSet("test", loader)
tpl, err := set.FromFile("main.tpl")
if err != nil {
t.Fatalf("failed to load template: %v", err)
}
ctx := pongo2.Context{
"mymap": map[string]string{
"a": "1",
"b": "2",
},
}
result, err := tpl.Execute(ctx)
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
// Should render the label twice with keys from the map
// Map iteration order is not guaranteed, so check for both possible outputs
expected1 := `<label for="test">a</label><label for="test">b</label>`
expected2 := `<label for="test">b</label><label for="test">a</label>`
if result != expected1 && result != expected2 {
t.Errorf("expected %q or %q, got %q", expected1, expected2, result)
}
}
func TestIssue343(t *testing.T) {
// Test \n escape sequence (newline) - the main issue
tpl, err := pongo2.FromString(`{% for val in my_string|split:"\n" %}[{{ val }}]{% endfor %}`)
if err != nil {
t.Fatal(err)
}
str, err := tpl.Execute(pongo2.Context{"my_string": "Line 1\nLine 2\nLine 3"})
if err != nil {
t.Fatal(err)
}
if str != "[Line 1][Line 2][Line 3]" {
t.Fatalf(`Expected "[Line 1][Line 2][Line 3]", but got %q`, str)
}
// Test \t escape sequence (tab)
tpl, err = pongo2.FromString(`{% for val in my_string|split:"\t" %}[{{ val }}]{% endfor %}`)
if err != nil {
t.Fatal(err)
}
str, err = tpl.Execute(pongo2.Context{"my_string": "A\tB\tC"})
if err != nil {
t.Fatal(err)
}
if str != "[A][B][C]" {
t.Fatalf(`Expected "[A][B][C]", but got %q`, str)
}
// Test \r escape sequence (carriage return)
tpl, err = pongo2.FromString(`{% for val in my_string|split:"\r" %}[{{ val }}]{% endfor %}`)
if err != nil {
t.Fatal(err)
}
str, err = tpl.Execute(pongo2.Context{"my_string": "X\rY\rZ"})
if err != nil {
t.Fatal(err)
}
if str != "[X][Y][Z]" {
t.Fatalf(`Expected "[X][Y][Z]", but got %q`, str)
}
// Test \' escape sequence in single-quoted strings
// Use |safe to prevent autoescape from converting ' to '
tpl, err = pongo2.FromString(`{{ 'it\'s working'|safe }}`)
if err != nil {
t.Fatal(err)
}
str, err = tpl.Execute(nil)
if err != nil {
t.Fatal(err)
}
if str != "it's working" {
t.Fatalf(`Expected "it's working", but got %q`, str)
}
// Test \\n produces literal backslash+n, not newline
tpl, err = pongo2.FromString(`{{ "hello\\nworld" }}`)
if err != nil {
t.Fatal(err)
}
str, err = tpl.Execute(nil)
if err != nil {
t.Fatal(err)
}
if str != "hello\\nworld" {
t.Fatalf(`Expected "hello\\nworld" (literal backslash-n), but got %q`, str)
}
// Test existing escape sequences still work: \"
// Use |safe to prevent autoescape from converting " to "
tpl, err = pongo2.FromString(`{{ "say \"hello\""|safe }}`)
if err != nil {
t.Fatal(err)
}
str, err = tpl.Execute(nil)
if err != nil {
t.Fatal(err)
}
if str != `say "hello"` {
t.Fatalf(`Expected 'say "hello"', but got %q`, str)
}
// Test existing escape sequences still work: \\
tpl, err = pongo2.FromString(`{{ "back\\slash" }}`)
if err != nil {
t.Fatal(err)
}
str, err = tpl.Execute(nil)
if err != nil {
t.Fatal(err)
}
if str != "back\\slash" {
t.Fatalf(`Expected "back\\slash", but got %q`, str)
}
}
func TestIssue341(t *testing.T) {
// Test that comparing two undefined/missing variables returns True
// Bug: {{ _missing == null }} returned False on master but True in v6.0.0
// Both _missing and null are undefined, so they should be equal.
// See: https://github.com/flosch/pongo2/issues/341
tests := []struct {
name string
template string
context pongo2.Context
expected string
}{
{
name: "two missing variables are equal",
template: "{{ _missing == _also_missing }}",
context: pongo2.Context{},
expected: "True",
},
{
name: "missing variable equals undefined literal",
template: "{{ _missing == null }}",
context: pongo2.Context{},
expected: "True",
},
{
name: "missing variable not equal to defined value",
template: "{{ _missing == defined }}",
context: pongo2.Context{"defined": "value"},
expected: "False",
},
{
name: "missing variable not equal to empty string",
template: "{{ _missing == '' }}",
context: pongo2.Context{},
expected: "False",
},
{
name: "missing variable not equal to zero",
template: "{{ _missing == 0 }}",
context: pongo2.Context{},
expected: "False",
},
{
name: "nil context value equals missing variable",
template: "{{ nil_value == _missing }}",
context: pongo2.Context{"nil_value": nil},
expected: "True",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tpl, err := pongo2.FromString(tt.template)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result, err := tpl.Execute(tt.context)
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
if result != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, result)
}
})
}
}
func TestIssue322(t *testing.T) {
// Test for data race in FromFile when called concurrently.
// The race was on firstTemplateCreated field being written without synchronization.
// See: https://github.com/flosch/pongo2/issues/322
memFS := fstest.MapFS{
"index.html": &fstest.MapFile{
Data: []byte(`<h1>{{ status }}</h1>`),
},
}
loader := pongo2.NewFSLoader(memFS)
set := pongo2.NewSet("test", loader)
const numGoroutines = 100
var wg sync.WaitGroup
wg.Add(numGoroutines)
for range numGoroutines {
go func() {
defer wg.Done()
tpl, err := set.FromFile("index.html")
if err != nil {
t.Errorf("FromFile failed: %v", err)
return
}
_, err = tpl.Execute(pongo2.Context{"status": "Hello World"})
if err != nil {
t.Errorf("Execute failed: %v", err)
}
}()
}
wg.Wait()
}
func TestIssue209(t *testing.T) {
// Test that "not X in Y" is correctly parsed as "not (X in Y)"
// Bug: "not X in Y" was being parsed as "(not X) in Y" due to
// incorrect operator precedence. The "not" operator should have
// lower precedence than "in".
// See: https://github.com/flosch/pongo2/issues/209
tests := []struct {
name string
template string
context pongo2.Context
expected string
}{
{
name: "not in - element exists",
template: `{% if not "Hello" in text %}is not{% else %}is{% endif %}`,
context: pongo2.Context{"text": "<h2>Hello!</h2><p>Welcome"},
expected: "is",
},
{
name: "not in - element does not exist",
template: `{% if not "World" in text %}is not{% else %}is{% endif %}`,
context: pongo2.Context{"text": "<h2>Hello!</h2><p>Welcome"},
expected: "is not",
},
{
name: "not in with list - element exists",
template: `{% if not 2 in numbers %}not found{% else %}found{% endif %}`,
context: pongo2.Context{"numbers": []int{1, 2, 3}},
expected: "found",
},
{
name: "not in with list - element does not exist",
template: `{% if not 5 in numbers %}not found{% else %}found{% endif %}`,
context: pongo2.Context{"numbers": []int{1, 2, 3}},
expected: "not found",
},
{
name: "not in with map - key exists",
template: `{% if not "foo" in mymap %}not found{% else %}found{% endif %}`,
context: pongo2.Context{"mymap": map[string]int{"foo": 1, "bar": 2}},
expected: "found",
},
{
name: "not in with map - key does not exist",
template: `{% if not "baz" in mymap %}not found{% else %}found{% endif %}`,
context: pongo2.Context{"mymap": map[string]int{"foo": 1, "bar": 2}},
expected: "not found",
},
{
name: "double negation - not not in", //nolint:dupword
template: `{% if not not "Hello" in text %}yes{% else %}no{% endif %}`, //nolint:dupword
context: pongo2.Context{"text": "Hello World"},
expected: "yes",
},
{
name: "not in combined with and",
template: `{% if flag and not "x" in text %}yes{% else %}no{% endif %}`,
context: pongo2.Context{"flag": true, "text": "abc"},
expected: "yes",
},
{
name: "not in combined with or",
template: `{% if not "x" in text or flag %}yes{% else %}no{% endif %}`,
context: pongo2.Context{"flag": false, "text": "abc"},
expected: "yes",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tpl, err := pongo2.FromString(tt.template)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result, err := tpl.Execute(tt.context)
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
if result != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, result)
}
})
}
}
func TestIssue237(t *testing.T) {
// Test that ifchanged with else clause works correctly when content doesn't change.
// Bug: ifchanged without watched expressions would panic or not render else block
// when the content doesn't change.
// See: https://github.com/flosch/pongo2/issues/237
tests := []struct {
name string
template string
context pongo2.Context
expected string
}{
{
name: "content-based ifchanged with else - content changes",
template: `{% for item in items %}{% ifchanged %}{{ item }}{% else %}*{% endifchanged %}{% endfor %}`,
context: pongo2.Context{"items": []string{"a", "b", "b", "c"}},
expected: "ab*c",
},
{
name: "content-based ifchanged with else - all same",
template: `{% for item in items %}{% ifchanged %}{{ item }}{% else %}*{% endifchanged %}{% endfor %}`,
context: pongo2.Context{"items": []string{"a", "a", "a"}},
expected: "a**",
},
{
name: "content-based ifchanged without else",
template: `{% for item in items %}{% ifchanged %}[{{ item }}]{% endifchanged %}{% endfor %}`,
context: pongo2.Context{"items": []string{"a", "a", "b", "b", "c"}},
expected: "[a][b][c]",
},
{
name: "expression-based ifchanged with else",
template: `{% for item in items %}{% ifchanged item %}{{ item }}{% else %}*{% endifchanged %}{% endfor %}`,
context: pongo2.Context{"items": []string{"a", "a", "b", "c", "c"}},
expected: "a*bc*",
},
{
name: "expression-based ifchanged without else",
template: `{% for item in items %}{% ifchanged item %}[{{ item }}]{% endifchanged %}{% endfor %}`,
context: pongo2.Context{"items": []string{"a", "a", "b", "b"}},
expected: "[a][b]",
},
{
name: "nested loop with content-based ifchanged and else",
template: `{% for outer in outers %}{% for inner in inners %}{% ifchanged %}{{ outer }}-{{ inner }}{% else %}*{% endifchanged %}{% endfor %}{% endfor %}`,
context: pongo2.Context{
"outers": []string{"A", "B"},
"inners": []string{"1", "1", "2"},
},
expected: "A-1*A-2B-1*B-2",
},
{
name: "nested loop with expression-based ifchanged without else",
template: `{% for outer in outers %}{% for inner in inners %}{% ifchanged inner %}[{{ outer }}-{{ inner }}]{% endifchanged %}{% endfor %}{% endfor %}`,
context: pongo2.Context{
"outers": []string{"A", "B"},
"inners": []string{"1", "1", "2"},
},
expected: "[A-1][A-2][B-1][B-2]",
},
{
name: "nested loop with content-based ifchanged without else - original issue scenario",
template: `{% for outer in outers %}{% for inner in inners %}{% ifchanged %}{{ inner }}{% endifchanged %}{% endfor %}{% endfor %}`,
context: pongo2.Context{
"outers": []string{"A", "B"},
"inners": []string{"x", "x", "y"},
},
expected: "xyxy",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tpl, err := pongo2.FromString(tt.template)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result, err := tpl.Execute(tt.context)
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
if result != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, result)
}
})
}
}
func TestBugStringByteIndexing(t *testing.T) {
// Bug: String indexing used byte offset instead of rune offset.
// For multi-byte UTF-8 characters (e.g., Chinese, emoji), accessing
// string[1] would return a garbled byte instead of the second character.
// This affects both integer index access (e.g., "var.0") and subscript
// access (e.g., "var[idx]").
tests := []struct {
name string
template string
context pongo2.Context
expected string
}{
{
name: "ASCII string index 0",
template: `{{ s.0 }}`,
context: pongo2.Context{"s": "hello"},
expected: "h",
},
{
name: "ASCII string index 1",
template: `{{ s.1 }}`,
context: pongo2.Context{"s": "hello"},
expected: "e",
},
{
name: "multi-byte string index 0",
template: `{{ s.0 }}`,
context: pongo2.Context{"s": "日本語"},
expected: "日",
},
{
name: "multi-byte string index 1",
template: `{{ s.1 }}`,
context: pongo2.Context{"s": "日本語"},
expected: "本",
},
{
name: "multi-byte string index 2",
template: `{{ s.2 }}`,
context: pongo2.Context{"s": "日本語"},
expected: "語",
},
{
name: "mixed ASCII and multi-byte index",
template: `{{ s.1 }}`,
context: pongo2.Context{"s": "aüc"},
expected: "ü",
},
{
name: "subscript access multi-byte string",
template: `{{ s[idx] }}`,
context: pongo2.Context{"s": "日本語", "idx": 2},
expected: "語",
},
{
name: "out of bounds returns empty for multi-byte",
template: `{{ s.3 }}`,
context: pongo2.Context{"s": "日本語"},
expected: "",
},
{
name: "emoji string indexing",
template: `{{ s.1 }}`,
context: pongo2.Context{"s": "A😀B"},
expected: "😀",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tpl, err := pongo2.FromString(tt.template)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result, err := tpl.Execute(tt.context)
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
if result != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, result)
}
})
}
}
func TestBugLjustRjustErrorMessage(t *testing.T) {
// Bug: ljust and rjust used %c format verb instead of %d in error messages.
// With maxCharPadding=10000, %c would render U+2710 (✐) instead of "10000".
tests := []struct {
name string
template string
expectedContain string
}{
{
name: "ljust error contains number not unicode",
template: `{{ "x"|ljust:20000 }}`,
expectedContain: "10000",
},
{
name: "rjust error contains number not unicode",
template: `{{ "x"|rjust:20000 }}`,
expectedContain: "10000",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tpl, err := pongo2.FromString(tt.template)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
_, err = tpl.Execute(nil)
if err == nil {
t.Fatal("expected an error but got none")
}
errMsg := err.Error()
if !strings.Contains(errMsg, tt.expectedContain) {
t.Errorf("error message should contain %q, got %q", tt.expectedContain, errMsg)
}
})
}
}
func TestBugAutoescapeNotRestoredOnError(t *testing.T) {
// Bug: tagAutoescapeNode.Execute did not restore ctx.Autoescape when
// wrapper.Execute returned an error. The fix uses defer to ensure
// the autoescape state is always restored.
tpl, err := pongo2.FromString(`{% autoescape off %}{{ safe }}{% endautoescape %}{{ unsafe }}`)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result, err := tpl.Execute(pongo2.Context{
"safe": "<b>bold</b>",
"unsafe": "<script>xss</script>",
})
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
expected := "<b>bold</b><script>xss</script>"
if result != expected {
t.Errorf("expected %q, got %q", expected, result)
}
// Nested autoescape blocks restore correctly.
tpl2, err := pongo2.FromString(`{% autoescape off %}{% autoescape on %}{{ inner }}{% endautoescape %}{{ outer }}{% endautoescape %}`)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result2, err := tpl2.Execute(pongo2.Context{
"inner": "<i>inner</i>",
"outer": "<b>outer</b>",
})
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
expected2 := "<i>inner</i><b>outer</b>"
if result2 != expected2 {
t.Errorf("expected %q, got %q", expected2, result2)
}
}
func TestBugLexerColumnMultiByteUTF8(t *testing.T) {
// Bug: The lexer incremented col by byte width instead of 1 for each rune.
// For multi-byte UTF-8 characters, error column numbers would be wrong.
tests := []struct {
name string
template string
expectedCol string
}{
{
name: "error column with only ASCII (baseline)",
template: "abc{{ invalid_syntax( }}",
expectedCol: "Col 23",
},
{
name: "error column after multi-byte chars",
template: "日本語{{ invalid_syntax( }}",
expectedCol: "Col 23",
},
{
name: "error column after mixed ASCII and multi-byte",
template: "aüc{{ invalid_syntax( }}",
expectedCol: "Col 23",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := pongo2.FromString(tt.template)
if err == nil {
t.Fatal("expected a parse error but got none")
}
errMsg := err.Error()
if !strings.Contains(errMsg, tt.expectedCol) {
t.Errorf("error message should contain %q, got %q", tt.expectedCol, errMsg)
}
})
}
}
func TestBugNegateFloatReturns1Point1(t *testing.T) {
// Bug: Negate() returned float64(1.1) instead of float64(1.0) when
// negating a zero float value. This was a typo in the source code.
tpl, err := pongo2.FromString(`{% if not zero_float %}yes{% else %}no{% endif %}`)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result, err := tpl.Execute(pongo2.Context{"zero_float": 0.0})
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
if result != "yes" {
t.Errorf("expected %q, got %q", "yes", result)
}
tpl2, err := pongo2.FromString(`{{ zero_float|default:"fallback" }}`)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result2, err := tpl2.Execute(pongo2.Context{"zero_float": 0.0})
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
if result2 != "fallback" {
t.Errorf("expected %q, got %q", "fallback", result2)
}
// Test that negated non-zero float gives 0.0
v := pongo2.AsValue(3.14)
negated := v.Negate()
if negated.Float() != 0.0 {
t.Errorf("Negate() of non-zero float should be 0.0, got %v", negated.Float())
}
// Test that negated zero float gives 1.0 (not 1.1)
v2 := pongo2.AsValue(0.0)
negated2 := v2.Negate()
if negated2.Float() != 1.0 {
t.Errorf("Negate() of zero float should be 1.0, got %v", negated2.Float())
}
}
func TestBugWidthratioDoubleRounding(t *testing.T) {
// Bug: widthratio used Ceil(x + 0.5) which double-rounds.
// For exact integer results like 50/100*200 = 100.0,
// Ceil(100.0 + 0.5) = 101 instead of the correct 100.
tests := []struct {
name string
template string
expected string
}{
{
name: "exact integer result not inflated",
template: `{% widthratio 50 100 200 %}`,
expected: "100",
},
{
name: "exact integer result 75/100*400",
template: `{% widthratio 75 100 400 %}`,
expected: "300",
},
{
name: "fractional result rounds correctly",
template: `{% widthratio 175 200 100 %}`,
expected: "88",
},
{
name: "small fraction rounds down",
template: `{% widthratio 1 3 100 %}`,
expected: "33",
},
{
name: "zero value",
template: `{% widthratio 0 100 200 %}`,
expected: "0",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tpl, err := pongo2.FromString(tt.template)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
result, err := tpl.Execute(nil)
if err != nil {
t.Fatalf("failed to execute template: %v", err)
}
if result != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, result)
}
})
}
}
func TestBugIfnotequalErrorMessage(t *testing.T) {
// Bug: ifnotequal's error message incorrectly says "ifequal" instead of "ifnotequal".
_, err := pongo2.FromString(`{% ifnotequal a b c %}{% endifnotequal %}`)
if err == nil {
t.Fatal("expected an error but got none")
}
errMsg := err.Error()
if !strings.Contains(errMsg, "ifnotequal") {
t.Errorf("error message should mention 'ifnotequal', got %q", errMsg)
}
}
func TestBugCycleSharedState(t *testing.T) {
// Bug: tagCycleNode.idx was stored on the AST node, which is shared
// across all concurrent executions of the same parsed template.
// This caused two problems:
// 1. Data race: concurrent idx++ without synchronization
// 2. Semantic bug: one execution's cycle position affected another,
// producing wrong output (e.g., "bcabca" instead of "abcabc")
//
// Each template execution must have independent cycle state.
tpl, err := pongo2.FromString(`{% for i in items %}{% cycle "a" "b" "c" %}{% endfor %}`)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
ctx := pongo2.Context{"items": []int{1, 2, 3, 4, 5, 6}}
const expected = "abcabc"
// First: verify sequential executions produce consistent results.
// With shared state on the node, the second execution would start
// where the first left off (idx=6), producing wrong output.
for i := range 5 {
result, err := tpl.Execute(ctx)
if err != nil {
t.Fatalf("execution %d: unexpected error: %v", i, err)
}
if result != expected {
t.Errorf("execution %d: got %q, want %q", i, result, expected)
}
}
// Second: verify concurrent executions are also correct.
var wg sync.WaitGroup
for range 20 {
wg.Add(1)
go func() {
defer wg.Done()
result, err := tpl.Execute(ctx)
if err != nil {
t.Errorf("concurrent: unexpected error: %v", err)
return
}
if result != expected {
t.Errorf("concurrent: got %q, want %q", result, expected)
}
}()
}
wg.Wait()
}
func TestBugIfchangedSharedState(t *testing.T) {
// Bug: tagIfchangedNode.lastValues and lastContent were stored on the
// AST node, which is shared across all concurrent executions.
// This caused two problems:
// 1. Data race: concurrent writes to lastValues/lastContent
// 2. Semantic bug: ifchanged compares against state from a DIFFERENT
// execution, so the first item might be suppressed if a previous
// execution ended with the same value.
//
// Each template execution must have independent ifchanged state.
tpl, err := pongo2.FromString(`{% for item in items %}{% ifchanged %}{{ item }}{% endifchanged %}{% endfor %}`)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
ctx := pongo2.Context{"items": []string{"a", "a", "b", "b", "c"}}
const expected = "abc"
// First: verify sequential executions produce consistent results.
// With shared state, the second execution starts with lastContent="c"
// from the first execution, so "a" would be correctly shown (different
// from "c"), but the pattern breaks in more complex scenarios.
// Use a case where it definitely breaks: items starting with the same
// value the previous execution ended with.
tplSameEnd, err := pongo2.FromString(`{% for item in items %}{% ifchanged %}{{ item }}{% endifchanged %}{% endfor %}`)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
// Items end with "x", so next execution starting with "x" would skip it
ctxEndsX := pongo2.Context{"items": []string{"a", "b", "x"}}
ctxStartsX := pongo2.Context{"items": []string{"x", "y", "z"}}
// First execution ends with lastContent="x"
result1, err := tplSameEnd.Execute(ctxEndsX)
if err != nil {
t.Fatalf("execution 1: unexpected error: %v", err)
}
if result1 != "abx" {
t.Errorf("execution 1: got %q, want %q", result1, "abx")
}
// Second execution should output "x" even though previous ended with "x"
result2, err := tplSameEnd.Execute(ctxStartsX)
if err != nil {
t.Fatalf("execution 2: unexpected error: %v", err)
}
if result2 != "xyz" {
t.Errorf("execution 2: got %q, want %q (ifchanged state leaked from previous execution)", result2, "xyz")
}
// Also verify concurrent executions produce correct results.
var wg2 sync.WaitGroup
for range 20 {
wg2.Add(1)
go func() {
defer wg2.Done()
result, err := tpl.Execute(ctx)
if err != nil {
t.Errorf("concurrent: unexpected error: %v", err)
return
}
if result != expected {
t.Errorf("concurrent: got %q, want %q", result, expected)
}
}()
}
wg2.Wait()
}
func TestBugWidthratioDivisionByZero(t *testing.T) {
// Bug: widthratio does not check for division by zero when max=0.
// Django returns "0" in this case.
tests := []struct {
name string
template string
expected string
}{
{
name: "max is zero literal",
template: `{% widthratio 50 0 200 %}`,
expected: "0",
},
{
name: "max is zero variable",
template: `{% widthratio value max_value width %}`,
expected: "0",
},
{
name: "all zeros",
template: `{% widthratio 0 0 0 %}`,
expected: "0",
},
{
name: "max zero with as variable",
template: `{% widthratio 50 0 200 as result %}{{ result }}`,
expected: "0",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tpl, err := pongo2.FromString(tt.template)
if err != nil {
t.Fatalf("failed to parse template: %v", err)
}
ctx := pongo2.Context{"value": 50, "max_value": 0, "width": 200}
result, err := tpl.Execute(ctx)
if err != nil {