This repository has been archived by the owner on Dec 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
template_test.go
111 lines (93 loc) · 2.53 KB
/
template_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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package extemplate
import (
"bytes"
"html/template"
"strings"
"sync"
"testing"
)
var x *Extemplate
var once sync.Once
func setup() {
x = New().Delims("{{", "}}").Funcs(template.FuncMap{
"tolower": strings.ToLower,
})
err := x.ParseDir("examples", []string{".tmpl"})
if err != nil {
panic(err)
}
}
func TestLookup(t *testing.T) {
once.Do(setup)
if tmpl := x.Lookup("foobar"); tmpl != nil {
t.Errorf("Lookup: expected nil, got %#v", tmpl)
}
if tmpl := x.Lookup("child.tmpl"); tmpl == nil {
t.Error("Lookup: expected template, got nil")
}
}
func TestExecuteTemplate(t *testing.T) {
once.Do(setup)
var buf bytes.Buffer
if err := x.ExecuteTemplate(&buf, "child.tmpl", nil); err != nil {
t.Errorf("ExecuteTemplate: %s", err)
}
if err := x.ExecuteTemplate(&buf, "foobar", nil); err == nil {
t.Error("ExecuteTemplate: expected err for unexisting template, got none")
}
}
func TestTemplates(t *testing.T) {
once.Do(setup)
tests := map[string]string{
"parent.tmpl": "Hello from master.tmpl", // normal template with {{ block }}
"child.tmpl": "Hello from child.tmpl\n\tHello from partials/question.tmpl", // template with inheritance
"grand-child.tmpl": "Hello from grand-child.tmpl", // template with nested inheritance
}
for k, v := range tests {
tmpl := x.Lookup(k)
if tmpl == nil {
t.Errorf("template not found in set: %s", k)
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
t.Errorf("error executing template %s: %s", k, err)
}
e := strings.TrimSpace(buf.String())
e = strings.Replace(e, "\r\n", "\n", -1)
if e != v {
t.Errorf("incorrect template result. \nExpected: %s\nActual: %s", v, e)
}
}
}
func TestNewTemplateFile(t *testing.T) {
tests := map[string]string{
"{{ extends \"foo.html\" }}": "foo.html",
"Nothing": "",
"{{ extends \"dir/file.html\" }}\n {{ .Var }}": "dir/file.html",
}
for c, e := range tests {
tf, err := newTemplateFile([]byte(c))
if err != nil {
t.Error(err)
}
if tf.layout != e {
t.Errorf("Expected layout %s, got %s", e, tf.layout)
}
}
}
func BenchmarkExtemplateGetLayoutForTemplate(b *testing.B) {
c := []byte("{{ extends \"foo.html\" }}")
for i := 0; i < b.N; i++ {
if _, err := newTemplateFile(c); err != nil {
b.Error(err)
}
}
}
func BenchmarkExtemplateParseDir(b *testing.B) {
x := New().Funcs(template.FuncMap{
"foo": strings.ToLower,
})
for i := 0; i < b.N; i++ {
x.ParseDir("examples", []string{".tmpl"})
}
}