hugo_template_test.go (2403B)
1 // Copyright 2022 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package template
15
16 import (
17 "bytes"
18 "context"
19 "reflect"
20 "strings"
21 "testing"
22
23 qt "github.com/frankban/quicktest"
24 "github.com/gohugoio/hugo/common/hreflect"
25 )
26
27 type TestStruct struct {
28 S string
29 M map[string]string
30 }
31
32 func (t TestStruct) Hello1(arg string) string {
33 return arg
34 }
35
36 func (t TestStruct) Hello2(arg1, arg2 string) string {
37 return arg1 + " " + arg2
38 }
39
40 type execHelper struct{}
41
42 func (e *execHelper) Init(ctx context.Context, tmpl Preparer) {
43 }
44
45 func (e *execHelper) GetFunc(ctx context.Context, tmpl Preparer, name string) (reflect.Value, reflect.Value, bool) {
46 if name == "print" {
47 return zero, zero, false
48 }
49 return reflect.ValueOf(func(s string) string {
50 return "hello " + s
51 }), zero, true
52 }
53
54 func (e *execHelper) GetMapValue(ctx context.Context, tmpl Preparer, m, key reflect.Value) (reflect.Value, bool) {
55 key = reflect.ValueOf(strings.ToLower(key.String()))
56 return m.MapIndex(key), true
57 }
58
59 func (e *execHelper) GetMethod(ctx context.Context, tmpl Preparer, receiver reflect.Value, name string) (method reflect.Value, firstArg reflect.Value) {
60 if name != "Hello1" {
61 return zero, zero
62 }
63 m := hreflect.GetMethodByName(receiver, "Hello2")
64 return m, reflect.ValueOf("v2")
65 }
66
67 func TestTemplateExecutor(t *testing.T) {
68 c := qt.New(t)
69
70 templ, err := New("").Parse(`
71 {{ print "foo" }}
72 {{ printf "hugo" }}
73 Map: {{ .M.A }}
74 Method: {{ .Hello1 "v1" }}
75
76 `)
77
78 c.Assert(err, qt.IsNil)
79
80 ex := NewExecuter(&execHelper{})
81
82 var b bytes.Buffer
83 data := TestStruct{S: "sv", M: map[string]string{"a": "av"}}
84
85 c.Assert(ex.ExecuteWithContext(context.Background(), templ, &b, data), qt.IsNil)
86 got := b.String()
87
88 c.Assert(got, qt.Contains, "foo")
89 c.Assert(got, qt.Contains, "hello hugo")
90 c.Assert(got, qt.Contains, "Map: av")
91 c.Assert(got, qt.Contains, "Method: v2 v1")
92 }