github.com/gohugoio/hugo@v0.88.1/tpl/internal/go_templates/texttemplate/hugo_template_test.go (about) 1 // Copyright 2019 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 "reflect" 19 "strings" 20 "testing" 21 22 qt "github.com/frankban/quicktest" 23 ) 24 25 type TestStruct struct { 26 S string 27 M map[string]string 28 } 29 30 func (t TestStruct) Hello1(arg string) string { 31 return arg 32 } 33 34 func (t TestStruct) Hello2(arg1, arg2 string) string { 35 return arg1 + " " + arg2 36 } 37 38 type execHelper struct { 39 } 40 41 func (e *execHelper) GetFunc(tmpl Preparer, name string) (reflect.Value, bool) { 42 if name == "print" { 43 return zero, false 44 } 45 return reflect.ValueOf(func(s string) string { 46 return "hello " + s 47 }), true 48 } 49 50 func (e *execHelper) GetMapValue(tmpl Preparer, m, key reflect.Value) (reflect.Value, bool) { 51 key = reflect.ValueOf(strings.ToLower(key.String())) 52 return m.MapIndex(key), true 53 } 54 55 func (e *execHelper) GetMethod(tmpl Preparer, receiver reflect.Value, name string) (method reflect.Value, firstArg reflect.Value) { 56 if name != "Hello1" { 57 return zero, zero 58 } 59 m := receiver.MethodByName("Hello2") 60 return m, reflect.ValueOf("v2") 61 } 62 63 func TestTemplateExecutor(t *testing.T) { 64 c := qt.New(t) 65 66 templ, err := New("").Parse(` 67 {{ print "foo" }} 68 {{ printf "hugo" }} 69 Map: {{ .M.A }} 70 Method: {{ .Hello1 "v1" }} 71 72 `) 73 74 c.Assert(err, qt.IsNil) 75 76 ex := NewExecuter(&execHelper{}) 77 78 var b bytes.Buffer 79 data := TestStruct{S: "sv", M: map[string]string{"a": "av"}} 80 81 c.Assert(ex.Execute(templ, &b, data), qt.IsNil) 82 got := b.String() 83 84 c.Assert(got, qt.Contains, "foo") 85 c.Assert(got, qt.Contains, "hello hugo") 86 c.Assert(got, qt.Contains, "Map: av") 87 c.Assert(got, qt.Contains, "Method: v2 v1") 88 89 }