| 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 |
package template |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"errors" |
| 10 |
"flag" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"iter" |
| 14 |
"reflect" |
| 15 |
"strings" |
| 16 |
"sync" |
| 17 |
"testing" |
| 18 |
"unsafe" |
| 19 |
) |
| 20 |
|
| 21 |
var debug = flag.Bool("debug", false, "show the errors produced by the tests") |
| 22 |
|
| 23 |
// T has lots of interesting pieces to use to test execution. |
| 24 |
type T struct { |
| 25 |
// Basics |
| 26 |
True bool |
| 27 |
I int |
| 28 |
U16 uint16 |
| 29 |
X, S string |
| 30 |
FloatZero float64 |
| 31 |
ComplexZero complex128 |
| 32 |
// Nested structs. |
| 33 |
U *U |
| 34 |
// Struct with String method. |
| 35 |
V0 V |
| 36 |
V1, V2 *V |
| 37 |
// Struct with Error method. |
| 38 |
W0 W |
| 39 |
W1, W2 *W |
| 40 |
// Slices |
| 41 |
SI []int |
| 42 |
SICap []int |
| 43 |
SIEmpty []int |
| 44 |
SB []bool |
| 45 |
// Arrays |
| 46 |
AI [3]int |
| 47 |
PAI *[3]int // pointer to array |
| 48 |
// Maps |
| 49 |
MSI map[string]int |
| 50 |
MSIone map[string]int // one element, for deterministic output |
| 51 |
MSIEmpty map[string]int |
| 52 |
MXI map[any]int |
| 53 |
MII map[int]int |
| 54 |
MI32S map[int32]string |
| 55 |
MI64S map[int64]string |
| 56 |
MUI32S map[uint32]string |
| 57 |
MUI64S map[uint64]string |
| 58 |
MI8S map[int8]string |
| 59 |
MUI8S map[uint8]string |
| 60 |
SMSI []map[string]int |
| 61 |
// Empty interfaces; used to see if we can dig inside one. |
| 62 |
Empty0 any // nil |
| 63 |
Empty1 any |
| 64 |
Empty2 any |
| 65 |
Empty3 any |
| 66 |
Empty4 any |
| 67 |
// Non-empty interfaces. |
| 68 |
NonEmptyInterface I |
| 69 |
NonEmptyInterfacePtS *I |
| 70 |
NonEmptyInterfaceNil I |
| 71 |
NonEmptyInterfaceTypedNil I |
| 72 |
// Stringer. |
| 73 |
Str fmt.Stringer |
| 74 |
Err error |
| 75 |
// Pointers |
| 76 |
PI *int |
| 77 |
PS *string |
| 78 |
PSI *[]int |
| 79 |
NIL *int |
| 80 |
UPI unsafe.Pointer |
| 81 |
EmptyUPI unsafe.Pointer |
| 82 |
// Function (not method) |
| 83 |
BinaryFunc func(string, string) string |
| 84 |
VariadicFunc func(...string) string |
| 85 |
VariadicFuncInt func(int, ...string) string |
| 86 |
NilOKFunc func(*int) bool |
| 87 |
ErrFunc func() (string, error) |
| 88 |
PanicFunc func() string |
| 89 |
TooFewReturnCountFunc func() |
| 90 |
TooManyReturnCountFunc func() (string, error, int) |
| 91 |
InvalidReturnTypeFunc func() (string, bool) |
| 92 |
// Template to test evaluation of templates. |
| 93 |
Tmpl *Template |
| 94 |
// Unexported field; cannot be accessed by template. |
| 95 |
unexported int |
| 96 |
} |
| 97 |
|
| 98 |
type S []string |
| 99 |
|
| 100 |
func (S) Method0() string { |
| 101 |
return "M0" |
| 102 |
} |
| 103 |
|
| 104 |
type U struct { |
| 105 |
V string |
| 106 |
} |
| 107 |
|
| 108 |
type V struct { |
| 109 |
j int |
| 110 |
} |
| 111 |
|
| 112 |
func (v *V) String() string { |
| 113 |
if v == nil { |
| 114 |
return "nilV" |
| 115 |
} |
| 116 |
return fmt.Sprintf("<%d>", v.j) |
| 117 |
} |
| 118 |
|
| 119 |
type W struct { |
| 120 |
k int |
| 121 |
} |
| 122 |
|
| 123 |
func (w *W) Error() string { |
| 124 |
if w == nil { |
| 125 |
return "nilW" |
| 126 |
} |
| 127 |
return fmt.Sprintf("[%d]", w.k) |
| 128 |
} |
| 129 |
|
| 130 |
var siVal = I(S{"a", "b"}) |
| 131 |
|
| 132 |
var 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 nil |
| 141 |
W0: W{888}, |
| 142 |
W1: &W{999}, // leave W2 as nil |
| 143 |
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 .X |
| 185 |
} |
| 186 |
|
| 187 |
var tSliceOfNil = []*T{nil} |
| 188 |
|
| 189 |
// A non-empty interface. |
| 190 |
type I interface { |
| 191 |
Method0() string |
| 192 |
} |
| 193 |
|
| 194 |
var iVal I = tVal |
| 195 |
|
| 196 |
// Helpers for creation. |
| 197 |
func newInt(n int) *int { |
| 198 |
return &n |
| 199 |
} |
| 200 |
|
| 201 |
func newUnsafePointer(n int) unsafe.Pointer { |
| 202 |
return unsafe.Pointer(&n) |
| 203 |
} |
| 204 |
|
| 205 |
func newString(s string) *string { |
| 206 |
return &s |
| 207 |
} |
| 208 |
|
| 209 |
func newIntSlice(n ...int) *[]int { |
| 210 |
p := new([]int) |
| 211 |
*p = make([]int, len(n)) |
| 212 |
copy(*p, n) |
| 213 |
return p |
| 214 |
} |
| 215 |
|
| 216 |
// Simple methods with and without arguments. |
| 217 |
func (t *T) Method0() string { |
| 218 |
return "M0" |
| 219 |
} |
| 220 |
|
| 221 |
func (t *T) Method1(a int) int { |
| 222 |
return a |
| 223 |
} |
| 224 |
|
| 225 |
func (t *T) Method2(a uint16, b string) string { |
| 226 |
return fmt.Sprintf("Method2: %d %s", a, b) |
| 227 |
} |
| 228 |
|
| 229 |
func (t *T) Method3(v any) string { |
| 230 |
return fmt.Sprintf("Method3: %v", v) |
| 231 |
} |
| 232 |
|
| 233 |
func (t *T) Copy() *T { |
| 234 |
n := new(T) |
| 235 |
*n = *t |
| 236 |
return n |
| 237 |
} |
| 238 |
|
| 239 |
func (t *T) MAdd(a int, b []int) []int { |
| 240 |
v := make([]int, len(b)) |
| 241 |
for i, x := range b { |
| 242 |
v[i] = x + a |
| 243 |
} |
| 244 |
return v |
| 245 |
} |
| 246 |
|
| 247 |
var myError = errors.New("my error") |
| 248 |
|
| 249 |
// MyError returns a value and an error according to its argument. |
| 250 |
func (t *T) MyError(error bool) (bool, error) { |
| 251 |
if error { |
| 252 |
return true, myError |
| 253 |
} |
| 254 |
return false, nil |
| 255 |
} |
| 256 |
|
| 257 |
// A few methods to test chaining. |
| 258 |
func (t *T) GetU() *U { |
| 259 |
return t.U |
| 260 |
} |
| 261 |
|
| 262 |
func (u *U) TrueFalse(b bool) string { |
| 263 |
if b { |
| 264 |
return "true" |
| 265 |
} |
| 266 |
return "" |
| 267 |
} |
| 268 |
|
| 269 |
func typeOf(arg any) string { |
| 270 |
return fmt.Sprintf("%T", arg) |
| 271 |
} |
| 272 |
|
| 273 |
type execTest struct { |
| 274 |
name string |
| 275 |
input string |
| 276 |
output string |
| 277 |
data any |
| 278 |
ok bool |
| 279 |
} |
| 280 |
|
| 281 |
// bigInt and bigUint are hex string representing numbers either side |
| 282 |
// of the max int boundary. |
| 283 |
// We do it this way so the test doesn't depend on ints being 32 bits. |
| 284 |
var ( |
| 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 |
) |
| 288 |
|
| 289 |
var execTests = []execTest{ |
| 290 |
// Trivial cases. |
| 291 |
{"empty", "", "", nil, true}, |
| 292 |
{"text", "some text", "some text", nil, true}, |
| 293 |
{"nil action", "{{nil}}", "", nil, false}, |
| 294 |
|
| 295 |
// 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}, |
| 303 |
|
| 304 |
// Fields of structs. |
| 305 |
{".X", "-{{.X}}-", "-x-", tVal, true}, |
| 306 |
{".U.V", "-{{.U.V}}-", "-v-", tVal, true}, |
| 307 |
{".unexported", "{{.unexported}}", "", tVal, false}, |
| 308 |
|
| 309 |
// 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}, |
| 316 |
|
| 317 |
// 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 int |
| 328 |
b string |
| 329 |
}{7, "seven"}, true}, |
| 330 |
|
| 331 |
// 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}, |
| 343 |
|
| 344 |
// 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}, |
| 348 |
|
| 349 |
// 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}, |
| 353 |
|
| 354 |
// 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}, |
| 360 |
|
| 361 |
// 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}, |
| 368 |
|
| 369 |
// Edge cases with <no value> with an interface value |
| 370 |
{"field on interface", "{{.foo}}", "<no value>", nil, true}, |
| 371 |
{"field on parenthesized interface", "{{(.).foo}}", "<no value>", nil, true}, |
| 372 |
|
| 373 |
// 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. |
| 378 |
|
| 379 |
// 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}, |
| 402 |
|
| 403 |
// 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}, |
| 416 |
|
| 417 |
// 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}, |
| 426 |
|
| 427 |
// Pipelines. |
| 428 |
{"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true}, |
| 429 |
{"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true}, |
| 430 |
|
| 431 |
// 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}, |
| 435 |
|
| 436 |
// Parenthesized expressions |
| 437 |
{"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true}, |
| 438 |
|
| 439 |
// Parenthesized expressions with field accesses |
| 440 |
{"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}, |
| 444 |
|
| 445 |
// 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}, |
| 472 |
|
| 473 |
// 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}, |
| 488 |
|
| 489 |
// HTML. |
| 490 |
{"html", `{{html "<script>alert(\"XSS\");</script>"}}`, |
| 491 |
"<script>alert("XSS");</script>", nil, true}, |
| 492 |
{"html pipeline", `{{printf "<script>alert(\"XSS\");</script>" | html}}`, |
| 493 |
"<script>alert("XSS");</script>", nil, true}, |
| 494 |
{"html", `{{html .PS}}`, "a string", tVal, true}, |
| 495 |
{"html typed nil", `{{html .NIL}}`, "<nil>", tVal, true}, |
| 496 |
{"html untyped nil", `{{html .Empty0}}`, "<no value>", tVal, true}, |
| 497 |
|
| 498 |
// JavaScript. |
| 499 |
{"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true}, |
| 500 |
|
| 501 |
// URL query. |
| 502 |
{"urlquery", `{{"http://www.example.org/"|urlquery}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true}, |
| 503 |
|
| 504 |
// Booleans |
| 505 |
{"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}, |
| 521 |
|
| 522 |
// 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}, |
| 542 |
|
| 543 |
// 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}, |
| 571 |
|
| 572 |
// 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}, |
| 578 |
|
| 579 |
// 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}, |
| 601 |
|
| 602 |
// 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}, |
| 649 |
|
| 650 |
// 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}, |
| 653 |
|
| 654 |
// Error handling. |
| 655 |
{"error method, error", "{{.MyError true}}", "", tVal, false}, |
| 656 |
{"error method, no error", "{{.MyError false}}", "false", tVal, true}, |
| 657 |
|
| 658 |
// Numbers |
| 659 |
{"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}, |
| 678 |
|
| 679 |
// 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}, |
| 742 |
|
| 743 |
// More variadic function corner cases. Some runes would get evaluated |
| 744 |
// 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}, |
| 748 |
|
| 749 |
{"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 |
} |
| 752 |
|
| 753 |
func fVal1(i int) iter.Seq[int] { |
| 754 |
return func(yield func(int) bool) { |
| 755 |
for v := range i { |
| 756 |
if !yield(v) { |
| 757 |
break |
| 758 |
} |
| 759 |
} |
| 760 |
} |
| 761 |
} |
| 762 |
|
| 763 |
func 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 |
break |
| 768 |
} |
| 769 |
} |
| 770 |
} |
| 771 |
} |
| 772 |
|
| 773 |
const rangeTestInt = `{{range $v := .}}{{printf "%T%d" $v $v}}{{end}}` |
| 774 |
|
| 775 |
func rangeTestData[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr]() string { |
| 776 |
I := T(5) |
| 777 |
var buf strings.Builder |
| 778 |
for i := T(0); i < I; i++ { |
| 779 |
fmt.Fprintf(&buf, "%T%d", i, i) |
| 780 |
} |
| 781 |
return buf.String() |
| 782 |
} |
| 783 |
|
| 784 |
func zeroArgs() string { |
| 785 |
return "zeroArgs" |
| 786 |
} |
| 787 |
|
| 788 |
func oneArg(a string) string { |
| 789 |
return "oneArg=" + a |
| 790 |
} |
| 791 |
|
| 792 |
func twoArgs(a, b string) string { |
| 793 |
return "twoArgs=" + a + b |
| 794 |
} |
| 795 |
|
| 796 |
func dddArg(a int, b ...string) string { |
| 797 |
return fmt.Sprintln(a, b) |
| 798 |
} |
| 799 |
|
| 800 |
// count returns a channel that will deliver n sequential 1-letter strings starting at "a" |
| 801 |
func count(n int) chan string { |
| 802 |
if n == 0 { |
| 803 |
return nil |
| 804 |
} |
| 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 c |
| 813 |
} |
| 814 |
|
| 815 |
// vfunc takes a *V and a V |
| 816 |
func vfunc(V, *V) string { |
| 817 |
return "vfunc" |
| 818 |
} |
| 819 |
|
| 820 |
// valueString takes a string, not a pointer. |
| 821 |
func valueString(v string) string { |
| 822 |
return "value is ignored" |
| 823 |
} |
| 824 |
|
| 825 |
// returnInt returns an int |
| 826 |
func returnInt() int { |
| 827 |
return 7 |
| 828 |
} |
| 829 |
|
| 830 |
func add(args ...int) int { |
| 831 |
sum := 0 |
| 832 |
for _, x := range args { |
| 833 |
sum += x |
| 834 |
} |
| 835 |
return sum |
| 836 |
} |
| 837 |
|
| 838 |
func echo(arg any) any { |
| 839 |
return arg |
| 840 |
} |
| 841 |
|
| 842 |
func 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 m |
| 851 |
} |
| 852 |
|
| 853 |
func stringer(s fmt.Stringer) string { |
| 854 |
return s.String() |
| 855 |
} |
| 856 |
|
| 857 |
func mapOfThree() any { |
| 858 |
return map[string]int{"three": 3} |
| 859 |
} |
| 860 |
|
| 861 |
func 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 *Template |
| 882 |
var err error |
| 883 |
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 |
continue |
| 891 |
} |
| 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 |
continue |
| 898 |
case test.ok && err != nil: |
| 899 |
t.Errorf("%s: unexpected execute error: %s", test.name, err) |
| 900 |
continue |
| 901 |
case !test.ok && err != nil: |
| 902 |
// expected error, got one |
| 903 |
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 |
} |
| 913 |
|
| 914 |
func TestExecute(t *testing.T) { |
| 915 |
testExecute(execTests, nil, t) |
| 916 |
} |
| 917 |
|
| 918 |
var delimPairs = []string{ |
| 919 |
"", "", // default |
| 920 |
"{{", "}}", // same as default |
| 921 |
"<<", ">>", // distinct |
| 922 |
"|", "|", // same |
| 923 |
"(日)", "(本)", // peculiar |
| 924 |
} |
| 925 |
|
| 926 |
func 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 |
text := ".Str" |
| 931 |
left := delimPairs[i+0] |
| 932 |
trueLeft := left |
| 933 |
right := delimPairs[i+1] |
| 934 |
trueRight := right |
| 935 |
if left == "" { // default case |
| 936 |
trueLeft = "{{" |
| 937 |
} |
| 938 |
if right == "" { // default case |
| 939 |
trueRight = "}}" |
| 940 |
} |
| 941 |
text = trueLeft + text + trueRight |
| 942 |
// Now add a comment |
| 943 |
text += trueLeft + "/*comment*/" + trueRight |
| 944 |
// Now add an action containing a string. |
| 945 |
text += trueLeft + `"` + trueLeft + `"` + trueRight |
| 946 |
// 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 |
var b = new(strings.Builder) |
| 952 |
err = tmpl.Execute(b, value) |
| 953 |
if err != nil { |
| 954 |
t.Fatalf("delim %q exec err %s", left, err) |
| 955 |
} |
| 956 |
if b.String() != hello+trueLeft { |
| 957 |
t.Errorf("expected %q got %q", hello+trueLeft, b.String()) |
| 958 |
} |
| 959 |
} |
| 960 |
} |
| 961 |
|
| 962 |
// Check that an error from a method flows back to the top. |
| 963 |
func TestExecuteError(t *testing.T) { |
| 964 |
b := new(bytes.Buffer) |
| 965 |
tmpl := New("error") |
| 966 |
_, err := tmpl.Parse("{{.MyError true}}") |
| 967 |
if err != nil { |
| 968 |
t.Fatalf("parse error: %s", err) |
| 969 |
} |
| 970 |
err = tmpl.Execute(b, tVal) |
| 971 |
if err == nil { |
| 972 |
t.Errorf("expected error; got none") |
| 973 |
} else if !strings.Contains(err.Error(), myError.Error()) { |
| 974 |
if *debug { |
| 975 |
fmt.Printf("test execute error: %s\n", err) |
| 976 |
} |
| 977 |
t.Errorf("expected myError; got %s", err) |
| 978 |
} |
| 979 |
} |
| 980 |
|
| 981 |
const execErrorText = `line 1 |
| 982 |
line 2 |
| 983 |
line 3 |
| 984 |
{{template "one" .}} |
| 985 |
{{define "one"}}{{template "two" .}}{{end}} |
| 986 |
{{define "two"}}{{template "three" .}}{{end}} |
| 987 |
{{define "three"}}{{index "hi" $}}{{end}}` |
| 988 |
|
| 989 |
// Check that an error from a nested template contains all the relevant information. |
| 990 |
func TestExecError(t *testing.T) { |
| 991 |
tmpl, err := New("top").Parse(execErrorText) |
| 992 |
if err != nil { |
| 993 |
t.Fatal("parse error:", err) |
| 994 |
} |
| 995 |
var b bytes.Buffer |
| 996 |
err = tmpl.Execute(&b, 5) // 5 is out of range indexing "hi" |
| 997 |
if err == nil { |
| 998 |
t.Fatal("expected error") |
| 999 |
} |
| 1000 |
const want = `template: top:7:20: executing "three" at <index "hi" $>: error calling index: index out of range: 5` |
| 1001 |
got := err.Error() |
| 1002 |
if got != want { |
| 1003 |
t.Errorf("expected\n%q\ngot\n%q", want, got) |
| 1004 |
} |
| 1005 |
} |
| 1006 |
|
| 1007 |
type CustomError struct{} |
| 1008 |
|
| 1009 |
func (*CustomError) Error() string { return "heyo !" } |
| 1010 |
|
| 1011 |
// Check that a custom error can be returned. |
| 1012 |
func TestExecError_CustomError(t *testing.T) { |
| 1013 |
failingFunc := func() (string, error) { |
| 1014 |
return "", &CustomError{} |
| 1015 |
} |
| 1016 |
tmpl := Must(New("top").Funcs(FuncMap{ |
| 1017 |
"err": failingFunc, |
| 1018 |
}).Parse("{{ err }}")) |
| 1019 |
|
| 1020 |
var b bytes.Buffer |
| 1021 |
err := tmpl.Execute(&b, nil) |
| 1022 |
|
| 1023 |
if _, ok := errors.AsType[*CustomError](err); !ok { |
| 1024 |
t.Fatalf("expected custom error; got %s", err) |
| 1025 |
} |
| 1026 |
} |
| 1027 |
|
| 1028 |
func TestJSEscaping(t *testing.T) { |
| 1029 |
testCases := []struct { |
| 1030 |
in, exp string |
| 1031 |
}{ |
| 1032 |
{`a`, `a`}, |
| 1033 |
{`'foo`, `\'foo`}, |
| 1034 |
{`Go "jump" \`, `Go \"jump\" \\`}, |
| 1035 |
{`Yukihiro says "今日は世界"`, `Yukihiro says \"今日は世界\"`}, |
| 1036 |
{"unprintable \uFFFE", `unprintable \uFFFE`}, |
| 1037 |
{`<html>`, `\u003Chtml\u003E`}, |
| 1038 |
{`no = in attributes`, `no \u003D in attributes`}, |
| 1039 |
{`' does not become HTML entity`, `\u0026#x27; does not become HTML entity`}, |
| 1040 |
} |
| 1041 |
for _, tc := range testCases { |
| 1042 |
s := JSEscapeString(tc.in) |
| 1043 |
if s != tc.exp { |
| 1044 |
t.Errorf("JS escaping [%s] got [%s] want [%s]", tc.in, s, tc.exp) |
| 1045 |
} |
| 1046 |
} |
| 1047 |
} |
| 1048 |
|
| 1049 |
// A nice example: walk a binary tree. |
| 1050 |
|
| 1051 |
type Tree struct { |
| 1052 |
Val int |
| 1053 |
Left, Right *Tree |
| 1054 |
} |
| 1055 |
|
| 1056 |
// Use different delimiters to test Set.Delims. |
| 1057 |
// Also test the trimming of leading and trailing spaces. |
| 1058 |
const treeTemplate = ` |
| 1059 |
(- define "tree" -) |
| 1060 |
[ |
| 1061 |
(- .Val -) |
| 1062 |
(- with .Left -) |
| 1063 |
(template "tree" . -) |
| 1064 |
(- end -) |
| 1065 |
(- with .Right -) |
| 1066 |
(- template "tree" . -) |
| 1067 |
(- end -) |
| 1068 |
] |
| 1069 |
(- end -) |
| 1070 |
` |
| 1071 |
|
| 1072 |
func TestTree(t *testing.T) { |
| 1073 |
var tree = &Tree{ |
| 1074 |
1, |
| 1075 |
&Tree{ |
| 1076 |
2, &Tree{ |
| 1077 |
3, |
| 1078 |
&Tree{ |
| 1079 |
4, nil, nil, |
| 1080 |
}, |
| 1081 |
nil, |
| 1082 |
}, |
| 1083 |
&Tree{ |
| 1084 |
5, |
| 1085 |
&Tree{ |
| 1086 |
6, nil, nil, |
| 1087 |
}, |
| 1088 |
nil, |
| 1089 |
}, |
| 1090 |
}, |
| 1091 |
&Tree{ |
| 1092 |
7, |
| 1093 |
&Tree{ |
| 1094 |
8, |
| 1095 |
&Tree{ |
| 1096 |
9, nil, nil, |
| 1097 |
}, |
| 1098 |
nil, |
| 1099 |
}, |
| 1100 |
&Tree{ |
| 1101 |
10, |
| 1102 |
&Tree{ |
| 1103 |
11, nil, nil, |
| 1104 |
}, |
| 1105 |
nil, |
| 1106 |
}, |
| 1107 |
}, |
| 1108 |
} |
| 1109 |
tmpl, err := New("root").Delims("(", ")").Parse(treeTemplate) |
| 1110 |
if err != nil { |
| 1111 |
t.Fatal("parse error:", err) |
| 1112 |
} |
| 1113 |
var b strings.Builder |
| 1114 |
const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]" |
| 1115 |
// First by looking up the template. |
| 1116 |
err = tmpl.Lookup("tree").Execute(&b, tree) |
| 1117 |
if err != nil { |
| 1118 |
t.Fatal("exec error:", err) |
| 1119 |
} |
| 1120 |
result := b.String() |
| 1121 |
if result != expect { |
| 1122 |
t.Errorf("expected %q got %q", expect, result) |
| 1123 |
} |
| 1124 |
// Then direct to execution. |
| 1125 |
b.Reset() |
| 1126 |
err = tmpl.ExecuteTemplate(&b, "tree", tree) |
| 1127 |
if err != nil { |
| 1128 |
t.Fatal("exec error:", err) |
| 1129 |
} |
| 1130 |
result = b.String() |
| 1131 |
if result != expect { |
| 1132 |
t.Errorf("expected %q got %q", expect, result) |
| 1133 |
} |
| 1134 |
} |
| 1135 |
|
| 1136 |
func TestExecuteOnNewTemplate(t *testing.T) { |
| 1137 |
// This is issue 3872. |
| 1138 |
New("Name").Templates() |
| 1139 |
// This is issue 11379. |
| 1140 |
new(Template).Templates() |
| 1141 |
new(Template).Parse("") |
| 1142 |
new(Template).New("abc").Parse("") |
| 1143 |
new(Template).Execute(nil, nil) // returns an error (but does not crash) |
| 1144 |
new(Template).ExecuteTemplate(nil, "XXX", nil) // returns an error (but does not crash) |
| 1145 |
} |
| 1146 |
|
| 1147 |
const testTemplates = `{{define "one"}}one{{end}}{{define "two"}}two{{end}}` |
| 1148 |
|
| 1149 |
func TestMessageForExecuteEmpty(t *testing.T) { |
| 1150 |
// Test a truly empty template. |
| 1151 |
tmpl := New("empty") |
| 1152 |
var b bytes.Buffer |
| 1153 |
err := tmpl.Execute(&b, 0) |
| 1154 |
if err == nil { |
| 1155 |
t.Fatal("expected initial error") |
| 1156 |
} |
| 1157 |
got := err.Error() |
| 1158 |
want := `template: empty: "empty" is an incomplete or empty template` |
| 1159 |
if got != want { |
| 1160 |
t.Errorf("expected error %s got %s", want, got) |
| 1161 |
} |
| 1162 |
// Add a non-empty template to check that the error is helpful. |
| 1163 |
tests, err := New("").Parse(testTemplates) |
| 1164 |
if err != nil { |
| 1165 |
t.Fatal(err) |
| 1166 |
} |
| 1167 |
tmpl.AddParseTree("secondary", tests.Tree) |
| 1168 |
err = tmpl.Execute(&b, 0) |
| 1169 |
if err == nil { |
| 1170 |
t.Fatal("expected second error") |
| 1171 |
} |
| 1172 |
got = err.Error() |
| 1173 |
want = `template: empty: "empty" is an incomplete or empty template` |
| 1174 |
if got != want { |
| 1175 |
t.Errorf("expected error %s got %s", want, got) |
| 1176 |
} |
| 1177 |
// Make sure we can execute the secondary. |
| 1178 |
err = tmpl.ExecuteTemplate(&b, "secondary", 0) |
| 1179 |
if err != nil { |
| 1180 |
t.Fatal(err) |
| 1181 |
} |
| 1182 |
} |
| 1183 |
|
| 1184 |
func TestFinalForPrintf(t *testing.T) { |
| 1185 |
tmpl, err := New("").Parse(`{{"x" | printf}}`) |
| 1186 |
if err != nil { |
| 1187 |
t.Fatal(err) |
| 1188 |
} |
| 1189 |
var b bytes.Buffer |
| 1190 |
err = tmpl.Execute(&b, 0) |
| 1191 |
if err != nil { |
| 1192 |
t.Fatal(err) |
| 1193 |
} |
| 1194 |
} |
| 1195 |
|
| 1196 |
type cmpTest struct { |
| 1197 |
expr string |
| 1198 |
truth string |
| 1199 |
ok bool |
| 1200 |
} |
| 1201 |
|
| 1202 |
var cmpTests = []cmpTest{ |
| 1203 |
{"eq true true", "true", true}, |
| 1204 |
{"eq true false", "false", true}, |
| 1205 |
{"eq 1+2i 1+2i", "true", true}, |
| 1206 |
{"eq 1+2i 1+3i", "false", true}, |
| 1207 |
{"eq 1.5 1.5", "true", true}, |
| 1208 |
{"eq 1.5 2.5", "false", true}, |
| 1209 |
{"eq 1 1", "true", true}, |
| 1210 |
{"eq 1 2", "false", true}, |
| 1211 |
{"eq `xy` `xy`", "true", true}, |
| 1212 |
{"eq `xy` `xyz`", "false", true}, |
| 1213 |
{"eq .Uthree .Uthree", "true", true}, |
| 1214 |
{"eq .Uthree .Ufour", "false", true}, |
| 1215 |
{"eq 3 4 5 6 3", "true", true}, |
| 1216 |
{"eq 3 4 5 6 7", "false", true}, |
| 1217 |
{"ne true true", "false", true}, |
| 1218 |
{"ne true false", "true", true}, |
| 1219 |
{"ne 1+2i 1+2i", "false", true}, |
| 1220 |
{"ne 1+2i 1+3i", "true", true}, |
| 1221 |
{"ne 1.5 1.5", "false", true}, |
| 1222 |
{"ne 1.5 2.5", "true", true}, |
| 1223 |
{"ne 1 1", "false", true}, |
| 1224 |
{"ne 1 2", "true", true}, |
| 1225 |
{"ne `xy` `xy`", "false", true}, |
| 1226 |
{"ne `xy` `xyz`", "true", true}, |
| 1227 |
{"ne .Uthree .Uthree", "false", true}, |
| 1228 |
{"ne .Uthree .Ufour", "true", true}, |
| 1229 |
{"lt 1.5 1.5", "false", true}, |
| 1230 |
{"lt 1.5 2.5", "true", true}, |
| 1231 |
{"lt 1 1", "false", true}, |
| 1232 |
{"lt 1 2", "true", true}, |
| 1233 |
{"lt `xy` `xy`", "false", true}, |
| 1234 |
{"lt `xy` `xyz`", "true", true}, |
| 1235 |
{"lt .Uthree .Uthree", "false", true}, |
| 1236 |
{"lt .Uthree .Ufour", "true", true}, |
| 1237 |
{"le 1.5 1.5", "true", true}, |
| 1238 |
{"le 1.5 2.5", "true", true}, |
| 1239 |
{"le 2.5 1.5", "false", true}, |
| 1240 |
{"le 1 1", "true", true}, |
| 1241 |
{"le 1 2", "true", true}, |
| 1242 |
{"le 2 1", "false", true}, |
| 1243 |
{"le `xy` `xy`", "true", true}, |
| 1244 |
{"le `xy` `xyz`", "true", true}, |
| 1245 |
{"le `xyz` `xy`", "false", true}, |
| 1246 |
{"le .Uthree .Uthree", "true", true}, |
| 1247 |
{"le .Uthree .Ufour", "true", true}, |
| 1248 |
{"le .Ufour .Uthree", "false", true}, |
| 1249 |
{"gt 1.5 1.5", "false", true}, |
| 1250 |
{"gt 1.5 2.5", "false", true}, |
| 1251 |
{"gt 1 1", "false", true}, |
| 1252 |
{"gt 2 1", "true", true}, |
| 1253 |
{"gt 1 2", "false", true}, |
| 1254 |
{"gt `xy` `xy`", "false", true}, |
| 1255 |
{"gt `xy` `xyz`", "false", true}, |
| 1256 |
{"gt .Uthree .Uthree", "false", true}, |
| 1257 |
{"gt .Uthree .Ufour", "false", true}, |
| 1258 |
{"gt .Ufour .Uthree", "true", true}, |
| 1259 |
{"ge 1.5 1.5", "true", true}, |
| 1260 |
{"ge 1.5 2.5", "false", true}, |
| 1261 |
{"ge 2.5 1.5", "true", true}, |
| 1262 |
{"ge 1 1", "true", true}, |
| 1263 |
{"ge 1 2", "false", true}, |
| 1264 |
{"ge 2 1", "true", true}, |
| 1265 |
{"ge `xy` `xy`", "true", true}, |
| 1266 |
{"ge `xy` `xyz`", "false", true}, |
| 1267 |
{"ge `xyz` `xy`", "true", true}, |
| 1268 |
{"ge .Uthree .Uthree", "true", true}, |
| 1269 |
{"ge .Uthree .Ufour", "false", true}, |
| 1270 |
{"ge .Ufour .Uthree", "true", true}, |
| 1271 |
// Mixing signed and unsigned integers. |
| 1272 |
{"eq .Uthree .Three", "true", true}, |
| 1273 |
{"eq .Three .Uthree", "true", true}, |
| 1274 |
{"le .Uthree .Three", "true", true}, |
| 1275 |
{"le .Three .Uthree", "true", true}, |
| 1276 |
{"ge .Uthree .Three", "true", true}, |
| 1277 |
{"ge .Three .Uthree", "true", true}, |
| 1278 |
{"lt .Uthree .Three", "false", true}, |
| 1279 |
{"lt .Three .Uthree", "false", true}, |
| 1280 |
{"gt .Uthree .Three", "false", true}, |
| 1281 |
{"gt .Three .Uthree", "false", true}, |
| 1282 |
{"eq .Ufour .Three", "false", true}, |
| 1283 |
{"lt .Ufour .Three", "false", true}, |
| 1284 |
{"gt .Ufour .Three", "true", true}, |
| 1285 |
{"eq .NegOne .Uthree", "false", true}, |
| 1286 |
{"eq .Uthree .NegOne", "false", true}, |
| 1287 |
{"ne .NegOne .Uthree", "true", true}, |
| 1288 |
{"ne .Uthree .NegOne", "true", true}, |
| 1289 |
{"lt .NegOne .Uthree", "true", true}, |
| 1290 |
{"lt .Uthree .NegOne", "false", true}, |
| 1291 |
{"le .NegOne .Uthree", "true", true}, |
| 1292 |
{"le .Uthree .NegOne", "false", true}, |
| 1293 |
{"gt .NegOne .Uthree", "false", true}, |
| 1294 |
{"gt .Uthree .NegOne", "true", true}, |
| 1295 |
{"ge .NegOne .Uthree", "false", true}, |
| 1296 |
{"ge .Uthree .NegOne", "true", true}, |
| 1297 |
{"eq (index `x` 0) 'x'", "true", true}, // The example that triggered this rule. |
| 1298 |
{"eq (index `x` 0) 'y'", "false", true}, |
| 1299 |
{"eq .V1 .V2", "true", true}, |
| 1300 |
{"eq .Ptr .Ptr", "true", true}, |
| 1301 |
{"eq .Ptr .NilPtr", "false", true}, |
| 1302 |
{"eq .NilPtr .NilPtr", "true", true}, |
| 1303 |
{"eq .Iface1 .Iface1", "true", true}, |
| 1304 |
{"eq .Iface1 .NilIface", "false", true}, |
| 1305 |
{"eq .NilIface .NilIface", "true", true}, |
| 1306 |
{"eq .NilIface .Iface1", "false", true}, |
| 1307 |
{"eq .NilIface 0", "false", true}, |
| 1308 |
{"eq 0 .NilIface", "false", true}, |
| 1309 |
{"eq .Map .Map", "true", true}, // Uncomparable types but nil is OK. |
| 1310 |
{"eq .Map nil", "true", true}, // Uncomparable types but nil is OK. |
| 1311 |
{"eq nil .Map", "true", true}, // Uncomparable types but nil is OK. |
| 1312 |
{"eq .Map .NonNilMap", "false", true}, // Uncomparable types but nil is OK. |
| 1313 |
// Errors |
| 1314 |
{"eq `xy` 1", "", false}, // Different types. |
| 1315 |
{"eq 2 2.0", "", false}, // Different types. |
| 1316 |
{"lt true true", "", false}, // Unordered types. |
| 1317 |
{"lt 1+0i 1+0i", "", false}, // Unordered types. |
| 1318 |
{"eq .Ptr 1", "", false}, // Incompatible types. |
| 1319 |
{"eq .Ptr .NegOne", "", false}, // Incompatible types. |
| 1320 |
{"eq .Map .V1", "", false}, // Uncomparable types. |
| 1321 |
{"eq .NonNilMap .NonNilMap", "", false}, // Uncomparable types. |
| 1322 |
} |
| 1323 |
|
| 1324 |
func TestComparison(t *testing.T) { |
| 1325 |
b := new(strings.Builder) |
| 1326 |
var cmpStruct = struct { |
| 1327 |
Uthree, Ufour uint |
| 1328 |
NegOne, Three int |
| 1329 |
Ptr, NilPtr *int |
| 1330 |
NonNilMap map[int]int |
| 1331 |
Map map[int]int |
| 1332 |
V1, V2 V |
| 1333 |
Iface1, NilIface fmt.Stringer |
| 1334 |
}{ |
| 1335 |
Uthree: 3, |
| 1336 |
Ufour: 4, |
| 1337 |
NegOne: -1, |
| 1338 |
Three: 3, |
| 1339 |
Ptr: new(int), |
| 1340 |
NonNilMap: make(map[int]int), |
| 1341 |
Iface1: b, |
| 1342 |
} |
| 1343 |
for _, test := range cmpTests { |
| 1344 |
text := fmt.Sprintf("{{if %s}}true{{else}}false{{end}}", test.expr) |
| 1345 |
tmpl, err := New("empty").Parse(text) |
| 1346 |
if err != nil { |
| 1347 |
t.Fatalf("%q: %s", test.expr, err) |
| 1348 |
} |
| 1349 |
b.Reset() |
| 1350 |
err = tmpl.Execute(b, &cmpStruct) |
| 1351 |
if test.ok && err != nil { |
| 1352 |
t.Errorf("%s errored incorrectly: %s", test.expr, err) |
| 1353 |
continue |
| 1354 |
} |
| 1355 |
if !test.ok && err == nil { |
| 1356 |
t.Errorf("%s did not error", test.expr) |
| 1357 |
continue |
| 1358 |
} |
| 1359 |
if b.String() != test.truth { |
| 1360 |
t.Errorf("%s: want %s; got %s", test.expr, test.truth, b.String()) |
| 1361 |
} |
| 1362 |
} |
| 1363 |
} |
| 1364 |
|
| 1365 |
func TestMissingMapKey(t *testing.T) { |
| 1366 |
data := map[string]int{ |
| 1367 |
"x": 99, |
| 1368 |
} |
| 1369 |
tmpl, err := New("t1").Parse("{{.x}} {{.y}}") |
| 1370 |
if err != nil { |
| 1371 |
t.Fatal(err) |
| 1372 |
} |
| 1373 |
var b strings.Builder |
| 1374 |
// By default, just get "<no value>" |
| 1375 |
err = tmpl.Execute(&b, data) |
| 1376 |
if err != nil { |
| 1377 |
t.Fatal(err) |
| 1378 |
} |
| 1379 |
want := "99 <no value>" |
| 1380 |
got := b.String() |
| 1381 |
if got != want { |
| 1382 |
t.Errorf("got %q; expected %q", got, want) |
| 1383 |
} |
| 1384 |
// Same if we set the option explicitly to the default. |
| 1385 |
tmpl.Option("missingkey=default") |
| 1386 |
b.Reset() |
| 1387 |
err = tmpl.Execute(&b, data) |
| 1388 |
if err != nil { |
| 1389 |
t.Fatal("default:", err) |
| 1390 |
} |
| 1391 |
want = "99 <no value>" |
| 1392 |
got = b.String() |
| 1393 |
if got != want { |
| 1394 |
t.Errorf("got %q; expected %q", got, want) |
| 1395 |
} |
| 1396 |
// Next we ask for a zero value |
| 1397 |
tmpl.Option("missingkey=zero") |
| 1398 |
b.Reset() |
| 1399 |
err = tmpl.Execute(&b, data) |
| 1400 |
if err != nil { |
| 1401 |
t.Fatal("zero:", err) |
| 1402 |
} |
| 1403 |
want = "99 0" |
| 1404 |
got = b.String() |
| 1405 |
if got != want { |
| 1406 |
t.Errorf("got %q; expected %q", got, want) |
| 1407 |
} |
| 1408 |
// Now we ask for an error. |
| 1409 |
tmpl.Option("missingkey=error") |
| 1410 |
err = tmpl.Execute(&b, data) |
| 1411 |
if err == nil { |
| 1412 |
t.Errorf("expected error; got none") |
| 1413 |
} |
| 1414 |
// same Option, but now a nil interface: ask for an error |
| 1415 |
err = tmpl.Execute(&b, nil) |
| 1416 |
t.Log(err) |
| 1417 |
if err == nil { |
| 1418 |
t.Errorf("expected error for nil-interface; got none") |
| 1419 |
} |
| 1420 |
} |
| 1421 |
|
| 1422 |
// Test that the error message for multiline unterminated string |
| 1423 |
// refers to the line number of the opening quote. |
| 1424 |
func TestUnterminatedStringError(t *testing.T) { |
| 1425 |
_, err := New("X").Parse("hello\n\n{{`unterminated\n\n\n\n}}\n some more\n\n") |
| 1426 |
if err == nil { |
| 1427 |
t.Fatal("expected error") |
| 1428 |
} |
| 1429 |
str := err.Error() |
| 1430 |
if !strings.Contains(str, "X:3: unterminated raw quoted string") { |
| 1431 |
t.Fatalf("unexpected error: %s", str) |
| 1432 |
} |
| 1433 |
} |
| 1434 |
|
| 1435 |
const alwaysErrorText = "always be failing" |
| 1436 |
|
| 1437 |
var alwaysError = errors.New(alwaysErrorText) |
| 1438 |
|
| 1439 |
type ErrorWriter int |
| 1440 |
|
| 1441 |
func (e ErrorWriter) Write(p []byte) (int, error) { |
| 1442 |
return 0, alwaysError |
| 1443 |
} |
| 1444 |
|
| 1445 |
func TestExecuteGivesExecError(t *testing.T) { |
| 1446 |
// First, a non-execution error shouldn't be an ExecError. |
| 1447 |
tmpl, err := New("X").Parse("hello") |
| 1448 |
if err != nil { |
| 1449 |
t.Fatal(err) |
| 1450 |
} |
| 1451 |
err = tmpl.Execute(ErrorWriter(0), 0) |
| 1452 |
if err == nil { |
| 1453 |
t.Fatal("expected error; got none") |
| 1454 |
} |
| 1455 |
if err.Error() != alwaysErrorText { |
| 1456 |
t.Errorf("expected %q error; got %q", alwaysErrorText, err) |
| 1457 |
} |
| 1458 |
// This one should be an ExecError. |
| 1459 |
tmpl, err = New("X").Parse("hello, {{.X.Y}}") |
| 1460 |
if err != nil { |
| 1461 |
t.Fatal(err) |
| 1462 |
} |
| 1463 |
err = tmpl.Execute(io.Discard, 0) |
| 1464 |
if err == nil { |
| 1465 |
t.Fatal("expected error; got none") |
| 1466 |
} |
| 1467 |
eerr, ok := err.(ExecError) |
| 1468 |
if !ok { |
| 1469 |
t.Fatalf("did not expect ExecError %s", eerr) |
| 1470 |
} |
| 1471 |
expect := "field X in type int" |
| 1472 |
if !strings.Contains(err.Error(), expect) { |
| 1473 |
t.Errorf("expected %q; got %q", expect, err) |
| 1474 |
} |
| 1475 |
} |
| 1476 |
|
| 1477 |
func funcNameTestFunc() int { |
| 1478 |
return 0 |
| 1479 |
} |
| 1480 |
|
| 1481 |
func TestGoodFuncNames(t *testing.T) { |
| 1482 |
names := []string{ |
| 1483 |
"_", |
| 1484 |
"a", |
| 1485 |
"a1", |
| 1486 |
"a1", |
| 1487 |
"Ӵ", |
| 1488 |
} |
| 1489 |
for _, name := range names { |
| 1490 |
tmpl := New("X").Funcs( |
| 1491 |
FuncMap{ |
| 1492 |
name: funcNameTestFunc, |
| 1493 |
}, |
| 1494 |
) |
| 1495 |
if tmpl == nil { |
| 1496 |
t.Fatalf("nil result for %q", name) |
| 1497 |
} |
| 1498 |
} |
| 1499 |
} |
| 1500 |
|
| 1501 |
func TestBadFuncNames(t *testing.T) { |
| 1502 |
names := []string{ |
| 1503 |
"", |
| 1504 |
"2", |
| 1505 |
"a-b", |
| 1506 |
} |
| 1507 |
for _, name := range names { |
| 1508 |
testBadFuncName(name, t) |
| 1509 |
} |
| 1510 |
} |
| 1511 |
|
| 1512 |
func TestIsTrue(t *testing.T) { |
| 1513 |
var nil_ptr *int |
| 1514 |
var nil_chan chan int |
| 1515 |
tests := []struct { |
| 1516 |
v any |
| 1517 |
want bool |
| 1518 |
}{ |
| 1519 |
{1, true}, |
| 1520 |
{0, false}, |
| 1521 |
{uint8(1), true}, |
| 1522 |
{uint8(0), false}, |
| 1523 |
{float64(1.0), true}, |
| 1524 |
{float64(0.0), false}, |
| 1525 |
{complex64(1.0), true}, |
| 1526 |
{complex64(0.0), false}, |
| 1527 |
{true, true}, |
| 1528 |
{false, false}, |
| 1529 |
{[2]int{1, 2}, true}, |
| 1530 |
{[0]int{}, false}, |
| 1531 |
{[]byte("abc"), true}, |
| 1532 |
{[]byte(""), false}, |
| 1533 |
{map[string]int{"a": 1, "b": 2}, true}, |
| 1534 |
{map[string]int{}, false}, |
| 1535 |
{make(chan int), true}, |
| 1536 |
{nil_chan, false}, |
| 1537 |
{new(int), true}, |
| 1538 |
{nil_ptr, false}, |
| 1539 |
{unsafe.Pointer(new(int)), true}, |
| 1540 |
{unsafe.Pointer(nil_ptr), false}, |
| 1541 |
} |
| 1542 |
for _, test_case := range tests { |
| 1543 |
got, _ := IsTrue(test_case.v) |
| 1544 |
if got != test_case.want { |
| 1545 |
t.Fatalf("expect result %v, got %v", test_case.want, got) |
| 1546 |
} |
| 1547 |
} |
| 1548 |
} |
| 1549 |
|
| 1550 |
func testBadFuncName(name string, t *testing.T) { |
| 1551 |
t.Helper() |
| 1552 |
defer func() { |
| 1553 |
recover() |
| 1554 |
}() |
| 1555 |
New("X").Funcs( |
| 1556 |
FuncMap{ |
| 1557 |
name: funcNameTestFunc, |
| 1558 |
}, |
| 1559 |
) |
| 1560 |
// If we get here, the name did not cause a panic, which is how Funcs |
| 1561 |
// reports an error. |
| 1562 |
t.Errorf("%q succeeded incorrectly as function name", name) |
| 1563 |
} |
| 1564 |
|
| 1565 |
func TestBlock(t *testing.T) { |
| 1566 |
const ( |
| 1567 |
input = `a({{block "inner" .}}bar({{.}})baz{{end}})b` |
| 1568 |
want = `a(bar(hello)baz)b` |
| 1569 |
overlay = `{{define "inner"}}foo({{.}})bar{{end}}` |
| 1570 |
want2 = `a(foo(goodbye)bar)b` |
| 1571 |
) |
| 1572 |
tmpl, err := New("outer").Parse(input) |
| 1573 |
if err != nil { |
| 1574 |
t.Fatal(err) |
| 1575 |
} |
| 1576 |
tmpl2, err := Must(tmpl.Clone()).Parse(overlay) |
| 1577 |
if err != nil { |
| 1578 |
t.Fatal(err) |
| 1579 |
} |
| 1580 |
|
| 1581 |
var buf strings.Builder |
| 1582 |
if err := tmpl.Execute(&buf, "hello"); err != nil { |
| 1583 |
t.Fatal(err) |
| 1584 |
} |
| 1585 |
if got := buf.String(); got != want { |
| 1586 |
t.Errorf("got %q, want %q", got, want) |
| 1587 |
} |
| 1588 |
|
| 1589 |
buf.Reset() |
| 1590 |
if err := tmpl2.Execute(&buf, "goodbye"); err != nil { |
| 1591 |
t.Fatal(err) |
| 1592 |
} |
| 1593 |
if got := buf.String(); got != want2 { |
| 1594 |
t.Errorf("got %q, want %q", got, want2) |
| 1595 |
} |
| 1596 |
} |
| 1597 |
|
| 1598 |
func TestEvalFieldErrors(t *testing.T) { |
| 1599 |
tests := []struct { |
| 1600 |
name, src string |
| 1601 |
value any |
| 1602 |
want string |
| 1603 |
}{ |
| 1604 |
{ |
| 1605 |
// Check that calling an invalid field on nil pointer |
| 1606 |
// prints a field error instead of a distracting nil |
| 1607 |
// pointer error. https://golang.org/issue/15125 |
| 1608 |
"MissingFieldOnNil", |
| 1609 |
"{{.MissingField}}", |
| 1610 |
(*T)(nil), |
| 1611 |
"can't evaluate field MissingField in type *template.T", |
| 1612 |
}, |
| 1613 |
{ |
| 1614 |
"MissingFieldOnNonNil", |
| 1615 |
"{{.MissingField}}", |
| 1616 |
&T{}, |
| 1617 |
"can't evaluate field MissingField in type *template.T", |
| 1618 |
}, |
| 1619 |
{ |
| 1620 |
"ExistingFieldOnNil", |
| 1621 |
"{{.X}}", |
| 1622 |
(*T)(nil), |
| 1623 |
"nil pointer evaluating *template.T.X", |
| 1624 |
}, |
| 1625 |
{ |
| 1626 |
"MissingKeyOnNilMap", |
| 1627 |
"{{.MissingKey}}", |
| 1628 |
(*map[string]string)(nil), |
| 1629 |
"nil pointer evaluating *map[string]string.MissingKey", |
| 1630 |
}, |
| 1631 |
{ |
| 1632 |
"MissingKeyOnNilMapPtr", |
| 1633 |
"{{.MissingKey}}", |
| 1634 |
(*map[string]string)(nil), |
| 1635 |
"nil pointer evaluating *map[string]string.MissingKey", |
| 1636 |
}, |
| 1637 |
{ |
| 1638 |
"MissingKeyOnMapPtrToNil", |
| 1639 |
"{{.MissingKey}}", |
| 1640 |
&map[string]string{}, |
| 1641 |
"<nil>", |
| 1642 |
}, |
| 1643 |
} |
| 1644 |
for _, tc := range tests { |
| 1645 |
t.Run(tc.name, func(t *testing.T) { |
| 1646 |
tmpl := Must(New("tmpl").Parse(tc.src)) |
| 1647 |
err := tmpl.Execute(io.Discard, tc.value) |
| 1648 |
got := "<nil>" |
| 1649 |
if err != nil { |
| 1650 |
got = err.Error() |
| 1651 |
} |
| 1652 |
if !strings.HasSuffix(got, tc.want) { |
| 1653 |
t.Fatalf("got error %q, want %q", got, tc.want) |
| 1654 |
} |
| 1655 |
}) |
| 1656 |
} |
| 1657 |
} |
| 1658 |
|
| 1659 |
func TestMaxExecDepth(t *testing.T) { |
| 1660 |
if testing.Short() { |
| 1661 |
t.Skip("skipping in -short mode") |
| 1662 |
} |
| 1663 |
tmpl := Must(New("tmpl").Parse(`{{template "tmpl" .}}`)) |
| 1664 |
err := tmpl.Execute(io.Discard, nil) |
| 1665 |
got := "<nil>" |
| 1666 |
if err != nil { |
| 1667 |
got = err.Error() |
| 1668 |
} |
| 1669 |
const want = "exceeded maximum template depth" |
| 1670 |
if !strings.Contains(got, want) { |
| 1671 |
t.Errorf("got error %q; want %q", got, want) |
| 1672 |
} |
| 1673 |
} |
| 1674 |
|
| 1675 |
func TestAddrOfIndex(t *testing.T) { |
| 1676 |
// golang.org/issue/14916. |
| 1677 |
// Before index worked on reflect.Values, the .String could not be |
| 1678 |
// found on the (incorrectly unaddressable) V value, |
| 1679 |
// in contrast to range, which worked fine. |
| 1680 |
// Also testing that passing a reflect.Value to tmpl.Execute works. |
| 1681 |
texts := []string{ |
| 1682 |
`{{range .}}{{.String}}{{end}}`, |
| 1683 |
`{{with index . 0}}{{.String}}{{end}}`, |
| 1684 |
} |
| 1685 |
for _, text := range texts { |
| 1686 |
tmpl := Must(New("tmpl").Parse(text)) |
| 1687 |
var buf strings.Builder |
| 1688 |
err := tmpl.Execute(&buf, reflect.ValueOf([]V{{1}})) |
| 1689 |
if err != nil { |
| 1690 |
t.Fatalf("%s: Execute: %v", text, err) |
| 1691 |
} |
| 1692 |
if buf.String() != "<1>" { |
| 1693 |
t.Fatalf("%s: template output = %q, want %q", text, &buf, "<1>") |
| 1694 |
} |
| 1695 |
} |
| 1696 |
} |
| 1697 |
|
| 1698 |
func TestInterfaceValues(t *testing.T) { |
| 1699 |
// golang.org/issue/17714. |
| 1700 |
// Before index worked on reflect.Values, interface values |
| 1701 |
// were always implicitly promoted to the underlying value, |
| 1702 |
// except that nil interfaces were promoted to the zero reflect.Value. |
| 1703 |
// Eliminating a round trip to interface{} and back to reflect.Value |
| 1704 |
// eliminated this promotion, breaking these cases. |
| 1705 |
tests := []struct { |
| 1706 |
text string |
| 1707 |
out string |
| 1708 |
}{ |
| 1709 |
{`{{index .Nil 1}}`, "ERROR: index of untyped nil"}, |
| 1710 |
{`{{index .Slice 2}}`, "2"}, |
| 1711 |
{`{{index .Slice .Two}}`, "2"}, |
| 1712 |
{`{{call .Nil 1}}`, "ERROR: call of nil"}, |
| 1713 |
{`{{call .PlusOne 1}}`, "2"}, |
| 1714 |
{`{{call .PlusOne .One}}`, "2"}, |
| 1715 |
{`{{and (index .Slice 0) true}}`, "0"}, |
| 1716 |
{`{{and .Zero true}}`, "0"}, |
| 1717 |
{`{{and (index .Slice 1) false}}`, "false"}, |
| 1718 |
{`{{and .One false}}`, "false"}, |
| 1719 |
{`{{or (index .Slice 0) false}}`, "false"}, |
| 1720 |
{`{{or .Zero false}}`, "false"}, |
| 1721 |
{`{{or (index .Slice 1) true}}`, "1"}, |
| 1722 |
{`{{or .One true}}`, "1"}, |
| 1723 |
{`{{not (index .Slice 0)}}`, "true"}, |
| 1724 |
{`{{not .Zero}}`, "true"}, |
| 1725 |
{`{{not (index .Slice 1)}}`, "false"}, |
| 1726 |
{`{{not .One}}`, "false"}, |
| 1727 |
{`{{eq (index .Slice 0) .Zero}}`, "true"}, |
| 1728 |
{`{{eq (index .Slice 1) .One}}`, "true"}, |
| 1729 |
{`{{ne (index .Slice 0) .Zero}}`, "false"}, |
| 1730 |
{`{{ne (index .Slice 1) .One}}`, "false"}, |
| 1731 |
{`{{ge (index .Slice 0) .One}}`, "false"}, |
| 1732 |
{`{{ge (index .Slice 1) .Zero}}`, "true"}, |
| 1733 |
{`{{gt (index .Slice 0) .One}}`, "false"}, |
| 1734 |
{`{{gt (index .Slice 1) .Zero}}`, "true"}, |
| 1735 |
{`{{le (index .Slice 0) .One}}`, "true"}, |
| 1736 |
{`{{le (index .Slice 1) .Zero}}`, "false"}, |
| 1737 |
{`{{lt (index .Slice 0) .One}}`, "true"}, |
| 1738 |
{`{{lt (index .Slice 1) .Zero}}`, "false"}, |
| 1739 |
} |
| 1740 |
|
| 1741 |
for _, tt := range tests { |
| 1742 |
tmpl := Must(New("tmpl").Parse(tt.text)) |
| 1743 |
var buf strings.Builder |
| 1744 |
err := tmpl.Execute(&buf, map[string]any{ |
| 1745 |
"PlusOne": func(n int) int { |
| 1746 |
return n + 1 |
| 1747 |
}, |
| 1748 |
"Slice": []int{0, 1, 2, 3}, |
| 1749 |
"One": 1, |
| 1750 |
"Two": 2, |
| 1751 |
"Nil": nil, |
| 1752 |
"Zero": 0, |
| 1753 |
}) |
| 1754 |
if strings.HasPrefix(tt.out, "ERROR:") { |
| 1755 |
e := strings.TrimSpace(strings.TrimPrefix(tt.out, "ERROR:")) |
| 1756 |
if err == nil || !strings.Contains(err.Error(), e) { |
| 1757 |
t.Errorf("%s: Execute: %v, want error %q", tt.text, err, e) |
| 1758 |
} |
| 1759 |
continue |
| 1760 |
} |
| 1761 |
if err != nil { |
| 1762 |
t.Errorf("%s: Execute: %v", tt.text, err) |
| 1763 |
continue |
| 1764 |
} |
| 1765 |
if buf.String() != tt.out { |
| 1766 |
t.Errorf("%s: template output = %q, want %q", tt.text, &buf, tt.out) |
| 1767 |
} |
| 1768 |
} |
| 1769 |
} |
| 1770 |
|
| 1771 |
// Check that panics during calls are recovered and returned as errors. |
| 1772 |
func TestExecutePanicDuringCall(t *testing.T) { |
| 1773 |
funcs := map[string]any{ |
| 1774 |
"doPanic": func() string { |
| 1775 |
panic("custom panic string") |
| 1776 |
}, |
| 1777 |
} |
| 1778 |
tests := []struct { |
| 1779 |
name string |
| 1780 |
input string |
| 1781 |
data any |
| 1782 |
wantErr string |
| 1783 |
}{ |
| 1784 |
{ |
| 1785 |
"direct func call panics", |
| 1786 |
"{{doPanic}}", (*T)(nil), |
| 1787 |
`template: t:1:2: executing "t" at <doPanic>: error calling doPanic: custom panic string`, |
| 1788 |
}, |
| 1789 |
{ |
| 1790 |
"indirect func call panics", |
| 1791 |
"{{call doPanic}}", (*T)(nil), |
| 1792 |
`template: t:1:7: executing "t" at <doPanic>: error calling doPanic: custom panic string`, |
| 1793 |
}, |
| 1794 |
{ |
| 1795 |
"direct method call panics", |
| 1796 |
"{{.GetU}}", (*T)(nil), |
| 1797 |
`template: t:1:2: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`, |
| 1798 |
}, |
| 1799 |
{ |
| 1800 |
"indirect method call panics", |
| 1801 |
"{{call .GetU}}", (*T)(nil), |
| 1802 |
`template: t:1:7: executing "t" at <.GetU>: error calling GetU: runtime error: invalid memory address or nil pointer dereference`, |
| 1803 |
}, |
| 1804 |
{ |
| 1805 |
"func field call panics", |
| 1806 |
"{{call .PanicFunc}}", tVal, |
| 1807 |
`template: t:1:2: executing "t" at <call .PanicFunc>: error calling call: test panic`, |
| 1808 |
}, |
| 1809 |
{ |
| 1810 |
"method call on nil interface", |
| 1811 |
"{{.NonEmptyInterfaceNil.Method0}}", tVal, |
| 1812 |
`template: t:1:23: executing "t" at <.NonEmptyInterfaceNil.Method0>: nil pointer evaluating template.I.Method0`, |
| 1813 |
}, |
| 1814 |
} |
| 1815 |
for _, tc := range tests { |
| 1816 |
b := new(bytes.Buffer) |
| 1817 |
tmpl, err := New("t").Funcs(funcs).Parse(tc.input) |
| 1818 |
if err != nil { |
| 1819 |
t.Fatalf("parse error: %s", err) |
| 1820 |
} |
| 1821 |
err = tmpl.Execute(b, tc.data) |
| 1822 |
if err == nil { |
| 1823 |
t.Errorf("%s: expected error; got none", tc.name) |
| 1824 |
} else if !strings.Contains(err.Error(), tc.wantErr) { |
| 1825 |
if *debug { |
| 1826 |
fmt.Printf("%s: test execute error: %s\n", tc.name, err) |
| 1827 |
} |
| 1828 |
t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err) |
| 1829 |
} |
| 1830 |
} |
| 1831 |
} |
| 1832 |
|
| 1833 |
func TestFunctionCheckDuringCall(t *testing.T) { |
| 1834 |
tests := []struct { |
| 1835 |
name string |
| 1836 |
input string |
| 1837 |
data any |
| 1838 |
wantErr string |
| 1839 |
}{{ |
| 1840 |
name: "call nothing", |
| 1841 |
input: `{{call}}`, |
| 1842 |
data: tVal, |
| 1843 |
wantErr: "wrong number of args for call: want at least 1 got 0", |
| 1844 |
}, |
| 1845 |
{ |
| 1846 |
name: "call non-function", |
| 1847 |
input: "{{call .True}}", |
| 1848 |
data: tVal, |
| 1849 |
wantErr: "error calling call: non-function .True of type bool", |
| 1850 |
}, |
| 1851 |
{ |
| 1852 |
name: "call func with wrong argument", |
| 1853 |
input: "{{call .BinaryFunc 1}}", |
| 1854 |
data: tVal, |
| 1855 |
wantErr: "error calling call: wrong number of args for .BinaryFunc: got 1 want 2", |
| 1856 |
}, |
| 1857 |
{ |
| 1858 |
name: "call variadic func with wrong argument", |
| 1859 |
input: `{{call .VariadicFuncInt}}`, |
| 1860 |
data: tVal, |
| 1861 |
wantErr: "error calling call: wrong number of args for .VariadicFuncInt: got 0 want at least 1", |
| 1862 |
}, |
| 1863 |
{ |
| 1864 |
name: "call too few return number func", |
| 1865 |
input: `{{call .TooFewReturnCountFunc}}`, |
| 1866 |
data: tVal, |
| 1867 |
wantErr: "error calling call: function .TooFewReturnCountFunc has 0 return values; should be 1 or 2", |
| 1868 |
}, |
| 1869 |
{ |
| 1870 |
name: "call too many return number func", |
| 1871 |
input: `{{call .TooManyReturnCountFunc}}`, |
| 1872 |
data: tVal, |
| 1873 |
wantErr: "error calling call: function .TooManyReturnCountFunc has 3 return values; should be 1 or 2", |
| 1874 |
}, |
| 1875 |
{ |
| 1876 |
name: "call invalid return type func", |
| 1877 |
input: `{{call .InvalidReturnTypeFunc}}`, |
| 1878 |
data: tVal, |
| 1879 |
wantErr: "error calling call: invalid function signature for .InvalidReturnTypeFunc: second return value should be error; is bool", |
| 1880 |
}, |
| 1881 |
{ |
| 1882 |
name: "call pipeline", |
| 1883 |
input: `{{call (len "test")}}`, |
| 1884 |
data: nil, |
| 1885 |
wantErr: "error calling call: non-function len \"test\" of type int", |
| 1886 |
}, |
| 1887 |
} |
| 1888 |
|
| 1889 |
for _, tc := range tests { |
| 1890 |
b := new(bytes.Buffer) |
| 1891 |
tmpl, err := New("t").Parse(tc.input) |
| 1892 |
if err != nil { |
| 1893 |
t.Fatalf("parse error: %s", err) |
| 1894 |
} |
| 1895 |
err = tmpl.Execute(b, tc.data) |
| 1896 |
if err == nil { |
| 1897 |
t.Errorf("%s: expected error; got none", tc.name) |
| 1898 |
} else if tc.wantErr == "" || !strings.Contains(err.Error(), tc.wantErr) { |
| 1899 |
if *debug { |
| 1900 |
fmt.Printf("%s: test execute error: %s\n", tc.name, err) |
| 1901 |
} |
| 1902 |
t.Errorf("%s: expected error:\n%s\ngot:\n%s", tc.name, tc.wantErr, err) |
| 1903 |
} |
| 1904 |
} |
| 1905 |
} |
| 1906 |
|
| 1907 |
// Issue 31810. Check that a parenthesized first argument behaves properly. |
| 1908 |
func TestIssue31810(t *testing.T) { |
| 1909 |
// A simple value with no arguments is fine. |
| 1910 |
var b strings.Builder |
| 1911 |
const text = "{{ (.) }}" |
| 1912 |
tmpl, err := New("").Parse(text) |
| 1913 |
if err != nil { |
| 1914 |
t.Error(err) |
| 1915 |
} |
| 1916 |
err = tmpl.Execute(&b, "result") |
| 1917 |
if err != nil { |
| 1918 |
t.Error(err) |
| 1919 |
} |
| 1920 |
if b.String() != "result" { |
| 1921 |
t.Errorf("%s got %q, expected %q", text, b.String(), "result") |
| 1922 |
} |
| 1923 |
|
| 1924 |
// Even a plain function fails - need to use call. |
| 1925 |
f := func() string { return "result" } |
| 1926 |
b.Reset() |
| 1927 |
err = tmpl.Execute(&b, f) |
| 1928 |
if err == nil { |
| 1929 |
t.Error("expected error with no call, got none") |
| 1930 |
} |
| 1931 |
|
| 1932 |
// Works if the function is explicitly called. |
| 1933 |
const textCall = "{{ (call .) }}" |
| 1934 |
tmpl, err = New("").Parse(textCall) |
| 1935 |
b.Reset() |
| 1936 |
err = tmpl.Execute(&b, f) |
| 1937 |
if err != nil { |
| 1938 |
t.Error(err) |
| 1939 |
} |
| 1940 |
if b.String() != "result" { |
| 1941 |
t.Errorf("%s got %q, expected %q", textCall, b.String(), "result") |
| 1942 |
} |
| 1943 |
} |
| 1944 |
|
| 1945 |
// Issue 43065, range over send only channel |
| 1946 |
func TestIssue43065(t *testing.T) { |
| 1947 |
var b bytes.Buffer |
| 1948 |
tmp := Must(New("").Parse(`{{range .}}{{end}}`)) |
| 1949 |
ch := make(chan<- int) |
| 1950 |
err := tmp.Execute(&b, ch) |
| 1951 |
if err == nil { |
| 1952 |
t.Error("expected err got nil") |
| 1953 |
} else if !strings.Contains(err.Error(), "range over send-only channel") { |
| 1954 |
t.Errorf("%s", err) |
| 1955 |
} |
| 1956 |
} |
| 1957 |
|
| 1958 |
// Issue 39807: data race in html/template & text/template |
| 1959 |
func TestIssue39807(t *testing.T) { |
| 1960 |
var wg sync.WaitGroup |
| 1961 |
|
| 1962 |
tplFoo, err := New("foo").Parse(`{{ template "bar" . }}`) |
| 1963 |
if err != nil { |
| 1964 |
t.Error(err) |
| 1965 |
} |
| 1966 |
|
| 1967 |
tplBar, err := New("bar").Parse("bar") |
| 1968 |
if err != nil { |
| 1969 |
t.Error(err) |
| 1970 |
} |
| 1971 |
|
| 1972 |
gofuncs := 10 |
| 1973 |
numTemplates := 10 |
| 1974 |
|
| 1975 |
for i := 1; i <= gofuncs; i++ { |
| 1976 |
wg.Add(1) |
| 1977 |
go func() { |
| 1978 |
defer wg.Done() |
| 1979 |
for j := 0; j < numTemplates; j++ { |
| 1980 |
_, err := tplFoo.AddParseTree(tplBar.Name(), tplBar.Tree) |
| 1981 |
if err != nil { |
| 1982 |
t.Error(err) |
| 1983 |
} |
| 1984 |
err = tplFoo.Execute(io.Discard, nil) |
| 1985 |
if err != nil { |
| 1986 |
t.Error(err) |
| 1987 |
} |
| 1988 |
} |
| 1989 |
}() |
| 1990 |
} |
| 1991 |
|
| 1992 |
wg.Wait() |
| 1993 |
} |
| 1994 |
|
| 1995 |
// Issue 48215: embedded nil pointer causes panic. |
| 1996 |
// Fixed by adding FieldByIndexErr to the reflect package. |
| 1997 |
func TestIssue48215(t *testing.T) { |
| 1998 |
type A struct { |
| 1999 |
S string |
| 2000 |
} |
| 2001 |
type B struct { |
| 2002 |
*A |
| 2003 |
} |
| 2004 |
tmpl, err := New("").Parse(`{{ .S }}`) |
| 2005 |
if err != nil { |
| 2006 |
t.Fatal(err) |
| 2007 |
} |
| 2008 |
err = tmpl.Execute(io.Discard, B{}) |
| 2009 |
// We expect an error, not a panic. |
| 2010 |
if err == nil { |
| 2011 |
t.Fatal("did not get error for nil embedded struct") |
| 2012 |
} |
| 2013 |
if !strings.Contains(err.Error(), "reflect: indirection through nil pointer to embedded struct field A") { |
| 2014 |
t.Fatal(err) |
| 2015 |
} |
| 2016 |
} |