-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmpl_test.go
93 lines (78 loc) · 1.78 KB
/
tmpl_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package tmpl_test
import (
"bytes"
"embed"
"flag"
"io/fs"
"os"
"path/filepath"
"testing"
"github.com/pnelson/tmpl"
)
var update = flag.Bool("update", false, "update .golden files")
//go:embed testdata
var embedFS embed.FS
// extFS is a fs.FS implementation that appends a common extension.
type extFS struct {
fs fs.FS
ext string
}
// Open implements the fs.FS interface.
func (f extFS) Open(name string) (fs.File, error) {
return f.fs.Open(name + f.ext)
}
func TestGolden(t *testing.T) {
var tt = map[string]tmpl.Viewable{
"basic.html": basic{Title: "test"},
"layout.html": index{layout: layout{Title: "test"}},
"nested.html": nested{layout: layout{Title: "test"}},
}
testdata, err := fs.Sub(embedFS, "testdata")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
templates := tmpl.New(extFS{testdata, ".html"})
for filename, view := range tt {
compare(t, templates, filename, view)
}
}
func compare(t *testing.T, set *tmpl.Template, filename string, view tmpl.Viewable) {
buf := bytes.NewBuffer(make([]byte, 0))
err := set.Render(buf, view)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
have := buf.Bytes()
golden := filepath.Join("testdata", "golden", filename)
if *update {
os.WriteFile(golden, have, 0644)
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !bytes.Equal(have, want) {
t.Errorf("does not match golden file")
}
}
type basic struct {
Title string
}
func (basic) Templates() []string {
return []string{"basic"}
}
type layout struct {
Title string
}
type index struct {
layout
}
func (index) Templates() []string {
return []string{"layout", "index"}
}
type nested struct {
layout
}
func (nested) Templates() []string {
return []string{"layout", "nested", "list_item"}
}