diff --git a/template/template.go b/template/template.go index 71bc486e1..91ff9d5eb 100644 --- a/template/template.go +++ b/template/template.go @@ -265,8 +265,7 @@ func (te Expander) Expand() (result string, resultErr error) { } }() - tmpl, err := text_template.New(te.name).Funcs(te.funcMap).Parse(te.text) - tmpl.Option("missingkey=zero") + tmpl, err := text_template.New(te.name).Funcs(te.funcMap).Option("missingkey=zero").Parse(te.text) if err != nil { return "", fmt.Errorf("error parsing template %v: %v", te.name, err) } diff --git a/template/template_test.go b/template/template_test.go index 6a2b81d1a..5b9069879 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -31,6 +31,7 @@ type testTemplatesScenario struct { queryResult promql.Vector shouldFail bool html bool + errorMsg string } func TestTemplateExpansion(t *testing.T) { @@ -45,6 +46,12 @@ func TestTemplateExpansion(t *testing.T) { text: "{{ 1 }}", output: "1", }, + { + // Non-ASCII space (not allowed in text/template, see https://github.com/golang/go/blob/master/src/text/template/parse/lex.go#L98) + text: "{{ }}", + shouldFail: true, + errorMsg: "error parsing template test: template: test:1: unexpected unrecognized character in action: U+00A0 in command", + }, { // HTML escaping. text: "{{ \"\" }}", @@ -140,18 +147,21 @@ func TestTemplateExpansion(t *testing.T) { // Unparsable template. text: "{{", shouldFail: true, + errorMsg: "error parsing template test: template: test:1: unexpected unclosed action in command", }, { // Error in function. text: "{{ query \"missing\" | first }}", queryResult: promql.Vector{}, shouldFail: true, + errorMsg: "error executing template test: template: test:1:21: executing \"test\" at : error calling first: first() called on vector with no elements", }, { // Panic. text: "{{ (query \"missing\").banana }}", queryResult: promql.Vector{}, shouldFail: true, + errorMsg: "error executing template test: template: test:1:10: executing \"test\" at <\"missing\">: can't evaluate field banana in type template.queryResult", }, { // Regex replacement. @@ -262,6 +272,9 @@ func TestTemplateExpansion(t *testing.T) { if err == nil { t.Fatalf("%d. Error not returned from %v", i, s.text) } + if err.Error() != s.errorMsg { + t.Fatalf("%d. Error message returned is wrong:\n returned: %v\n expected: %v", i, err.Error(), s.errorMsg) + } continue } if err != nil {