// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "bytes" "template" "testing" ) type data struct { F, T bool C, G, H string A, E []string } var testData = data{ F: false, T: true, C: "", G: "", H: "", A: []string{"", ""}, E: []string{}, } type testCase struct { name string input string output string } var testCases = []testCase{ {"if", "{{if .T}}Hello{{end}}, {{.C}}!", "Hello, <Cincinatti>!"}, {"else", "{{if .F}}{{.H}}{{else}}{{.G}}{{end}}!", "<Goodbye>!"}, {"overescaping", "Hello, {{.C | html}}!", "Hello, <Cincinatti>!"}, {"assignment", "{{if $x := .H}}{{$x}}{{end}}", "<Hello>"}, {"withBody", "{{with .H}}{{.}}{{end}}", "<Hello>"}, {"withElse", "{{with .E}}{{.}}{{else}}{{.H}}{{end}}", "<Hello>"}, {"rangeBody", "{{range .A}}{{.}}{{end}}", "<a><b>"}, {"rangeElse", "{{range .E}}{{.}}{{else}}{{.H}}{{end}}", "<Hello>"}, {"nonStringValue", "{{.T}}", "true"}, {"constant", ``, ``}, } func TestAutoesc(t *testing.T) { for _, testCase := range testCases { name := testCase.name tmpl := template.New(name) tmpl, err := tmpl.Parse(testCase.input) if err != nil { t.Errorf("%s: failed to parse template: %s", name, err) continue } Escape(tmpl) buffer := new(bytes.Buffer) err = tmpl.Execute(buffer, testData) if err != nil { t.Errorf("%s: template execution failed: %s", name, err) continue } output := testCase.output actual := buffer.String() if output != actual { t.Errorf("%s: escaped output: %q != %q", name, output, actual) } } }