package templtest import ( _ "embed" "errors" "regexp" "strings" "testing" "git.buddy.wtf/lib/tmpl" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" ) //go:embed expect/index-simple.html var expectdIndexHTML string func TestHTML(t *testing.T) { type testcase struct { Name string tmpl.Templates Expected string Template string Data interface{} Err bool } tt := []testcase{ { Name: "get template by name", Expected: expectdIndexHTML, Template: "index", Data: "test", Templates: tmpl.Templates{ FS: data, Root: "data", Suffix: "html.tmpl", Funcs: map[string]interface{}{ "upper": strings.ToUpper, }, }, }, { Name: "error on invalid template", Err: true, Template: "borked", Templates: tmpl.Templates{FS: data, Suffix: "invalid"}, }, { Name: "error calling invalid template", Template: "borked", Templates: tmpl.Templates{ FS: data, Suffix: "template", Funcs: map[string]interface{}{ "return_error": func() (string, error) { return "invalid", errors.New("error running template") }, }, }, }, } for _, tc := range tt { tc := tc t.Run(tc.Name, func(t *testing.T) { t.Parallel() a := assert.New(t) template, err := tc.Templates.HTML(tc.Template) if tc.Err { a.Error(err) return } else { a.NoError(err) } actual := tmpl.String(template, tc.Data) a.Empty(cmp.Diff(singlespace(actual), singlespace(tc.Expected))) }) } } var spacesRegex = regexp.MustCompile(`\s+`) func singlespace(in string) string { return strings.Join(spacesRegex.Split(in, -1), " ") }