...
1
16
17 package util
18
19 import (
20 "testing"
21 )
22
23 const (
24 validTmpl = "image: {{ .ImageRepository }}/pause:3.9"
25 validTmplOut = "image: registry.k8s.io/pause:3.9"
26 doNothing = "image: registry.k8s.io/pause:3.9"
27 invalidTmpl1 = "{{ .baz }/d}"
28 invalidTmpl2 = "{{ !foobar }}"
29 )
30
31 func TestParseTemplate(t *testing.T) {
32 var tmplTests = []struct {
33 name string
34 template string
35 data interface{}
36 output string
37 errExpected bool
38 }{
39 {
40 name: "should parse a valid template and set the right values",
41 template: validTmpl,
42 data: struct{ ImageRepository, Arch string }{
43 ImageRepository: "registry.k8s.io",
44 Arch: "amd64",
45 },
46 output: validTmplOut,
47 errExpected: false,
48 },
49 {
50 name: "should noop if there aren't any {{ .foo }} present",
51 template: doNothing,
52 data: struct{ ImageRepository, Arch string }{
53 ImageRepository: "registry.k8s.io",
54 Arch: "amd64",
55 },
56 output: doNothing,
57 errExpected: false,
58 },
59 {
60 name: "invalid syntax, passing nil",
61 template: invalidTmpl1,
62 data: nil,
63 output: "",
64 errExpected: true,
65 },
66 {
67 name: "invalid syntax",
68 template: invalidTmpl2,
69 data: struct{}{},
70 output: "",
71 errExpected: true,
72 },
73 }
74 for _, tt := range tmplTests {
75 t.Run(tt.name, func(t *testing.T) {
76 outbytes, err := ParseTemplate(tt.template, tt.data)
77 if tt.errExpected != (err != nil) {
78 t.Errorf(
79 "failed TestParseTemplate:\n\texpected err: %t\n\t actual: %s",
80 tt.errExpected,
81 err,
82 )
83 }
84 if tt.output != string(outbytes) {
85 t.Errorf(
86 "failed TestParseTemplate:\n\texpected bytes: %s\n\t actual: %s",
87 tt.output,
88 outbytes,
89 )
90 }
91 })
92 }
93 }
94
View as plain text