Debian Codegraph @

tpl/internal/go_templates/htmltemplate/template_test.go

raw
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package template_test
6
7 import (
8 "bytes"
9 "encoding/json"
10 "strings"
11 "testing"
12
13 . "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
14 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
15 )
16
17 func TestTemplateClone(t *testing.T) {
18 // https://golang.org/issue/12996
19 orig := New("name")
20 clone, err := orig.Clone()
21 if err != nil {
22 t.Fatal(err)
23 }
24 if len(clone.Templates()) != len(orig.Templates()) {
25 t.Fatalf("Invalid length of t.Clone().Templates()")
26 }
27
28 const want = "stuff"
29 parsed := Must(clone.Parse(want))
30 var buf strings.Builder
31 err = parsed.Execute(&buf, nil)
32 if err != nil {
33 t.Fatal(err)
34 }
35 if got := buf.String(); got != want {
36 t.Fatalf("got %q; want %q", got, want)
37 }
38 }
39
40 func TestRedefineNonEmptyAfterExecution(t *testing.T) {
41 c := newTestCase(t)
42 c.mustParse(c.root, `foo`)
43 c.mustExecute(c.root, nil, "foo")
44 c.mustNotParse(c.root, `bar`)
45 }
46
47 func TestRedefineEmptyAfterExecution(t *testing.T) {
48 c := newTestCase(t)
49 c.mustParse(c.root, ``)
50 c.mustExecute(c.root, nil, "")
51 c.mustNotParse(c.root, `foo`)
52 c.mustExecute(c.root, nil, "")
53 }
54
55 func TestRedefineAfterNonExecution(t *testing.T) {
56 c := newTestCase(t)
57 c.mustParse(c.root, `{{if .}}<{{template "X"}}>{{end}}{{define "X"}}foo{{end}}`)
58 c.mustExecute(c.root, 0, "")
59 c.mustNotParse(c.root, `{{define "X"}}bar{{end}}`)
60 c.mustExecute(c.root, 1, "&lt;foo>")
61 }
62
63 func TestRedefineAfterNamedExecution(t *testing.T) {
64 c := newTestCase(t)
65 c.mustParse(c.root, `<{{template "X" .}}>{{define "X"}}foo{{end}}`)
66 c.mustExecute(c.root, nil, "&lt;foo>")
67 c.mustNotParse(c.root, `{{define "X"}}bar{{end}}`)
68 c.mustExecute(c.root, nil, "&lt;foo>")
69 }
70
71 func TestRedefineNestedByNameAfterExecution(t *testing.T) {
72 c := newTestCase(t)
73 c.mustParse(c.root, `{{define "X"}}foo{{end}}`)
74 c.mustExecute(c.lookup("X"), nil, "foo")
75 c.mustNotParse(c.root, `{{define "X"}}bar{{end}}`)
76 c.mustExecute(c.lookup("X"), nil, "foo")
77 }
78
79 func TestRedefineNestedByTemplateAfterExecution(t *testing.T) {
80 c := newTestCase(t)
81 c.mustParse(c.root, `{{define "X"}}foo{{end}}`)
82 c.mustExecute(c.lookup("X"), nil, "foo")
83 c.mustNotParse(c.lookup("X"), `bar`)
84 c.mustExecute(c.lookup("X"), nil, "foo")
85 }
86
87 func TestRedefineSafety(t *testing.T) {
88 c := newTestCase(t)
89 c.mustParse(c.root, `<html><a href="{{template "X"}}">{{define "X"}}{{end}}`)
90 c.mustExecute(c.root, nil, `<html><a href="">`)
91 // Note: Every version of Go prior to Go 1.8 accepted the redefinition of "X"
92 // on the next line, but luckily kept it from being used in the outer template.
93 // Now we reject it, which makes clearer that we're not going to use it.
94 c.mustNotParse(c.root, `{{define "X"}}" bar="baz{{end}}`)
95 c.mustExecute(c.root, nil, `<html><a href="">`)
96 }
97
98 func TestRedefineTopUse(t *testing.T) {
99 c := newTestCase(t)
100 c.mustParse(c.root, `{{template "X"}}{{.}}{{define "X"}}{{end}}`)
101 c.mustExecute(c.root, 42, `42`)
102 c.mustNotParse(c.root, `{{define "X"}}<script>{{end}}`)
103 c.mustExecute(c.root, 42, `42`)
104 }
105
106 func TestRedefineOtherParsers(t *testing.T) {
107 c := newTestCase(t)
108 c.mustParse(c.root, ``)
109 c.mustExecute(c.root, nil, ``)
110 if _, err := c.root.ParseFiles("no.template"); err == nil || !strings.Contains(err.Error(), "Execute") {
111 t.Errorf("ParseFiles: %v\nwanted error about already having Executed", err)
112 }
113 if _, err := c.root.ParseGlob("*.no.template"); err == nil || !strings.Contains(err.Error(), "Execute") {
114 t.Errorf("ParseGlob: %v\nwanted error about already having Executed", err)
115 }
116 if _, err := c.root.AddParseTree("t1", c.root.Tree); err == nil || !strings.Contains(err.Error(), "Execute") {
117 t.Errorf("AddParseTree: %v\nwanted error about already having Executed", err)
118 }
119 }
120
121 func TestNumbers(t *testing.T) {
122 c := newTestCase(t)
123 c.mustParse(c.root, `{{print 1_2.3_4}} {{print 0x0_1.e_0p+02}}`)
124 c.mustExecute(c.root, nil, "12.34 7.5")
125 }
126
127 func TestStringsInScriptsWithJsonContentTypeAreCorrectlyEscaped(t *testing.T) {
128 // See #33671 and #37634 for more context on this.
129 tests := []struct{ name, in string }{
130 {"empty", ""},
131 {"invalid", string(rune(-1))},
132 {"null", "\u0000"},
133 {"unit separator", "\u001F"},
134 {"tab", "\t"},
135 {"gt and lt", "<>"},
136 {"quotes", `'"`},
137 {"ASCII letters", "ASCII letters"},
138 {"Unicode", "ʕ⊙ϖ⊙ʔ"},
139 {"Pizza", "🍕"},
140 }
141 const (
142 prefix = `<script type="application/ld+json">`
143 suffix = `</script>`
144 templ = prefix + `"{{.}}"` + suffix
145 )
146 tpl := Must(New("JS string is JSON string").Parse(templ))
147 for _, tt := range tests {
148 t.Run(tt.name, func(t *testing.T) {
149 var buf bytes.Buffer
150 if err := tpl.Execute(&buf, tt.in); err != nil {
151 t.Fatalf("Cannot render template: %v", err)
152 }
153 trimmed := bytes.TrimSuffix(bytes.TrimPrefix(buf.Bytes(), []byte(prefix)), []byte(suffix))
154 var got string
155 if err := json.Unmarshal(trimmed, &got); err != nil {
156 t.Fatalf("Cannot parse JS string %q as JSON: %v", trimmed[1:len(trimmed)-1], err)
157 }
158 if got != tt.in {
159 t.Errorf("Serialization changed the string value: got %q want %q", got, tt.in)
160 }
161 })
162 }
163 }
164
165 func TestSkipEscapeComments(t *testing.T) {
166 c := newTestCase(t)
167 tr := parse.New("root")
168 tr.Mode = parse.ParseComments
169 newT, err := tr.Parse("{{/* A comment */}}{{ 1 }}{{/* Another comment */}}", "", "", make(map[string]*parse.Tree))
170 if err != nil {
171 t.Fatalf("Cannot parse template text: %v", err)
172 }
173 c.root, err = c.root.AddParseTree("root", newT)
174 if err != nil {
175 t.Fatalf("Cannot add parse tree to template: %v", err)
176 }
177 c.mustExecute(c.root, nil, "1")
178 }
179
180 type testCase struct {
181 t *testing.T
182 root *Template
183 }
184
185 func newTestCase(t *testing.T) *testCase {
186 return &testCase{
187 t: t,
188 root: New("root"),
189 }
190 }
191
192 func (c *testCase) lookup(name string) *Template {
193 return c.root.Lookup(name)
194 }
195
196 func (c *testCase) mustParse(t *Template, text string) {
197 _, err := t.Parse(text)
198 if err != nil {
199 c.t.Fatalf("parse: %v", err)
200 }
201 }
202
203 func (c *testCase) mustNotParse(t *Template, text string) {
204 _, err := t.Parse(text)
205 if err == nil {
206 c.t.Fatalf("parse: unexpected success")
207 }
208 }
209
210 func (c *testCase) mustExecute(t *Template, val any, want string) {
211 var buf strings.Builder
212 err := t.Execute(&buf, val)
213 if err != nil {
214 c.t.Fatalf("execute: %v", err)
215 }
216 if buf.String() != want {
217 c.t.Fatalf("template output:\n%s\nwant:\n%s", buf.String(), want)
218 }
219 }