src/text/template/exec_test.go GO 2,022 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 2,022.
1// Copyright 2011 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.45package template67import (8	"bytes"9	"errors"10	"flag"11	"fmt"12	"io"13	"iter"14	"reflect"15	"strings"16	"sync"17	"testing"18	"unsafe"19)2021var debug = flag.Bool("debug", false, "show the errors produced by the tests")2223// T has lots of interesting pieces to use to test execution.24type T struct {25	// Basics26	True        bool27	I           int28	U16         uint1629	X, S        string30	FloatZero   float6431	ComplexZero complex12832	// Nested structs.33	U *U34	// Struct with String method.35	V0     V36	V1, V2 *V37	// Struct with Error method.38	W0     W39	W1, W2 *W40	// Slices41	SI      []int42	SICap   []int43	SIEmpty []int44	SB      []bool45	// Arrays46	AI  [3]int47	PAI *[3]int // pointer to array48	// Maps49	MSI      map[string]int50	MSIone   map[string]int // one element, for deterministic output51	MSIEmpty map[string]int52	MXI      map[any]int53	MII      map[int]int54	MI32S    map[int32]string55	MI64S    map[int64]string56	MUI32S   map[uint32]string57	MUI64S   map[uint64]string58	MI8S     map[int8]string59	MUI8S    map[uint8]string60	SMSI     []map[string]int61	// Empty interfaces; used to see if we can dig inside one.62	Empty0 any // nil63	Empty1 any64	Empty2 any65	Empty3 any66	Empty4 any67	// Non-empty interfaces.68	NonEmptyInterface         I69	NonEmptyInterfacePtS      *I70	NonEmptyInterfaceNil      I71	NonEmptyInterfaceTypedNil I72	// Stringer.73	Str fmt.Stringer74	Err error75	// Pointers76	PI       *int77	PS       *string78	PSI      *[]int79	NIL      *int80	UPI      unsafe.Pointer81	EmptyUPI unsafe.Pointer82	// Function (not method)83	BinaryFunc             func(string, string) string84	VariadicFunc           func(...string) string85	VariadicFuncInt        func(int, ...string) string86	NilOKFunc              func(*int) bool87	ErrFunc                func() (string, error)88	PanicFunc              func() string89	TooFewReturnCountFunc  func()90	TooManyReturnCountFunc func() (string, error, int)91	InvalidReturnTypeFunc  func() (string, bool)92	// Template to test evaluation of templates.93	Tmpl *Template94	// Unexported field; cannot be accessed by template.95	unexported int96}9798type S []string99100func (S) Method0() string {101	return "M0"102}103104type U struct {105	V string106}107108type V struct {109	j int110}111112func (v *V) String() string {113	if v == nil {114		return "nilV"115	}116	return fmt.Sprintf("<%d>", v.j)117}118119type W struct {120	k int121}122123func (w *W) Error() string {124	if w == nil {125		return "nilW"126	}127	return fmt.Sprintf("[%d]", w.k)128}129130var siVal = I(S{"a", "b"})131132var tVal = &T{133	True:   true,134	I:      17,135	U16:    16,136	X:      "x",137	S:      "xyz",138	U:      &U{"v"},139	V0:     V{6666},140	V1:     &V{7777}, // leave V2 as nil141	W0:     W{888},142	W1:     &W{999}, // leave W2 as nil143	SI:     []int{3, 4, 5},144	SICap:  make([]int, 5, 10),145	AI:     [3]int{3, 4, 5},146	PAI:    &[3]int{3, 4, 5},147	SB:     []bool{true, false},148	MSI:    map[string]int{"one": 1, "two": 2, "three": 3},149	MSIone: map[string]int{"one": 1},150	MXI:    map[any]int{"one": 1},151	MII:    map[int]int{1: 1},152	MI32S:  map[int32]string{1: "one", 2: "two"},153	MI64S:  map[int64]string{2: "i642", 3: "i643"},154	MUI32S: map[uint32]string{2: "u322", 3: "u323"},155	MUI64S: map[uint64]string{2: "ui642", 3: "ui643"},156	MI8S:   map[int8]string{2: "i82", 3: "i83"},157	MUI8S:  map[uint8]string{2: "u82", 3: "u83"},158	SMSI: []map[string]int{159		{"one": 1, "two": 2},160		{"eleven": 11, "twelve": 12},161	},162	Empty1:                    3,163	Empty2:                    "empty2",164	Empty3:                    []int{7, 8},165	Empty4:                    &U{"UinEmpty"},166	NonEmptyInterface:         &T{X: "x"},167	NonEmptyInterfacePtS:      &siVal,168	NonEmptyInterfaceTypedNil: (*T)(nil),169	Str:                       bytes.NewBuffer([]byte("foozle")),170	Err:                       errors.New("erroozle"),171	PI:                        newInt(23),172	PS:                        newString("a string"),173	PSI:                       newIntSlice(21, 22, 23),174	UPI:                       newUnsafePointer(23),175	BinaryFunc:                func(a, b string) string { return fmt.Sprintf("[%s=%s]", a, b) },176	VariadicFunc:              func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },177	VariadicFuncInt:           func(a int, s ...string) string { return fmt.Sprint(a, "=<", strings.Join(s, "+"), ">") },178	NilOKFunc:                 func(s *int) bool { return s == nil },179	ErrFunc:                   func() (string, error) { return "bla", nil },180	PanicFunc:                 func() string { panic("test panic") },181	TooFewReturnCountFunc:     func() {},182	TooManyReturnCountFunc:    func() (string, error, int) { return "", nil, 0 },183	InvalidReturnTypeFunc:     func() (string, bool) { return "", false },184	Tmpl:                      Must(New("x").Parse("test template")), // "x" is the value of .X185}186187var tSliceOfNil = []*T{nil}188189// A non-empty interface.190type I interface {191	Method0() string192}193194var iVal I = tVal195196// Helpers for creation.197func newInt(n int) *int {198	return &n199}200201func newUnsafePointer(n int) unsafe.Pointer {202	return unsafe.Pointer(&n)203}204205func newString(s string) *string {206	return &s207}208209func newIntSlice(n ...int) *[]int {210	p := new([]int)211	*p = make([]int, len(n))212	copy(*p, n)213	return p214}215216// Simple methods with and without arguments.217func (t *T) Method0() string {218	return "M0"219}220221func (t *T) Method1(a int) int {222	return a223}224225func (t *T) Method2(a uint16, b string) string {226	return fmt.Sprintf("Method2: %d %s", a, b)227}228229func (t *T) Method3(v any) string {230	return fmt.Sprintf("Method3: %v", v)231}232233func (t *T) Copy() *T {234	n := new(T)235	*n = *t236	return n237}238239func (t *T) MAdd(a int, b []int) []int {240	v := make([]int, len(b))241	for i, x := range b {242		v[i] = x + a243	}244	return v245}246247var myError = errors.New("my error")248249// MyError returns a value and an error according to its argument.250func (t *T) MyError(error bool) (bool, error) {251	if error {252		return true, myError253	}254	return false, nil255}256257// A few methods to test chaining.258func (t *T) GetU() *U {259	return t.U260}261262func (u *U) TrueFalse(b bool) string {263	if b {264		return "true"265	}266	return ""267}268269func typeOf(arg any) string {270	return fmt.Sprintf("%T", arg)271}272273type execTest struct {274	name   string275	input  string276	output string277	data   any278	ok     bool279}280281// bigInt and bigUint are hex string representing numbers either side282// of the max int boundary.283// We do it this way so the test doesn't depend on ints being 32 bits.284var (285	bigInt  = fmt.Sprintf("0x%x", int(1<<uint(reflect.TypeFor[int]().Bits()-1)-1))286	bigUint = fmt.Sprintf("0x%x", uint(1<<uint(reflect.TypeFor[int]().Bits()-1)))287)288289var execTests = []execTest{290	// Trivial cases.291	{"empty", "", "", nil, true},292	{"text", "some text", "some text", nil, true},293	{"nil action", "{{nil}}", "", nil, false},294295	// Ideal constants.296	{"ideal int", "{{typeOf 3}}", "int", 0, true},297	{"ideal float", "{{typeOf 1.0}}", "float64", 0, true},298	{"ideal exp float", "{{typeOf 1e1}}", "float64", 0, true},299	{"ideal complex", "{{typeOf 1i}}", "complex128", 0, true},300	{"ideal int", "{{typeOf " + bigInt + "}}", "int", 0, true},301	{"ideal too big", "{{typeOf " + bigUint + "}}", "", 0, false},302	{"ideal nil without type", "{{nil}}", "", 0, false},303304	// Fields of structs.305	{".X", "-{{.X}}-", "-x-", tVal, true},306	{".U.V", "-{{.U.V}}-", "-v-", tVal, true},307	{".unexported", "{{.unexported}}", "", tVal, false},308309	// Fields on maps.310	{"map .one", "{{.MSI.one}}", "1", tVal, true},311	{"map .two", "{{.MSI.two}}", "2", tVal, true},312	{"map .NO", "{{.MSI.NO}}", "<no value>", tVal, true},313	{"map .one interface", "{{.MXI.one}}", "1", tVal, true},314	{"map .WRONG args", "{{.MSI.one 1}}", "", tVal, false},315	{"map .WRONG type", "{{.MII.one}}", "", tVal, false},316317	// Dots of all kinds to test basic evaluation.318	{"dot int", "<{{.}}>", "<13>", 13, true},319	{"dot uint", "<{{.}}>", "<14>", uint(14), true},320	{"dot float", "<{{.}}>", "<15.1>", 15.1, true},321	{"dot bool", "<{{.}}>", "<true>", true, true},322	{"dot complex", "<{{.}}>", "<(16.2-17i)>", 16.2 - 17i, true},323	{"dot string", "<{{.}}>", "<hello>", "hello", true},324	{"dot slice", "<{{.}}>", "<[-1 -2 -3]>", []int{-1, -2, -3}, true},325	{"dot map", "<{{.}}>", "<map[two:22]>", map[string]int{"two": 22}, true},326	{"dot struct", "<{{.}}>", "<{7 seven}>", struct {327		a int328		b string329	}{7, "seven"}, true},330331	// Variables.332	{"$ int", "{{$}}", "123", 123, true},333	{"$.I", "{{$.I}}", "17", tVal, true},334	{"$.U.V", "{{$.U.V}}", "v", tVal, true},335	{"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true},336	{"simple assignment", "{{$x := 2}}{{$x = 3}}{{$x}}", "3", tVal, true},337	{"nested assignment",338		"{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{$x}}",339		"3", tVal, true},340	{"nested assignment changes the last declaration",341		"{{$x := 1}}{{if true}}{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{end}}{{$x}}",342		"1", tVal, true},343344	// Type with String method.345	{"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true},346	{"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true},347	{"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true},348349	// Type with Error method.350	{"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true},351	{"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true},352	{"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true},353354	// Pointers.355	{"*int", "{{.PI}}", "23", tVal, true},356	{"*string", "{{.PS}}", "a string", tVal, true},357	{"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},358	{"*[]int[1]", "{{index .PSI 1}}", "22", tVal, true},359	{"NIL", "{{.NIL}}", "<nil>", tVal, true},360361	// Empty interfaces holding values.362	{"empty nil", "{{.Empty0}}", "<no value>", tVal, true},363	{"empty with int", "{{.Empty1}}", "3", tVal, true},364	{"empty with string", "{{.Empty2}}", "empty2", tVal, true},365	{"empty with slice", "{{.Empty3}}", "[7 8]", tVal, true},366	{"empty with struct", "{{.Empty4}}", "{UinEmpty}", tVal, true},367	{"empty with struct, field", "{{.Empty4.V}}", "UinEmpty", tVal, true},368369	// Edge cases with <no value> with an interface value370	{"field on interface", "{{.foo}}", "<no value>", nil, true},371	{"field on parenthesized interface", "{{(.).foo}}", "<no value>", nil, true},372373	// Issue 31810: Parenthesized first element of pipeline with arguments.374	// See also TestIssue31810.375	{"unparenthesized non-function", "{{1 2}}", "", nil, false},376	{"parenthesized non-function", "{{(1) 2}}", "", nil, false},377	{"parenthesized non-function with no args", "{{(1)}}", "1", nil, true}, // This is fine.378379	// Method calls.380	{".Method0", "-{{.Method0}}-", "-M0-", tVal, true},381	{".Method1(1234)", "-{{.Method1 1234}}-", "-1234-", tVal, true},382	{".Method1(.I)", "-{{.Method1 .I}}-", "-17-", tVal, true},383	{".Method2(3, .X)", "-{{.Method2 3 .X}}-", "-Method2: 3 x-", tVal, true},384	{".Method2(.U16, `str`)", "-{{.Method2 .U16 `str`}}-", "-Method2: 16 str-", tVal, true},385	{".Method2(.U16, $x)", "{{if $x := .X}}-{{.Method2 .U16 $x}}{{end}}-", "-Method2: 16 x-", tVal, true},386	{".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: <nil>-", tVal, true},387	{".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: <nil>-", tVal, true},388	{"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true},389	{"method on chained var",390		"{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",391		"true", tVal, true},392	{"chained method",393		"{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}",394		"true", tVal, true},395	{"chained method on variable",396		"{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",397		"true", tVal, true},398	{".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true},399	{".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true},400	{"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true},401	{"method on typed nil interface value", "{{.NonEmptyInterfaceTypedNil.Method0}}", "M0", tVal, true},402403	// Function call builtin.404	{".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},405	{".VariadicFunc0", "{{call .VariadicFunc}}", "<>", tVal, true},406	{".VariadicFunc2", "{{call .VariadicFunc `he` `llo`}}", "<he+llo>", tVal, true},407	{".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true},408	{"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true},409	{"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true},410	{"Interface Call", `{{stringer .S}}`, "foozle", map[string]any{"S": bytes.NewBufferString("foozle")}, true},411	{".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true},412	{"call nil", "{{call nil}}", "", tVal, false},413	{"empty call", "{{call}}", "", tVal, false},414	{"empty call after pipe valid", "{{.ErrFunc | call}}", "bla", tVal, true},415	{"empty call after pipe invalid", "{{1 | call}}", "", tVal, false},416417	// Erroneous function calls (check args).418	{".BinaryFuncTooFew", "{{call .BinaryFunc `1`}}", "", tVal, false},419	{".BinaryFuncTooMany", "{{call .BinaryFunc `1` `2` `3`}}", "", tVal, false},420	{".BinaryFuncBad0", "{{call .BinaryFunc 1 3}}", "", tVal, false},421	{".BinaryFuncBad1", "{{call .BinaryFunc `1` 3}}", "", tVal, false},422	{".VariadicFuncBad0", "{{call .VariadicFunc 3}}", "", tVal, false},423	{".VariadicFuncIntBad0", "{{call .VariadicFuncInt}}", "", tVal, false},424	{".VariadicFuncIntBad`", "{{call .VariadicFuncInt `x`}}", "", tVal, false},425	{".VariadicFuncNilBad", "{{call .VariadicFunc nil}}", "", tVal, false},426427	// Pipelines.428	{"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},429	{"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},430431	// Nil values aren't missing arguments.432	{"nil pipeline", "{{ .Empty0 | call .NilOKFunc }}", "true", tVal, true},433	{"nil call arg", "{{ call .NilOKFunc .Empty0 }}", "true", tVal, true},434	{"bad nil pipeline", "{{ .Empty0 | .VariadicFunc }}", "", tVal, false},435436	// Parenthesized expressions437	{"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true},438439	// Parenthesized expressions with field accesses440	{"parens: $ in paren", "{{($).X}}", "x", tVal, true},441	{"parens: $.GetU in paren", "{{($.GetU).V}}", "v", tVal, true},442	{"parens: $ in paren in pipe", "{{($ | echo).X}}", "x", tVal, true},443	{"parens: spaces and args", `{{(makemap "up" "down" "left" "right").left}}`, "right", tVal, true},444445	// If.446	{"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},447	{"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},448	{"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false},449	{"if on typed nil interface value", "{{if .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},450	{"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},451	{"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},452	{"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},453	{"if 0.0", "{{if .FloatZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},454	{"if 1.5i", "{{if 1.5i}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},455	{"if 0.0i", "{{if .ComplexZero}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},456	{"if nonNilPointer", "{{if .PI}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},457	{"if nilPointer", "{{if .NIL}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},458	{"if UPI", "{{if .UPI}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},459	{"if EmptyUPI", "{{if .EmptyUPI}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},460	{"if emptystring", "{{if ``}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},461	{"if string", "{{if `notempty`}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},462	{"if emptyslice", "{{if .SIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},463	{"if slice", "{{if .SI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},464	{"if emptymap", "{{if .MSIEmpty}}NON-EMPTY{{else}}EMPTY{{end}}", "EMPTY", tVal, true},465	{"if map", "{{if .MSI}}NON-EMPTY{{else}}EMPTY{{end}}", "NON-EMPTY", tVal, true},466	{"if map unset", "{{if .MXI.none}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},467	{"if map not unset", "{{if not .MXI.none}}ZERO{{else}}NON-ZERO{{end}}", "ZERO", tVal, true},468	{"if $x with $y int", "{{if $x := true}}{{with $y := .I}}{{$x}},{{$y}}{{end}}{{end}}", "true,17", tVal, true},469	{"if $x with $x int", "{{if $x := true}}{{with $x := .I}}{{$x}},{{end}}{{$x}}{{end}}", "17,true", tVal, true},470	{"if else if", "{{if false}}FALSE{{else if true}}TRUE{{end}}", "TRUE", tVal, true},471	{"if else chain", "{{if eq 1 3}}1{{else if eq 2 3}}2{{else if eq 3 3}}3{{end}}", "3", tVal, true},472473	// Print etc.474	{"print", `{{print "hello, print"}}`, "hello, print", tVal, true},475	{"print 123", `{{print 1 2 3}}`, "1 2 3", tVal, true},476	{"print nil", `{{print nil}}`, "<nil>", tVal, true},477	{"println", `{{println 1 2 3}}`, "1 2 3\n", tVal, true},478	{"printf int", `{{printf "%04x" 127}}`, "007f", tVal, true},479	{"printf float", `{{printf "%g" 3.5}}`, "3.5", tVal, true},480	{"printf complex", `{{printf "%g" 1+7i}}`, "(1+7i)", tVal, true},481	{"printf string", `{{printf "%s" "hello"}}`, "hello", tVal, true},482	{"printf function", `{{printf "%#q" zeroArgs}}`, "`zeroArgs`", tVal, true},483	{"printf field", `{{printf "%s" .U.V}}`, "v", tVal, true},484	{"printf method", `{{printf "%s" .Method0}}`, "M0", tVal, true},485	{"printf dot", `{{with .I}}{{printf "%d" .}}{{end}}`, "17", tVal, true},486	{"printf var", `{{with $x := .I}}{{printf "%d" $x}}{{end}}`, "17", tVal, true},487	{"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true},488489	// HTML.490	{"html", `{{html "<script>alert(\"XSS\");</script>"}}`,491		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},492	{"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`,493		"&lt;script&gt;alert(&#34;XSS&#34;);&lt;/script&gt;", nil, true},494	{"html", `{{html .PS}}`, "a string", tVal, true},495	{"html typed nil", `{{html .NIL}}`, "&lt;nil&gt;", tVal, true},496	{"html untyped nil", `{{html .Empty0}}`, "&lt;no value&gt;", tVal, true},497498	// JavaScript.499	{"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},500501	// URL query.502	{"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},503504	// Booleans505	{"not", "{{not true}} {{not false}}", "false true", nil, true},506	{"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},507	{"or", "{{or 0 0}} {{or 1 0}} {{or 0 true}} {{or 1 1}}", "0 1 true 1", nil, true},508	{"or short-circuit", "{{or 0 1 (die)}}", "1", nil, true},509	{"and short-circuit", "{{and 1 0 (die)}}", "0", nil, true},510	{"or short-circuit2", "{{or 0 0 (die)}}", "", nil, false},511	{"and short-circuit2", "{{and 1 1 (die)}}", "", nil, false},512	{"and pipe-true", "{{1 | and 1}}", "1", nil, true},513	{"and pipe-false", "{{0 | and 1}}", "0", nil, true},514	{"or pipe-true", "{{1 | or 0}}", "1", nil, true},515	{"or pipe-false", "{{0 | or 0}}", "0", nil, true},516	{"and undef", "{{and 1 .Unknown}}", "<no value>", nil, true},517	{"or undef", "{{or 0 .Unknown}}", "<no value>", nil, true},518	{"boolean if", "{{if and true 1 `hi`}}TRUE{{else}}FALSE{{end}}", "TRUE", tVal, true},519	{"boolean if not", "{{if and true 1 `hi` | not}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},520	{"boolean if pipe", "{{if true | not | and 1}}TRUE{{else}}FALSE{{end}}", "FALSE", nil, true},521522	// Indexing.523	{"slice[0]", "{{index .SI 0}}", "3", tVal, true},524	{"slice[1]", "{{index .SI 1}}", "4", tVal, true},525	{"slice[HUGE]", "{{index .SI 10}}", "", tVal, false},526	{"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},527	{"slice[nil]", "{{index .SI nil}}", "", tVal, false},528	{"map[one]", "{{index .MSI `one`}}", "1", tVal, true},529	{"map[two]", "{{index .MSI `two`}}", "2", tVal, true},530	{"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},531	{"map[nil]", "{{index .MSI nil}}", "", tVal, false},532	{"map[``]", "{{index .MSI ``}}", "0", tVal, true},533	{"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},534	{"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},535	{"nil[1]", "{{index nil 1}}", "", tVal, false},536	{"map MI64S", "{{index .MI64S 2}}", "i642", tVal, true},537	{"map MI32S", "{{index .MI32S 2}}", "two", tVal, true},538	{"map MUI64S", "{{index .MUI64S 3}}", "ui643", tVal, true},539	{"map MI8S", "{{index .MI8S 3}}", "i83", tVal, true},540	{"map MUI8S", "{{index .MUI8S 2}}", "u82", tVal, true},541	{"index of an interface field", "{{index .Empty3 0}}", "7", tVal, true},542543	// Slicing.544	{"slice[:]", "{{slice .SI}}", "[3 4 5]", tVal, true},545	{"slice[1:]", "{{slice .SI 1}}", "[4 5]", tVal, true},546	{"slice[1:2]", "{{slice .SI 1 2}}", "[4]", tVal, true},547	{"slice[-1:]", "{{slice .SI -1}}", "", tVal, false},548	{"slice[1:-2]", "{{slice .SI 1 -2}}", "", tVal, false},549	{"slice[1:2:-1]", "{{slice .SI 1 2 -1}}", "", tVal, false},550	{"slice[2:1]", "{{slice .SI 2 1}}", "", tVal, false},551	{"slice[2:2:1]", "{{slice .SI 2 2 1}}", "", tVal, false},552	{"out of range", "{{slice .SI 4 5}}", "", tVal, false},553	{"out of range", "{{slice .SI 2 2 5}}", "", tVal, false},554	{"len(s) < indexes < cap(s)", "{{slice .SICap 6 10}}", "[0 0 0 0]", tVal, true},555	{"len(s) < indexes < cap(s)", "{{slice .SICap 6 10 10}}", "[0 0 0 0]", tVal, true},556	{"indexes > cap(s)", "{{slice .SICap 10 11}}", "", tVal, false},557	{"indexes > cap(s)", "{{slice .SICap 6 10 11}}", "", tVal, false},558	{"array[:]", "{{slice .AI}}", "[3 4 5]", tVal, true},559	{"array[1:]", "{{slice .AI 1}}", "[4 5]", tVal, true},560	{"array[1:2]", "{{slice .AI 1 2}}", "[4]", tVal, true},561	{"pointer to array[:]", "{{slice .PAI}}", "[3 4 5]", tVal, true},562	{"pointer to array[1:]", "{{slice .PAI 1}}", "[4 5]", tVal, true},563	{"pointer to array[1:2]", "{{slice .PAI 1 2}}", "[4]", tVal, true},564	{"string[:]", "{{slice .S}}", "xyz", tVal, true},565	{"string[0:1]", "{{slice .S 0 1}}", "x", tVal, true},566	{"string[1:]", "{{slice .S 1}}", "yz", tVal, true},567	{"string[1:2]", "{{slice .S 1 2}}", "y", tVal, true},568	{"out of range", "{{slice .S 1 5}}", "", tVal, false},569	{"3-index slice of string", "{{slice .S 1 2 2}}", "", tVal, false},570	{"slice of an interface field", "{{slice .Empty3 0 1}}", "[7]", tVal, true},571572	// Len.573	{"slice", "{{len .SI}}", "3", tVal, true},574	{"map", "{{len .MSI }}", "3", tVal, true},575	{"len of int", "{{len 3}}", "", tVal, false},576	{"len of nothing", "{{len .Empty0}}", "", tVal, false},577	{"len of an interface field", "{{len .Empty3}}", "2", tVal, true},578579	// With.580	{"with true", "{{with true}}{{.}}{{end}}", "true", tVal, true},581	{"with false", "{{with false}}{{.}}{{else}}FALSE{{end}}", "FALSE", tVal, true},582	{"with 1", "{{with 1}}{{.}}{{else}}ZERO{{end}}", "1", tVal, true},583	{"with 0", "{{with 0}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},584	{"with 1.5", "{{with 1.5}}{{.}}{{else}}ZERO{{end}}", "1.5", tVal, true},585	{"with 0.0", "{{with .FloatZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},586	{"with 1.5i", "{{with 1.5i}}{{.}}{{else}}ZERO{{end}}", "(0+1.5i)", tVal, true},587	{"with 0.0i", "{{with .ComplexZero}}{{.}}{{else}}ZERO{{end}}", "ZERO", tVal, true},588	{"with emptystring", "{{with ``}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},589	{"with string", "{{with `notempty`}}{{.}}{{else}}EMPTY{{end}}", "notempty", tVal, true},590	{"with emptyslice", "{{with .SIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},591	{"with slice", "{{with .SI}}{{.}}{{else}}EMPTY{{end}}", "[3 4 5]", tVal, true},592	{"with emptymap", "{{with .MSIEmpty}}{{.}}{{else}}EMPTY{{end}}", "EMPTY", tVal, true},593	{"with map", "{{with .MSIone}}{{.}}{{else}}EMPTY{{end}}", "map[one:1]", tVal, true},594	{"with empty interface, struct field", "{{with .Empty4}}{{.V}}{{end}}", "UinEmpty", tVal, true},595	{"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},596	{"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},597	{"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},598	{"with on typed nil interface value", "{{with .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},599	{"with else with", "{{with 0}}{{.}}{{else with true}}{{.}}{{end}}", "true", tVal, true},600	{"with else with chain", "{{with 0}}{{.}}{{else with false}}{{.}}{{else with `notempty`}}{{.}}{{end}}", "notempty", tVal, true},601602	// Range.603	{"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},604	{"range empty no else", "{{range .SIEmpty}}-{{.}}-{{end}}", "", tVal, true},605	{"range []int else", "{{range .SI}}-{{.}}-{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},606	{"range empty else", "{{range .SIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},607	{"range []int break else", "{{range .SI}}-{{.}}-{{break}}NOTREACHED{{else}}EMPTY{{end}}", "-3-", tVal, true},608	{"range []int continue else", "{{range .SI}}-{{.}}-{{continue}}NOTREACHED{{else}}EMPTY{{end}}", "-3--4--5-", tVal, true},609	{"range []bool", "{{range .SB}}-{{.}}-{{end}}", "-true--false-", tVal, true},610	{"range []int method", "{{range .SI | .MAdd .I}}-{{.}}-{{end}}", "-20--21--22-", tVal, true},611	{"range map", "{{range .MSI}}-{{.}}-{{end}}", "-1--3--2-", tVal, true},612	{"range empty map no else", "{{range .MSIEmpty}}-{{.}}-{{end}}", "", tVal, true},613	{"range map else", "{{range .MSI}}-{{.}}-{{else}}EMPTY{{end}}", "-1--3--2-", tVal, true},614	{"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},615	{"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},616	{"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},617	{"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},618	{"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},619	{"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},620	{"range $x $y MSIone", "{{range $x, $y := .MSIone}}<{{$x}}={{$y}}>{{end}}", "<one=1>", tVal, true},621	{"range $x PSI", "{{range $x := .PSI}}<{{$x}}>{{end}}", "<21><22><23>", tVal, true},622	{"declare in range", "{{range $x := .PSI}}<{{$foo:=$x}}{{$x}}>{{end}}", "<21><22><23>", tVal, true},623	{"range count", `{{range $i, $x := count 5}}[{{$i}}]{{$x}}{{end}}`, "[0]a[1]b[2]c[3]d[4]e", tVal, true},624	{"range nil count", `{{range $i, $x := count 0}}{{else}}empty{{end}}`, "empty", tVal, true},625	{"range iter.Seq[int]", `{{range $i := .}}{{$i}}{{end}}`, "01", fVal1(2), true},626	{"i = range iter.Seq[int]", `{{$i := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal1(2), true},627	{"range iter.Seq[int] over two var", `{{range $i, $c := .}}{{$c}}{{end}}`, "", fVal1(2), false},628	{"i, c := range iter.Seq2[int,int]", `{{range $i, $c := .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},629	{"i, c = range iter.Seq2[int,int]", `{{$i := 0}}{{$c := 0}}{{range $i, $c = .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},630	{"i = range iter.Seq2[int,int]", `{{$i := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal2(2), true},631	{"i := range iter.Seq2[int,int]", `{{range $i := .}}{{$i}}{{end}}`, "01", fVal2(2), true},632	{"i,c,x range iter.Seq2[int,int]", `{{$i := 0}}{{$c := 0}}{{$x := 0}}{{range $i, $c = .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},633	{"i,x range iter.Seq[int]", `{{$i := 0}}{{$x := 0}}{{range $i = .}}{{$i}}{{end}}`, "01", fVal1(2), true},634	{"range iter.Seq[int] else", `{{range $i := .}}{{$i}}{{else}}empty{{end}}`, "empty", fVal1(0), true},635	{"range iter.Seq2[int,int] else", `{{range $i := .}}{{$i}}{{else}}empty{{end}}`, "empty", fVal2(0), true},636	{"range int8", rangeTestInt, rangeTestData[int8](), int8(5), true},637	{"range int16", rangeTestInt, rangeTestData[int16](), int16(5), true},638	{"range int32", rangeTestInt, rangeTestData[int32](), int32(5), true},639	{"range int64", rangeTestInt, rangeTestData[int64](), int64(5), true},640	{"range int", rangeTestInt, rangeTestData[int](), int(5), true},641	{"range uint8", rangeTestInt, rangeTestData[uint8](), uint8(5), true},642	{"range uint16", rangeTestInt, rangeTestData[uint16](), uint16(5), true},643	{"range uint32", rangeTestInt, rangeTestData[uint32](), uint32(5), true},644	{"range uint64", rangeTestInt, rangeTestData[uint64](), uint64(5), true},645	{"range uint", rangeTestInt, rangeTestData[uint](), uint(5), true},646	{"range uintptr", rangeTestInt, rangeTestData[uintptr](), uintptr(5), true},647	{"range uintptr(0)", `{{range $v := .}}{{print $v}}{{else}}empty{{end}}`, "empty", uintptr(0), true},648	{"range 5", `{{range $v := 5}}{{printf "%T%d" $v $v}}{{end}}`, rangeTestData[int](), nil, true},649650	// Cute examples.651	{"or as if true", `{{or .SI "slice is empty"}}`, "[3 4 5]", tVal, true},652	{"or as if false", `{{or .SIEmpty "slice is empty"}}`, "slice is empty", tVal, true},653654	// Error handling.655	{"error method, error", "{{.MyError true}}", "", tVal, false},656	{"error method, no error", "{{.MyError false}}", "false", tVal, true},657658	// Numbers659	{"decimal", "{{print 1234}}", "1234", tVal, true},660	{"decimal _", "{{print 12_34}}", "1234", tVal, true},661	{"binary", "{{print 0b101}}", "5", tVal, true},662	{"binary _", "{{print 0b_1_0_1}}", "5", tVal, true},663	{"BINARY", "{{print 0B101}}", "5", tVal, true},664	{"octal0", "{{print 0377}}", "255", tVal, true},665	{"octal", "{{print 0o377}}", "255", tVal, true},666	{"octal _", "{{print 0o_3_7_7}}", "255", tVal, true},667	{"OCTAL", "{{print 0O377}}", "255", tVal, true},668	{"hex", "{{print 0x123}}", "291", tVal, true},669	{"hex _", "{{print 0x1_23}}", "291", tVal, true},670	{"HEX", "{{print 0X123ABC}}", "1194684", tVal, true},671	{"float", "{{print 123.4}}", "123.4", tVal, true},672	{"float _", "{{print 0_0_1_2_3.4}}", "123.4", tVal, true},673	{"hex float", "{{print +0x1.ep+2}}", "7.5", tVal, true},674	{"hex float _", "{{print +0x_1.e_0p+0_2}}", "7.5", tVal, true},675	{"HEX float", "{{print +0X1.EP+2}}", "7.5", tVal, true},676	{"print multi", "{{print 1_2_3_4 7.5_00_00_00}}", "1234 7.5", tVal, true},677	{"print multi2", "{{print 1234 0x0_1.e_0p+02}}", "1234 7.5", tVal, true},678679	// Fixed bugs.680	// Must separate dot and receiver; otherwise args are evaluated with dot set to variable.681	{"bug0", "{{range .MSIone}}{{if $.Method1 .}}X{{end}}{{end}}", "X", tVal, true},682	// Do not loop endlessly in indirect for non-empty interfaces.683	// The bug appears with *interface only; looped forever.684	{"bug1", "{{.Method0}}", "M0", &iVal, true},685	// Was taking address of interface field, so method set was empty.686	{"bug2", "{{$.NonEmptyInterface.Method0}}", "M0", tVal, true},687	// Struct values were not legal in with - mere oversight.688	{"bug3", "{{with $}}{{.Method0}}{{end}}", "M0", tVal, true},689	// Nil interface values in if.690	{"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},691	// Stringer.692	{"bug5", "{{.Str}}", "foozle", tVal, true},693	{"bug5a", "{{.Err}}", "erroozle", tVal, true},694	// Args need to be indirected and dereferenced sometimes.695	{"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},696	{"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},697	{"bug6c", "{{vfunc .V1 .V0}}", "vfunc", tVal, true},698	{"bug6d", "{{vfunc .V1 .V1}}", "vfunc", tVal, true},699	// Legal parse but illegal execution: non-function should have no arguments.700	{"bug7a", "{{3 2}}", "", tVal, false},701	{"bug7b", "{{$x := 1}}{{$x 2}}", "", tVal, false},702	{"bug7c", "{{$x := 1}}{{3 | $x}}", "", tVal, false},703	// Pipelined arg was not being type-checked.704	{"bug8a", "{{3|oneArg}}", "", tVal, false},705	{"bug8b", "{{4|dddArg 3}}", "", tVal, false},706	// A bug was introduced that broke map lookups for lower-case names.707	{"bug9", "{{.cause}}", "neglect", map[string]string{"cause": "neglect"}, true},708	// Field chain starting with function did not work.709	{"bug10", "{{mapOfThree.three}}-{{(mapOfThree).three}}", "3-3", 0, true},710	// Dereferencing nil pointer while evaluating function arguments should not panic. Issue 7333.711	{"bug11", "{{valueString .PS}}", "", T{}, false},712	// 0xef gave constant type float64. Issue 8622.713	{"bug12xe", "{{printf `%T` 0xef}}", "int", T{}, true},714	{"bug12xE", "{{printf `%T` 0xEE}}", "int", T{}, true},715	{"bug12Xe", "{{printf `%T` 0Xef}}", "int", T{}, true},716	{"bug12XE", "{{printf `%T` 0XEE}}", "int", T{}, true},717	// Chained nodes did not work as arguments. Issue 8473.718	{"bug13", "{{print (.Copy).I}}", "17", tVal, true},719	// Didn't protect against nil or literal values in field chains.720	{"bug14a", "{{(nil).True}}", "", tVal, false},721	{"bug14b", "{{$x := nil}}{{$x.anything}}", "", tVal, false},722	{"bug14c", `{{$x := (1.0)}}{{$y := ("hello")}}{{$x.anything}}{{$y.true}}`, "", tVal, false},723	// Didn't call validateType on function results. Issue 10800.724	{"bug15", "{{valueString returnInt}}", "", tVal, false},725	// Variadic function corner cases. Issue 10946.726	{"bug16a", "{{true|printf}}", "", tVal, false},727	{"bug16b", "{{1|printf}}", "", tVal, false},728	{"bug16c", "{{1.1|printf}}", "", tVal, false},729	{"bug16d", "{{'x'|printf}}", "", tVal, false},730	{"bug16e", "{{0i|printf}}", "", tVal, false},731	{"bug16f", "{{true|twoArgs \"xxx\"}}", "", tVal, false},732	{"bug16g", "{{\"aaa\" |twoArgs \"bbb\"}}", "twoArgs=bbbaaa", tVal, true},733	{"bug16h", "{{1|oneArg}}", "", tVal, false},734	{"bug16i", "{{\"aaa\"|oneArg}}", "oneArg=aaa", tVal, true},735	{"bug16j", "{{1+2i|printf \"%v\"}}", "(1+2i)", tVal, true},736	{"bug16k", "{{\"aaa\"|printf }}", "aaa", tVal, true},737	{"bug17a", "{{.NonEmptyInterface.X}}", "x", tVal, true},738	{"bug17b", "-{{.NonEmptyInterface.Method1 1234}}-", "-1234-", tVal, true},739	{"bug17c", "{{len .NonEmptyInterfacePtS}}", "2", tVal, true},740	{"bug17d", "{{index .NonEmptyInterfacePtS 0}}", "a", tVal, true},741	{"bug17e", "{{range .NonEmptyInterfacePtS}}-{{.}}-{{end}}", "-a--b-", tVal, true},742743	// More variadic function corner cases. Some runes would get evaluated744	// as constant floats instead of ints. Issue 34483.745	{"bug18a", "{{eq . '.'}}", "true", '.', true},746	{"bug18b", "{{eq . 'e'}}", "true", 'e', true},747	{"bug18c", "{{eq . 'P'}}", "true", 'P', true},748749	{"issue56490", "{{$i := 0}}{{$x := 0}}{{range $i = .AI}}{{end}}{{$i}}", "5", tVal, true},750	{"issue60801", "{{$k := 0}}{{$v := 0}}{{range $k, $v = .AI}}{{$k}}={{$v}} {{end}}", "0=3 1=4 2=5 ", tVal, true},751}752753func fVal1(i int) iter.Seq[int] {754	return func(yield func(int) bool) {755		for v := range i {756			if !yield(v) {757				break758			}759		}760	}761}762763func fVal2(i int) iter.Seq2[int, int] {764	return func(yield func(int, int) bool) {765		for v := range i {766			if !yield(v, v+1) {767				break768			}769		}770	}771}772773const rangeTestInt = `{{range $v := .}}{{printf "%T%d" $v $v}}{{end}}`774775func rangeTestData[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr]() string {776	I := T(5)777	var buf strings.Builder778	for i := T(0); i < I; i++ {779		fmt.Fprintf(&buf, "%T%d", i, i)780	}781	return buf.String()782}783784func zeroArgs() string {785	return "zeroArgs"786}787788func oneArg(a string) string {789	return "oneArg=" + a790}791792func twoArgs(a, b string) string {793	return "twoArgs=" + a + b794}795796func dddArg(a int, b ...string) string {797	return fmt.Sprintln(a, b)798}799800// count returns a channel that will deliver n sequential 1-letter strings starting at "a"801func count(n int) chan string {802	if n == 0 {803		return nil804	}805	c := make(chan string)806	go func() {807		for i := 0; i < n; i++ {808			c <- "abcdefghijklmnop"[i : i+1]809		}810		close(c)811	}()812	return c813}814815// vfunc takes a *V and a V816func vfunc(V, *V) string {817	return "vfunc"818}819820// valueString takes a string, not a pointer.821func valueString(v string) string {822	return "value is ignored"823}824825// returnInt returns an int826func returnInt() int {827	return 7828}829830func add(args ...int) int {831	sum := 0832	for _, x := range args {833		sum += x834	}835	return sum836}837838func echo(arg any) any {839	return arg840}841842func makemap(arg ...string) map[string]string {843	if len(arg)%2 != 0 {844		panic("bad makemap")845	}846	m := make(map[string]string)847	for i := 0; i < len(arg); i += 2 {848		m[arg[i]] = arg[i+1]849	}850	return m851}852853func stringer(s fmt.Stringer) string {854	return s.String()855}856857func mapOfThree() any {858	return map[string]int{"three": 3}859}860861func testExecute(execTests []execTest, template *Template, t *testing.T) {862	b := new(strings.Builder)863	funcs := FuncMap{864		"add":         add,865		"count":       count,866		"dddArg":      dddArg,867		"die":         func() bool { panic("die") },868		"echo":        echo,869		"makemap":     makemap,870		"mapOfThree":  mapOfThree,871		"oneArg":      oneArg,872		"returnInt":   returnInt,873		"stringer":    stringer,874		"twoArgs":     twoArgs,875		"typeOf":      typeOf,876		"valueString": valueString,877		"vfunc":       vfunc,878		"zeroArgs":    zeroArgs,879	}880	for _, test := range execTests {881		var tmpl *Template882		var err error883		if template == nil {884			tmpl, err = New(test.name).Funcs(funcs).Parse(test.input)885		} else {886			tmpl, err = template.New(test.name).Funcs(funcs).Parse(test.input)887		}888		if err != nil {889			t.Errorf("%s: parse error: %s", test.name, err)890			continue891		}892		b.Reset()893		err = tmpl.Execute(b, test.data)894		switch {895		case !test.ok && err == nil:896			t.Errorf("%s: expected error; got none", test.name)897			continue898		case test.ok && err != nil:899			t.Errorf("%s: unexpected execute error: %s", test.name, err)900			continue901		case !test.ok && err != nil:902			// expected error, got one903			if *debug {904				fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)905			}906		}907		result := b.String()908		if result != test.output {909			t.Errorf("%s: expected\n\t%q\ngot\n\t%q", test.name, test.output, result)910		}911	}912}913914func TestExecute(t *testing.T) {915	testExecute(execTests, nil, t)916}917918var delimPairs = []string{919	"", "", // default920	"{{", "}}", // same as default921	"<<", ">>", // distinct922	"|", "|", // same923	"(日)", "(本)", // peculiar924}925926func TestDelims(t *testing.T) {927	const hello = "Hello, world"928	var value = struct{ Str string }{hello}929	for i := 0; i < len(delimPairs); i += 2 {930		left := delimPairs[i+0]931		trueLeft := left932		right := delimPairs[i+1]933		trueRight := right934		if left == "" { // default case935			trueLeft = "{{"936		}937		if right == "" { // default case938			trueRight = "}}"939		}940		action := trueLeft + ".Str" + trueRight941		// A comment, which is not preserved in the parse tree.942		comment := trueLeft + "/*comment*/" + trueRight943		// An action containing a string that looks like the left delimiter.944		strAction := trueLeft + `"` + trueLeft + `"` + trueRight945		text := action + comment + strAction946		// At this point text looks like `{{.Str}}{{/*comment*/}}{{"{{"}}`.947		tmpl, err := New("delims").Delims(left, right).Parse(text)948		if err != nil {949			t.Fatalf("delim %q text %q parse err %s", left, text, err)950		}951		// The parse tree's String form should roundtrip back to the input,952		// using the custom delimiters, modulo the dropped comment.953		if got, want := tmpl.Root.String(), action+strAction; got != want {954			t.Errorf("delim %q: String() = %q, want %q", left, got, want)955		}956		var b = new(strings.Builder)957		err = tmpl.Execute(b, value)958		if err != nil {959			t.Fatalf("delim %q exec err %s", left, err)960		}961		if b.String() != hello+trueLeft {962			t.Errorf("expected %q got %q", hello+trueLeft, b.String())963		}964	}965}966967// Check that an error from a method flows back to the top.968func TestExecuteError(t *testing.T) {969	b := new(bytes.Buffer)970	tmpl := New("error")971	_, err := tmpl.Parse("{{.MyError true}}")972	if err != nil {973		t.Fatalf("parse error: %s", err)974	}975	err = tmpl.Execute(b, tVal)976	if err == nil {977		t.Errorf("expected error; got none")978	} else if !strings.Contains(err.Error(), myError.Error()) {979		if *debug {980			fmt.Printf("test execute error: %s\n", err)981		}982		t.Errorf("expected myError; got %s", err)983	}984}985986const execErrorText = `line 1987line 2988line 3989{{template "one" .}}990{{define "one"}}{{template "two" .}}{{end}}991{{define "two"}}{{template "three" .}}{{end}}992{{define "three"}}{{index "hi" $}}{{end}}`993994// Check that an error from a nested template contains all the relevant information.995func TestExecError(t *testing.T) {996	tmpl, err := New("top").Parse(execErrorText)997	if err != nil {998		t.Fatal("parse error:", err)999	}1000	var b bytes.Buffer1001	err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi"1002	if err == nil {1003		t.Fatal("expected error")1004	}1005	const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5`1006	got := err.Error()1007	if got != want {1008		t.Errorf("expected\n%q\ngot\n%q", want, got)1009	}1010}10111012type CustomError struct{}10131014func (*CustomError) Error() string { return "heyo !" }10151016// Check that a custom error can be returned.1017func TestExecError_CustomError(t *testing.T) {1018	failingFunc := func() (string, error) {1019		return "", &CustomError{}1020	}1021	tmpl := Must(New("top").Funcs(FuncMap{1022		"err": failingFunc,1023	}).Parse("{{ err }}"))10241025	var b bytes.Buffer1026	err := tmpl.Execute(&b, nil)10271028	if _, ok := errors.AsType[*CustomError](err); !ok {1029		t.Fatalf("expected custom error; got %s", err)1030	}1031}10321033func TestJSEscaping(t *testing.T) {1034	testCases := []struct {1035		in, exp string1036	}{1037		{`a`, `a`},1038		{`'foo`, `\'foo`},1039		{`Go "jump" \`, `Go \"jump\" \\`},1040		{`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`},1041		{"unprintable \uFFFE", `unprintable \uFFFE`},1042		{`<html>`, `\u003Chtml\u003E`},1043		{`no = in attributes`, `no \u003D in attributes`},1044		{`&#x27; does not become HTML entity`, `\u0026#x27; does not become HTML entity`},1045	}1046	for _, tc := range testCases {1047		s := JSEscapeString(tc.in)1048		if s != tc.exp {1049			t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp)1050		}1051	}1052}10531054// A nice example: walk a binary tree.10551056type Tree struct {1057	Val         int1058	Left, Right *Tree1059}10601061// Use different delimiters to test Set.Delims.1062// Also test the trimming of leading and trailing spaces.1063const treeTemplate = `1064	(- define "tree" -)1065	[1066		(- .Val -)1067		(- with .Left -)1068			(template "tree" . -)1069		(- end -)1070		(- with .Right -)1071			(- template "tree" . -)1072		(- end -)1073	]1074	(- end -)1075`10761077func TestTree(t *testing.T) {1078	var tree = &Tree{1079		1,1080		&Tree{1081			2, &Tree{1082				3,1083				&Tree{1084					4, nil, nil,1085				},1086				nil,1087			},1088			&Tree{1089				5,1090				&Tree{1091					6, nil, nil,1092				},1093				nil,1094			},1095		},1096		&Tree{1097			7,1098			&Tree{1099				8,1100				&Tree{1101					9, nil, nil,1102				},1103				nil,1104			},1105			&Tree{1106				10,1107				&Tree{1108					11, nil, nil,1109				},1110				nil,1111			},1112		},1113	}1114	tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate)1115	if err != nil {1116		t.Fatal("parse error:", err)1117	}1118	var b strings.Builder1119	const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]"1120	// First by looking up the template.1121	err = tmpl.Lookup("tree").Execute(&b, tree)1122	if err != nil {1123		t.Fatal("exec error:", err)1124	}1125	result := b.String()1126	if result != expect {1127		t.Errorf("expected %q got %q", expect, result)1128	}1129	// Then direct to execution.1130	b.Reset()1131	err = tmpl.ExecuteTemplate(&b, "tree", tree)1132	if err != nil {1133		t.Fatal("exec error:", err)1134	}1135	result = b.String()1136	if result != expect {1137		t.Errorf("expected %q got %q", expect, result)1138	}1139}11401141func TestExecuteOnNewTemplate(t *testing.T) {1142	// This is issue 3872.1143	New("Name").Templates()1144	// This is issue 11379.1145	new(Template).Templates()1146	new(Template).Parse("")1147	new(Template).New("abc").Parse("")1148	new(Template).Execute(nil, nil)                // returns an error (but does not crash)1149	new(Template).ExecuteTemplate(nil, "XXX", nil) // returns an error (but does not crash)1150}11511152const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}`11531154func TestMessageForExecuteEmpty(t *testing.T) {1155	// Test a truly empty template.1156	tmpl := New("empty")1157	var b bytes.Buffer1158	err := tmpl.Execute(&b, 0)1159	if err == nil {1160		t.Fatal("expected initial error")1161	}1162	got := err.Error()1163	want := `template: empty: "empty" is an incomplete or empty template`1164	if got != want {1165		t.Errorf("expected error %s got %s", want, got)1166	}1167	// Add a non-empty template to check that the error is helpful.1168	tests, err := New("").Parse(testTemplates)1169	if err != nil {1170		t.Fatal(err)1171	}1172	tmpl.AddParseTree("secondary", tests.Tree)1173	err = tmpl.Execute(&b, 0)1174	if err == nil {1175		t.Fatal("expected second error")1176	}1177	got = err.Error()1178	want = `template: empty: "empty" is an incomplete or empty template`1179	if got != want {1180		t.Errorf("expected error %s got %s", want, got)1181	}1182	// Make sure we can execute the secondary.1183	err = tmpl.ExecuteTemplate(&b, "secondary", 0)1184	if err != nil {1185		t.Fatal(err)1186	}1187}11881189func TestFinalForPrintf(t *testing.T) {1190	tmpl, err := New("").Parse(`{{"x" | printf}}`)1191	if err != nil {1192		t.Fatal(err)1193	}1194	var b bytes.Buffer1195	err = tmpl.Execute(&b, 0)1196	if err != nil {1197		t.Fatal(err)1198	}1199}12001201type cmpTest struct {1202	expr  string1203	truth string1204	ok    bool1205}12061207var cmpTests = []cmpTest{1208	{"eq true true", "true", true},1209	{"eq true false", "false", true},1210	{"eq 1+2i 1+2i", "true", true},1211	{"eq 1+2i 1+3i", "false", true},1212	{"eq 1.5 1.5", "true", true},1213	{"eq 1.5 2.5", "false", true},1214	{"eq 1 1", "true", true},1215	{"eq 1 2", "false", true},1216	{"eq `xy` `xy`", "true", true},1217	{"eq `xy` `xyz`", "false", true},1218	{"eq .Uthree .Uthree", "true", true},1219	{"eq .Uthree .Ufour", "false", true},1220	{"eq 3 4 5 6 3", "true", true},1221	{"eq 3 4 5 6 7", "false", true},1222	{"ne true true", "false", true},1223	{"ne true false", "true", true},1224	{"ne 1+2i 1+2i", "false", true},1225	{"ne 1+2i 1+3i", "true", true},1226	{"ne 1.5 1.5", "false", true},1227	{"ne 1.5 2.5", "true", true},1228	{"ne 1 1", "false", true},1229	{"ne 1 2", "true", true},1230	{"ne `xy` `xy`", "false", true},1231	{"ne `xy` `xyz`", "true", true},1232	{"ne .Uthree .Uthree", "false", true},1233	{"ne .Uthree .Ufour", "true", true},1234	{"lt 1.5 1.5", "false", true},1235	{"lt 1.5 2.5", "true", true},1236	{"lt 1 1", "false", true},1237	{"lt 1 2", "true", true},1238	{"lt `xy` `xy`", "false", true},1239	{"lt `xy` `xyz`", "true", true},1240	{"lt .Uthree .Uthree", "false", true},1241	{"lt .Uthree .Ufour", "true", true},1242	{"le 1.5 1.5", "true", true},1243	{"le 1.5 2.5", "true", true},1244	{"le 2.5 1.5", "false", true},1245	{"le 1 1", "true", true},1246	{"le 1 2", "true", true},1247	{"le 2 1", "false", true},1248	{"le `xy` `xy`", "true", true},1249	{"le `xy` `xyz`", "true", true},1250	{"le `xyz` `xy`", "false", true},1251	{"le .Uthree .Uthree", "true", true},1252	{"le .Uthree .Ufour", "true", true},1253	{"le .Ufour .Uthree", "false", true},1254	{"gt 1.5 1.5", "false", true},1255	{"gt 1.5 2.5", "false", true},1256	{"gt 1 1", "false", true},1257	{"gt 2 1", "true", true},1258	{"gt 1 2", "false", true},1259	{"gt `xy` `xy`", "false", true},1260	{"gt `xy` `xyz`", "false", true},1261	{"gt .Uthree .Uthree", "false", true},1262	{"gt .Uthree .Ufour", "false", true},1263	{"gt .Ufour .Uthree", "true", true},1264	{"ge 1.5 1.5", "true", true},1265	{"ge 1.5 2.5", "false", true},1266	{"ge 2.5 1.5", "true", true},1267	{"ge 1 1", "true", true},1268	{"ge 1 2", "false", true},1269	{"ge 2 1", "true", true},1270	{"ge `xy` `xy`", "true", true},1271	{"ge `xy` `xyz`", "false", true},1272	{"ge `xyz` `xy`", "true", true},1273	{"ge .Uthree .Uthree", "true", true},1274	{"ge .Uthree .Ufour", "false", true},1275	{"ge .Ufour .Uthree", "true", true},1276	// Mixing signed and unsigned integers.1277	{"eq .Uthree .Three", "true", true},1278	{"eq .Three .Uthree", "true", true},1279	{"le .Uthree .Three", "true", true},1280	{"le .Three .Uthree", "true", true},1281	{"ge .Uthree .Three", "true", true},1282	{"ge .Three .Uthree", "true", true},1283	{"lt .Uthree .Three", "false", true},1284	{"lt .Three .Uthree", "false", true},1285	{"gt .Uthree .Three", "false", true},1286	{"gt .Three .Uthree", "false", true},1287	{"eq .Ufour .Three", "false", true},1288	{"lt .Ufour .Three", "false", true},1289	{"gt .Ufour .Three", "true", true},1290	{"eq .NegOne .Uthree", "false", true},1291	{"eq .Uthree .NegOne", "false", true},1292	{"ne .NegOne .Uthree", "true", true},1293	{"ne .Uthree .NegOne", "true", true},1294	{"lt .NegOne .Uthree", "true", true},1295	{"lt .Uthree .NegOne", "false", true},1296	{"le .NegOne .Uthree", "true", true},1297	{"le .Uthree .NegOne", "false", true},1298	{"gt .NegOne .Uthree", "false", true},1299	{"gt .Uthree .NegOne", "true", true},1300	{"ge .NegOne .Uthree", "false", true},1301	{"ge .Uthree .NegOne", "true", true},1302	{"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule.1303	{"eq (index `x` 0) 'y'", "false", true},1304	{"eq .V1 .V2", "true", true},1305	{"eq .Ptr .Ptr", "true", true},1306	{"eq .Ptr .NilPtr", "false", true},1307	{"eq .NilPtr .NilPtr", "true", true},1308	{"eq .Iface1 .Iface1", "true", true},1309	{"eq .Iface1 .NilIface", "false", true},1310	{"eq .NilIface .NilIface", "true", true},1311	{"eq .NilIface .Iface1", "false", true},1312	{"eq .NilIface 0", "false", true},1313	{"eq 0 .NilIface", "false", true},1314	{"eq .Map .Map", "true", true},        // Uncomparable types but nil is OK.1315	{"eq .Map nil", "true", true},         // Uncomparable types but nil is OK.1316	{"eq nil .Map", "true", true},         // Uncomparable types but nil is OK.1317	{"eq .Map .NonNilMap", "false", true}, // Uncomparable types but nil is OK.1318	// Errors1319	{"eq `xy` 1", "", false},                // Different types.1320	{"eq 2 2.0", "", false},                 // Different types.1321	{"lt true true", "", false},             // Unordered types.1322	{"lt 1+0i 1+0i", "", false},             // Unordered types.1323	{"eq .Ptr 1", "", false},                // Incompatible types.1324	{"eq .Ptr .NegOne", "", false},          // Incompatible types.1325	{"eq .Map .V1", "", false},              // Uncomparable types.1326	{"eq .NonNilMap .NonNilMap", "", false}, // Uncomparable types.1327}13281329func TestComparison(t *testing.T) {1330	b := new(strings.Builder)1331	var cmpStruct = struct {1332		Uthree, Ufour    uint1333		NegOne, Three    int1334		Ptr, NilPtr      *int1335		NonNilMap        map[int]int1336		Map              map[int]int1337		V1, V2           V1338		Iface1, NilIface fmt.Stringer1339	}{1340		Uthree:    3,1341		Ufour:     4,1342		NegOne:    -1,1343		Three:     3,1344		Ptr:       new(int),1345		NonNilMap: make(map[int]int),1346		Iface1:    b,1347	}1348	for _, test := range cmpTests {1349		text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr)1350		tmpl, err := New("empty").Parse(text)1351		if err != nil {1352			t.Fatalf("%q: %s", test.expr, err)1353		}1354		b.Reset()1355		err = tmpl.Execute(b, &cmpStruct)1356		if test.ok && err != nil {1357			t.Errorf("%s errored incorrectly: %s", test.expr, err)1358			continue1359		}1360		if !test.ok && err == nil {1361			t.Errorf("%s did not error", test.expr)1362			continue1363		}1364		if b.String() != test.truth {1365			t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String())1366		}1367	}1368}13691370func TestMissingMapKey(t *testing.T) {1371	data := map[string]int{1372		"x": 99,1373	}1374	tmpl, err := New("t1").Parse("{{.x}} {{.y}}")1375	if err != nil {1376		t.Fatal(err)1377	}1378	var b strings.Builder1379	// By default, just get "<no value>"1380	err = tmpl.Execute(&b, data)1381	if err != nil {1382		t.Fatal(err)1383	}1384	want := "99 <no value>"1385	got := b.String()1386	if got != want {1387		t.Errorf("got %q; expected %q", got, want)1388	}1389	// Same if we set the option explicitly to the default.1390	tmpl.Option("missingkey=default")1391	b.Reset()1392	err = tmpl.Execute(&b, data)1393	if err != nil {1394		t.Fatal("default:", err)1395	}1396	want = "99 <no value>"1397	got = b.String()1398	if got != want {1399		t.Errorf("got %q; expected %q", got, want)1400	}1401	// Next we ask for a zero value1402	tmpl.Option("missingkey=zero")1403	b.Reset()1404	err = tmpl.Execute(&b, data)1405	if err != nil {1406		t.Fatal("zero:", err)1407	}1408	want = "99 0"1409	got = b.String()1410	if got != want {1411		t.Errorf("got %q; expected %q", got, want)1412	}1413	// Now we ask for an error.1414	tmpl.Option("missingkey=error")1415	err = tmpl.Execute(&b, data)1416	if err == nil {1417		t.Errorf("expected error; got none")1418	}1419	// same Option, but now a nil interface: ask for an error1420	err = tmpl.Execute(&b, nil)1421	t.Log(err)1422	if err == nil {1423		t.Errorf("expected error for nil-interface; got none")1424	}1425}14261427// Test that the error message for multiline unterminated string1428// refers to the line number of the opening quote.1429func TestUnterminatedStringError(t *testing.T) {1430	_, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n")1431	if err == nil {1432		t.Fatal("expected error")1433	}1434	str := err.Error()1435	if !strings.Contains(str, "X:3: unterminated raw quoted string") {1436		t.Fatalf("unexpected error: %s", str)1437	}1438}14391440const alwaysErrorText = "always be failing"14411442var alwaysError = errors.New(alwaysErrorText)14431444type ErrorWriter int14451446func (e ErrorWriter) Write(p []byte) (int, error) {1447	return 0, alwaysError1448}14491450func TestExecuteGivesExecError(t *testing.T) {1451	// First, a non-execution error shouldn't be an ExecError.1452	tmpl, err := New("X").Parse("hello")1453	if err != nil {1454		t.Fatal(err)1455	}1456	err = tmpl.Execute(ErrorWriter(0), 0)1457	if err == nil {1458		t.Fatal("expected error; got none")1459	}1460	if err.Error() != alwaysErrorText {1461		t.Errorf("expected %q error; got %q", alwaysErrorText, err)1462	}1463	// This one should be an ExecError.1464	tmpl, err = New("X").Parse("hello, {{.X.Y}}")1465	if err != nil {1466		t.Fatal(err)1467	}1468	err = tmpl.Execute(io.Discard, 0)1469	if err == nil {1470		t.Fatal("expected error; got none")1471	}1472	eerr, ok := err.(ExecError)1473	if !ok {1474		t.Fatalf("did not expect ExecError %s", eerr)1475	}1476	expect := "field X in type int"1477	if !strings.Contains(err.Error(), expect) {1478		t.Errorf("expected %q; got %q", expect, err)1479	}1480}14811482func funcNameTestFunc() int {1483	return 01484}14851486func TestGoodFuncNames(t *testing.T) {1487	names := []string{1488		"_",1489		"a",1490		"a1",1491		"a1",1492		"Ӵ",1493	}1494	for _, name := range names {1495		tmpl := New("X").Funcs(1496			FuncMap{1497				name: funcNameTestFunc,1498			},1499		)1500		if tmpl == nil {1501			t.Fatalf("nil result for %q", name)1502		}1503	}1504}15051506func TestBadFuncNames(t *testing.T) {1507	names := []string{1508		"",1509		"2",1510		"a-b",1511	}1512	for _, name := range names {1513		testBadFuncName(name, t)1514	}1515}15161517func TestIsTrue(t *testing.T) {1518	var nil_ptr *int1519	var nil_chan chan int1520	tests := []struct {1521		v    any1522		want bool1523	}{1524		{1, true},1525		{0, false},1526		{uint8(1), true},1527		{uint8(0), false},1528		{float64(1.0), true},1529		{float64(0.0), false},1530		{complex64(1.0), true},1531		{complex64(0.0), false},1532		{true, true},1533		{false, false},1534		{[2]int{1, 2}, true},1535		{[0]int{}, false},1536		{[]byte("abc"), true},1537		{[]byte(""), false},1538		{map[string]int{"a": 1, "b": 2}, true},1539		{map[string]int{}, false},1540		{make(chan int), true},1541		{nil_chan, false},1542		{new(int), true},1543		{nil_ptr, false},1544		{unsafe.Pointer(new(int)), true},1545		{unsafe.Pointer(nil_ptr), false},1546	}1547	for _, test_case := range tests {1548		got, _ := IsTrue(test_case.v)1549		if got != test_case.want {1550			t.Fatalf("expect result %v, got %v", test_case.want, got)1551		}1552	}1553}15541555func testBadFuncName(name string, t *testing.T) {1556	t.Helper()1557	defer func() {1558		recover()1559	}()1560	New("X").Funcs(1561		FuncMap{1562			name: funcNameTestFunc,1563		},1564	)1565	// If we get here, the name did not cause a panic, which is how Funcs1566	// reports an error.1567	t.Errorf("%q succeeded incorrectly as function name", name)1568}15691570func TestBlock(t *testing.T) {1571	const (1572		input   = `a({{block "inner" .}}bar({{.}})baz{{end}})b`1573		want    = `a(bar(hello)baz)b`1574		overlay = `{{define "inner"}}foo({{.}})bar{{end}}`1575		want2   = `a(foo(goodbye)bar)b`1576	)1577	tmpl, err := New("outer").Parse(input)1578	if err != nil {1579		t.Fatal(err)1580	}1581	tmpl2, err := Must(tmpl.Clone()).Parse(overlay)1582	if err != nil {1583		t.Fatal(err)1584	}15851586	var buf strings.Builder1587	if err := tmpl.Execute(&buf, "hello"); err != nil {1588		t.Fatal(err)1589	}1590	if got := buf.String(); got != want {1591		t.Errorf("got %q, want %q", got, want)1592	}15931594	buf.Reset()1595	if err := tmpl2.Execute(&buf, "goodbye"); err != nil {1596		t.Fatal(err)1597	}1598	if got := buf.String(); got != want2 {1599		t.Errorf("got %q, want %q", got, want2)1600	}1601}16021603func TestEvalFieldErrors(t *testing.T) {1604	tests := []struct {1605		name, src string1606		value     any1607		want      string1608	}{1609		{1610			// Check that calling an invalid field on nil pointer1611			// prints a field error instead of a distracting nil1612			// pointer error. https://golang.org/issue/151251613			"MissingFieldOnNil",1614			"{{.MissingField}}",1615			(*T)(nil),1616			"can't evaluate field MissingField in type *template.T",1617		},1618		{1619			"MissingFieldOnNonNil",1620			"{{.MissingField}}",1621			&T{},1622			"can't evaluate field MissingField in type *template.T",1623		},1624		{1625			"ExistingFieldOnNil",1626			"{{.X}}",1627			(*T)(nil),1628			"nil pointer evaluating *template.T.X",1629		},1630		{1631			"MissingKeyOnNilMap",1632			"{{.MissingKey}}",1633			(*map[string]string)(nil),1634			"nil pointer evaluating *map[string]string.MissingKey",1635		},1636		{1637			"MissingKeyOnNilMapPtr",1638			"{{.MissingKey}}",1639			(*map[string]string)(nil),1640			"nil pointer evaluating *map[string]string.MissingKey",1641		},1642		{1643			"MissingKeyOnMapPtrToNil",1644			"{{.MissingKey}}",1645			&map[string]string{},1646			"<nil>",1647		},1648	}1649	for _, tc := range tests {1650		t.Run(tc.name, func(t *testing.T) {1651			tmpl := Must(New("tmpl").Parse(tc.src))1652			err := tmpl.Execute(io.Discard, tc.value)1653			got := "<nil>"1654			if err != nil {1655				got = err.Error()1656			}1657			if !strings.HasSuffix(got, tc.want) {1658				t.Fatalf("got error %q, want %q", got, tc.want)1659			}1660		})1661	}1662}16631664func TestMaxExecDepth(t *testing.T) {1665	if testing.Short() {1666		t.Skip("skipping in -short mode")1667	}1668	tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`))1669	err := tmpl.Execute(io.Discard, nil)1670	got := "<nil>"1671	if err != nil {1672		got = err.Error()1673	}1674	const want = "exceeded maximum template depth"1675	if !strings.Contains(got, want) {1676		t.Errorf("got error %q; want %q", got, want)1677	}1678}16791680func TestAddrOfIndex(t *testing.T) {1681	// golang.org/issue/14916.1682	// Before index worked on reflect.Values, the .String could not be1683	// found on the (incorrectly unaddressable) V value,1684	// in contrast to range, which worked fine.1685	// Also testing that passing a reflect.Value to tmpl.Execute works.1686	texts := []string{1687		`{{range .}}{{.String}}{{end}}`,1688		`{{with index . 0}}{{.String}}{{end}}`,1689	}1690	for _, text := range texts {1691		tmpl := Must(New("tmpl").Parse(text))1692		var buf strings.Builder1693		err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}}))1694		if err != nil {1695			t.Fatalf("%s: Execute: %v", text, err)1696		}1697		if buf.String() != "<1>" {1698			t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>")1699		}1700	}1701}17021703func TestInterfaceValues(t *testing.T) {1704	// golang.org/issue/17714.1705	// Before index worked on reflect.Values, interface values1706	// were always implicitly promoted to the underlying value,1707	// except that nil interfaces were promoted to the zero reflect.Value.1708	// Eliminating a round trip to interface{} and back to reflect.Value1709	// eliminated this promotion, breaking these cases.1710	tests := []struct {1711		text string1712		out  string1713	}{1714		{`{{index .Nil 1}}`, "ERROR: index of untyped nil"},1715		{`{{index .Slice 2}}`, "2"},1716		{`{{index .Slice .Two}}`, "2"},1717		{`{{call .Nil 1}}`, "ERROR: call of nil"},1718		{`{{call .PlusOne 1}}`, "2"},1719		{`{{call .PlusOne .One}}`, "2"},1720		{`{{and (index .Slice 0) true}}`, "0"},1721		{`{{and .Zero true}}`, "0"},1722		{`{{and (index .Slice 1) false}}`, "false"},1723		{`{{and .One false}}`, "false"},1724		{`{{or (index .Slice 0) false}}`, "false"},1725		{`{{or .Zero false}}`, "false"},1726		{`{{or (index .Slice 1) true}}`, "1"},1727		{`{{or .One true}}`, "1"},1728		{`{{not (index .Slice 0)}}`, "true"},1729		{`{{not .Zero}}`, "true"},1730		{`{{not (index .Slice 1)}}`, "false"},1731		{`{{not .One}}`, "false"},1732		{`{{eq (index .Slice 0) .Zero}}`, "true"},1733		{`{{eq (index .Slice 1) .One}}`, "true"},1734		{`{{ne (index .Slice 0) .Zero}}`, "false"},1735		{`{{ne (index .Slice 1) .One}}`, "false"},1736		{`{{ge (index .Slice 0) .One}}`, "false"},1737		{`{{ge (index .Slice 1) .Zero}}`, "true"},1738		{`{{gt (index .Slice 0) .One}}`, "false"},1739		{`{{gt (index .Slice 1) .Zero}}`, "true"},1740		{`{{le (index .Slice 0) .One}}`, "true"},1741		{`{{le (index .Slice 1) .Zero}}`, "false"},1742		{`{{lt (index .Slice 0) .One}}`, "true"},1743		{`{{lt (index .Slice 1) .Zero}}`, "false"},1744	}17451746	for _, tt := range tests {1747		tmpl := Must(New("tmpl").Parse(tt.text))1748		var buf strings.Builder1749		err := tmpl.Execute(&buf, map[string]any{1750			"PlusOne": func(n int) int {1751				return n + 11752			},1753			"Slice": []int{0, 1, 2, 3},1754			"One":   1,1755			"Two":   2,1756			"Nil":   nil,1757			"Zero":  0,1758		})1759		if strings.HasPrefix(tt.out, "ERROR:") {1760			e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:"))1761			if err == nil || !strings.Contains(err.Error(), e) {1762				t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e)1763			}1764			continue1765		}1766		if err != nil {1767			t.Errorf("%s: Execute: %v", tt.text, err)1768			continue1769		}1770		if buf.String() != tt.out {1771			t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out)1772		}1773	}1774}17751776// Check that panics during calls are recovered and returned as errors.1777func TestExecutePanicDuringCall(t *testing.T) {1778	funcs := map[string]any{1779		"doPanic": func() string {1780			panic("custom panic string")1781		},1782	}1783	tests := []struct {1784		name    string1785		input   string1786		data    any1787		wantErr string1788	}{1789		{1790			"direct func call panics",1791			"{{doPanic}}", (*T)(nil),1792			`template: t:1:2: executing "t" at <doPanic>: error calling doPanic: custom panic string`,1793		},1794		{1795			"indirect func call panics",1796			"{{call doPanic}}", (*T)(nil),1797			`template: t:1:7: executing "t" at <doPanic>: error calling doPanic: custom panic string`,1798		},1799		{1800			"direct method call panics",1801			"{{.GetU}}", (*T)(nil),1802			`template: t:1:2: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,1803		},1804		{1805			"indirect method call panics",1806			"{{call .GetU}}", (*T)(nil),1807			`template: t:1:7: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`,1808		},1809		{1810			"func field call panics",1811			"{{call .PanicFunc}}", tVal,1812			`template: t:1:2: executing "t" at <call .PanicFunc>: error calling call: test panic`,1813		},1814		{1815			"method call on nil interface",1816			"{{.NonEmptyInterfaceNil.Method0}}", tVal,1817			`template: t:1:23: executing "t" at <.NonEmptyInterfaceNil.Method0>: nil pointer evaluating template.I.Method0`,1818		},1819	}1820	for _, tc := range tests {1821		b := new(bytes.Buffer)1822		tmpl, err := New("t").Funcs(funcs).Parse(tc.input)1823		if err != nil {1824			t.Fatalf("parse error: %s", err)1825		}1826		err = tmpl.Execute(b, tc.data)1827		if err == nil {1828			t.Errorf("%s: expected error; got none", tc.name)1829		} else if !strings.Contains(err.Error(), tc.wantErr) {1830			if *debug {1831				fmt.Printf("%s: test execute error: %s\n", tc.name, err)1832			}1833			t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)1834		}1835	}1836}18371838func TestFunctionCheckDuringCall(t *testing.T) {1839	tests := []struct {1840		name    string1841		input   string1842		data    any1843		wantErr string1844	}{{1845		name:    "call nothing",1846		input:   `{{call}}`,1847		data:    tVal,1848		wantErr: "wrong number of args for call: want at least 1 got 0",1849	},1850		{1851			name:    "call non-function",1852			input:   "{{call .True}}",1853			data:    tVal,1854			wantErr: "error calling call: non-function .True of type bool",1855		},1856		{1857			name:    "call func with wrong argument",1858			input:   "{{call .BinaryFunc 1}}",1859			data:    tVal,1860			wantErr: "error calling call: wrong number of args for .BinaryFunc: got 1 want 2",1861		},1862		{1863			name:    "call variadic func with wrong argument",1864			input:   `{{call .VariadicFuncInt}}`,1865			data:    tVal,1866			wantErr: "error calling call: wrong number of args for .VariadicFuncInt: got 0 want at least 1",1867		},1868		{1869			name:    "call too few return number func",1870			input:   `{{call .TooFewReturnCountFunc}}`,1871			data:    tVal,1872			wantErr: "error calling call: function .TooFewReturnCountFunc has 0 return values; should be 1 or 2",1873		},1874		{1875			name:    "call too many return number func",1876			input:   `{{call .TooManyReturnCountFunc}}`,1877			data:    tVal,1878			wantErr: "error calling call: function .TooManyReturnCountFunc has 3 return values; should be 1 or 2",1879		},1880		{1881			name:    "call invalid return type func",1882			input:   `{{call .InvalidReturnTypeFunc}}`,1883			data:    tVal,1884			wantErr: "error calling call: invalid function signature for .InvalidReturnTypeFunc: second return value should be error; is bool",1885		},1886		{1887			name:    "call pipeline",1888			input:   `{{call (len "test")}}`,1889			data:    nil,1890			wantErr: "error calling call: non-function len \"test\" of type int",1891		},1892	}18931894	for _, tc := range tests {1895		b := new(bytes.Buffer)1896		tmpl, err := New("t").Parse(tc.input)1897		if err != nil {1898			t.Fatalf("parse error: %s", err)1899		}1900		err = tmpl.Execute(b, tc.data)1901		if err == nil {1902			t.Errorf("%s: expected error; got none", tc.name)1903		} else if tc.wantErr == "" || !strings.Contains(err.Error(), tc.wantErr) {1904			if *debug {1905				fmt.Printf("%s: test execute error: %s\n", tc.name, err)1906			}1907			t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err)1908		}1909	}1910}19111912// Issue 31810. Check that a parenthesized first argument behaves properly.1913func TestIssue31810(t *testing.T) {1914	// A simple value with no arguments is fine.1915	var b strings.Builder1916	const text = "{{ (.)  }}"1917	tmpl, err := New("").Parse(text)1918	if err != nil {1919		t.Error(err)1920	}1921	err = tmpl.Execute(&b, "result")1922	if err != nil {1923		t.Error(err)1924	}1925	if b.String() != "result" {1926		t.Errorf("%s got %q, expected %q", text, b.String(), "result")1927	}19281929	// Even a plain function fails - need to use call.1930	f := func() string { return "result" }1931	b.Reset()1932	err = tmpl.Execute(&b, f)1933	if err == nil {1934		t.Error("expected error with no call, got none")1935	}19361937	// Works if the function is explicitly called.1938	const textCall = "{{ (call .)  }}"1939	tmpl, err = New("").Parse(textCall)1940	b.Reset()1941	err = tmpl.Execute(&b, f)1942	if err != nil {1943		t.Error(err)1944	}1945	if b.String() != "result" {1946		t.Errorf("%s got %q, expected %q", textCall, b.String(), "result")1947	}1948}19491950// Issue 43065, range over send only channel1951func TestIssue43065(t *testing.T) {1952	var b bytes.Buffer1953	tmp := Must(New("").Parse(`{{range .}}{{end}}`))1954	ch := make(chan<- int)1955	err := tmp.Execute(&b, ch)1956	if err == nil {1957		t.Error("expected err got nil")1958	} else if !strings.Contains(err.Error(), "range over send-only channel") {1959		t.Errorf("%s", err)1960	}1961}19621963// Issue 39807: data race in html/template & text/template1964func TestIssue39807(t *testing.T) {1965	var wg sync.WaitGroup19661967	tplFoo, err := New("foo").Parse(`{{ template "bar" . }}`)1968	if err != nil {1969		t.Error(err)1970	}19711972	tplBar, err := New("bar").Parse("bar")1973	if err != nil {1974		t.Error(err)1975	}19761977	gofuncs := 101978	numTemplates := 1019791980	for i := 1; i <= gofuncs; i++ {1981		wg.Add(1)1982		go func() {1983			defer wg.Done()1984			for j := 0; j < numTemplates; j++ {1985				_, err := tplFoo.AddParseTree(tplBar.Name(), tplBar.Tree)1986				if err != nil {1987					t.Error(err)1988				}1989				err = tplFoo.Execute(io.Discard, nil)1990				if err != nil {1991					t.Error(err)1992				}1993			}1994		}()1995	}19961997	wg.Wait()1998}19992000// Issue 48215: embedded nil pointer causes panic.

Code quality findings 20

Empty interface; prefer specific types or generics for type safety
empty-interface
// Eliminating a round trip to interface{} and back to reflect.Value
Use of unsafe package detected; ensure it’s necessary, justified in comments, and bounds-checked to avoid memory corruption
warning safety unsafe-package
UPI unsafe.Pointer
Use of unsafe package detected; ensure it’s necessary, justified in comments, and bounds-checked to avoid memory corruption
warning safety unsafe-package
EmptyUPI unsafe.Pointer
Use of unsafe package detected; ensure it’s necessary, justified in comments, and bounds-checked to avoid memory corruption
warning safety unsafe-package
func newUnsafePointer(n int) unsafe.Pointer {
Use of unsafe package detected; ensure it’s necessary, justified in comments, and bounds-checked to avoid memory corruption
warning safety unsafe-package
return unsafe.Pointer(&n)
Use of unsafe package detected; ensure it’s necessary, justified in comments, and bounds-checked to avoid memory corruption
warning safety unsafe-package
{unsafe.Pointer(new(int)), true},
Use of unsafe package detected; ensure it’s necessary, justified in comments, and bounds-checked to avoid memory corruption
warning safety unsafe-package
{unsafe.Pointer(nil_ptr), false},
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer func() {
May hide panics instead of handling errors properly; use only with specific panic recovery logic
warning correctness recover-without-defer
recover()
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer wg.Done()
Range over slice copies each element by value; use index or pointer receiver for large structs to avoid copies
info performance copy-large-struct
for i, x := range b {
Range over slice copies each element by value; use index or pointer receiver for large structs to avoid copies
info performance copy-large-struct
{"i, c := range iter.Seq2[int,int]", `{{range $i, $c := .}}{{$i}}{{$c}}{{end}}`, "0112", fVal2(2), true},
Map created without size hint before being populated in a loop; provide capacity hint to reduce allocations
info performance map-without-size-hint
m := make(map[string]string)
Formatted output to console; prefer structured logging for consistency
info correctness fmt-printf
fmt.Printf("%s: %s\n\t%s\n", test.name, test.input, err)
Deeply nested control structures reduce readability; consider extracting to functions or using early returns
info maintainability deep-nesting
if right == "" { // default case
Formatted output to console; prefer structured logging for consistency
info correctness fmt-printf
fmt.Printf("test execute error: %s\n", err)
String to byte slice conversion inside loop allocates a new slice each iteration; convert once before the loop
info correctness string-to-byte-in-loop
{[]byte(""), false},
Formatted output to console; prefer structured logging for consistency
info correctness fmt-printf
fmt.Printf("%s: test execute error: %s\n", tc.name, err)
Deeply nested control structures reduce readability; consider extracting to functions or using early returns
info maintainability deep-nesting
wantErr: "wrong number of args for call: want at least 1 got 0",
Formatted output to console; prefer structured logging for consistency
info correctness fmt-printf
fmt.Printf("%s: test execute error: %s\n", tc.name, err)

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.