Debian Codegraph @

tpl/internal/go_templates/htmltemplate/clone_test.go

raw
1 // Copyright 2011 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 //go:build !windows
6
7 package template
8
9 import (
10 "errors"
11 "fmt"
12 "io"
13 "strings"
14 "sync"
15 "testing"
16
17 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
18 )
19
20 func TestAddParseTreeHTML(t *testing.T) {
21 root := Must(New("root").Parse(`{{define "a"}} {{.}} {{template "b"}} {{.}} "></a>{{end}}`))
22 tree, err := parse.Parse("t", `{{define "b"}}<a href="{{end}}`, "", "", nil, nil)
23 if err != nil {
24 t.Fatal(err)
25 }
26 added := Must(root.AddParseTree("b", tree["b"]))
27 b := new(strings.Builder)
28 err = added.ExecuteTemplate(b, "a", "1>0")
29 if err != nil {
30 t.Fatal(err)
31 }
32 if got, want := b.String(), ` 1&gt;0 <a href=" 1%3e0 "></a>`; got != want {
33 t.Errorf("got %q want %q", got, want)
34 }
35 }
36
37 func TestClone(t *testing.T) {
38 // The {{.}} will be executed with data "<i>*/" in different contexts.
39 // In the t0 template, it will be in a text context.
40 // In the t1 template, it will be in a URL context.
41 // In the t2 template, it will be in a JavaScript context.
42 // In the t3 template, it will be in a CSS context.
43 const tmpl = `{{define "a"}}{{template "lhs"}}{{.}}{{template "rhs"}}{{end}}`
44 b := new(strings.Builder)
45
46 // Create an incomplete template t0.
47 t0 := Must(New("t0").Parse(tmpl))
48
49 // Clone t0 as t1.
50 t1 := Must(t0.Clone())
51 Must(t1.Parse(`{{define "lhs"}} <a href=" {{end}}`))
52 Must(t1.Parse(`{{define "rhs"}} "></a> {{end}}`))
53
54 // Execute t1.
55 b.Reset()
56 if err := t1.ExecuteTemplate(b, "a", "<i>*/"); err != nil {
57 t.Fatal(err)
58 }
59 if got, want := b.String(), ` <a href=" %3ci%3e*/ "></a> `; got != want {
60 t.Errorf("t1: got %q want %q", got, want)
61 }
62
63 // Clone t0 as t2.
64 t2 := Must(t0.Clone())
65 Must(t2.Parse(`{{define "lhs"}} <p onclick="javascript: {{end}}`))
66 Must(t2.Parse(`{{define "rhs"}} "></p> {{end}}`))
67
68 // Execute t2.
69 b.Reset()
70 if err := t2.ExecuteTemplate(b, "a", "<i>*/"); err != nil {
71 t.Fatal(err)
72 }
73 if got, want := b.String(), ` <p onclick="javascript: &#34;\u003ci\u003e*/&#34; "></p> `; got != want {
74 t.Errorf("t2: got %q want %q", got, want)
75 }
76
77 // Clone t0 as t3, but do not execute t3 yet.
78 t3 := Must(t0.Clone())
79 Must(t3.Parse(`{{define "lhs"}} <style> {{end}}`))
80 Must(t3.Parse(`{{define "rhs"}} </style> {{end}}`))
81
82 // Complete t0.
83 Must(t0.Parse(`{{define "lhs"}} ( {{end}}`))
84 Must(t0.Parse(`{{define "rhs"}} ) {{end}}`))
85
86 // Clone t0 as t4. Redefining the "lhs" template should not fail.
87 t4 := Must(t0.Clone())
88 if _, err := t4.Parse(`{{define "lhs"}} OK {{end}}`); err != nil {
89 t.Errorf(`redefine "lhs": got err %v want nil`, err)
90 }
91 // Cloning t1 should fail as it has been executed.
92 if _, err := t1.Clone(); err == nil {
93 t.Error("cloning t1: got nil err want non-nil")
94 }
95 // Redefining the "lhs" template in t1 should fail as it has been executed.
96 if _, err := t1.Parse(`{{define "lhs"}} OK {{end}}`); err == nil {
97 t.Error(`redefine "lhs": got nil err want non-nil`)
98 }
99
100 // Execute t0.
101 b.Reset()
102 if err := t0.ExecuteTemplate(b, "a", "<i>*/"); err != nil {
103 t.Fatal(err)
104 }
105 if got, want := b.String(), ` ( &lt;i&gt;*/ ) `; got != want {
106 t.Errorf("t0: got %q want %q", got, want)
107 }
108
109 // Clone t0. This should fail, as t0 has already executed.
110 if _, err := t0.Clone(); err == nil {
111 t.Error(`t0.Clone(): got nil err want non-nil`)
112 }
113
114 // Similarly, cloning sub-templates should fail.
115 if _, err := t0.Lookup("a").Clone(); err == nil {
116 t.Error(`t0.Lookup("a").Clone(): got nil err want non-nil`)
117 }
118 if _, err := t0.Lookup("lhs").Clone(); err == nil {
119 t.Error(`t0.Lookup("lhs").Clone(): got nil err want non-nil`)
120 }
121
122 // Execute t3.
123 b.Reset()
124 if err := t3.ExecuteTemplate(b, "a", "<i>*/"); err != nil {
125 t.Fatal(err)
126 }
127 if got, want := b.String(), ` <style> ZgotmplZ </style> `; got != want {
128 t.Errorf("t3: got %q want %q", got, want)
129 }
130 }
131
132 func TestTemplates(t *testing.T) {
133 names := []string{"t0", "a", "lhs", "rhs"}
134 // Some template definitions borrowed from TestClone.
135 const tmpl = `
136 {{define "a"}}{{template "lhs"}}{{.}}{{template "rhs"}}{{end}}
137 {{define "lhs"}} <a href=" {{end}}
138 {{define "rhs"}} "></a> {{end}}`
139 t0 := Must(New("t0").Parse(tmpl))
140 templates := t0.Templates()
141 if len(templates) != len(names) {
142 t.Errorf("expected %d templates; got %d", len(names), len(templates))
143 }
144 for _, name := range names {
145 found := false
146 for _, tmpl := range templates {
147 if name == tmpl.text.Name() {
148 found = true
149 break
150 }
151 }
152 if !found {
153 t.Error("could not find template", name)
154 }
155 }
156 }
157
158 // This used to crash; https://golang.org/issue/3281
159 func TestCloneCrash(t *testing.T) {
160 t1 := New("all")
161 Must(t1.New("t1").Parse(`{{define "foo"}}foo{{end}}`))
162 t1.Clone()
163 }
164
165 // Ensure that this guarantee from the docs is upheld:
166 // "Further calls to Parse in the copy will add templates
167 // to the copy but not to the original."
168 func TestCloneThenParse(t *testing.T) {
169 t0 := Must(New("t0").Parse(`{{define "a"}}{{template "embedded"}}{{end}}`))
170 t1 := Must(t0.Clone())
171 Must(t1.Parse(`{{define "embedded"}}t1{{end}}`))
172 if len(t0.Templates())+1 != len(t1.Templates()) {
173 t.Error("adding a template to a clone added it to the original")
174 }
175 // double check that the embedded template isn't available in the original
176 err := t0.ExecuteTemplate(io.Discard, "a", nil)
177 if err == nil {
178 t.Error("expected 'no such template' error")
179 }
180 }
181
182 // https://golang.org/issue/5980
183 func TestFuncMapWorksAfterClone(t *testing.T) {
184 funcs := FuncMap{"customFunc": func() (string, error) {
185 return "", errors.New("issue5980")
186 }}
187
188 // get the expected error output (no clone)
189 uncloned := Must(New("").Funcs(funcs).Parse("{{customFunc}}"))
190 wantErr := uncloned.Execute(io.Discard, nil)
191
192 // toClone must be the same as uncloned. It has to be recreated from scratch,
193 // since cloning cannot occur after execution.
194 toClone := Must(New("").Funcs(funcs).Parse("{{customFunc}}"))
195 cloned := Must(toClone.Clone())
196 gotErr := cloned.Execute(io.Discard, nil)
197
198 if wantErr.Error() != gotErr.Error() {
199 t.Errorf("clone error message mismatch want %q got %q", wantErr, gotErr)
200 }
201 }
202
203 // https://golang.org/issue/16101
204 func TestTemplateCloneExecuteRace(t *testing.T) {
205 const (
206 input = `<title>{{block "a" .}}a{{end}}</title><body>{{block "b" .}}b{{end}}<body>`
207 overlay = `{{define "b"}}A{{end}}`
208 )
209 outer := Must(New("outer").Parse(input))
210 tmpl := Must(Must(outer.Clone()).Parse(overlay))
211
212 var wg sync.WaitGroup
213 for i := 0; i < 10; i++ {
214 wg.Add(1)
215 go func() {
216 defer wg.Done()
217 for i := 0; i < 100; i++ {
218 if err := tmpl.Execute(io.Discard, "data"); err != nil {
219 panic(err)
220 }
221 }
222 }()
223 }
224 wg.Wait()
225 }
226
227 func TestTemplateCloneLookup(t *testing.T) {
228 // Template.escape makes an assumption that the template associated
229 // with t.Name() is t. Check that this holds.
230 tmpl := Must(New("x").Parse("a"))
231 tmpl = Must(tmpl.Clone())
232 if tmpl.Lookup(tmpl.Name()) != tmpl {
233 t.Error("after Clone, tmpl.Lookup(tmpl.Name()) != tmpl")
234 }
235 }
236
237 func TestCloneGrowth(t *testing.T) {
238 tmpl := Must(New("root").Parse(`<title>{{block "B". }}Arg{{end}}</title>`))
239 tmpl = Must(tmpl.Clone())
240 Must(tmpl.Parse(`{{define "B"}}Text{{end}}`))
241 for i := 0; i < 10; i++ {
242 tmpl.Execute(io.Discard, nil)
243 }
244 if len(tmpl.DefinedTemplates()) > 200 {
245 t.Fatalf("too many templates: %v", len(tmpl.DefinedTemplates()))
246 }
247 }
248
249 // https://golang.org/issue/17735
250 func TestCloneRedefinedName(t *testing.T) {
251 const base = `
252 {{ define "a" -}}<title>{{ template "b" . -}}</title>{{ end -}}
253 {{ define "b" }}{{ end -}}
254 `
255 const page = `{{ template "a" . }}`
256
257 t1 := Must(New("a").Parse(base))
258
259 for i := 0; i < 2; i++ {
260 t2 := Must(t1.Clone())
261 t2 = Must(t2.New(fmt.Sprintf("%d", i)).Parse(page))
262 err := t2.Execute(io.Discard, nil)
263 if err != nil {
264 t.Fatal(err)
265 }
266 }
267 }
268
269 // Issue 24791.
270 func TestClonePipe(t *testing.T) {
271 a := Must(New("a").Parse(`{{define "a"}}{{range $v := .A}}{{$v}}{{end}}{{end}}`))
272 data := struct{ A []string }{A: []string{"hi"}}
273 b := Must(a.Clone())
274 var buf strings.Builder
275 if err := b.Execute(&buf, &data); err != nil {
276 t.Fatal(err)
277 }
278 if got, want := buf.String(), "hi"; got != want {
279 t.Errorf("got %q want %q", got, want)
280 }
281 }