-
Notifications
You must be signed in to change notification settings - Fork 12
/
template_test.go
121 lines (101 loc) · 2.19 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
112
113
114
115
116
117
118
119
120
121
package httpdoc
import (
"io/ioutil"
"os"
"testing"
)
func setEnv(t *testing.T, k, v string) func() {
preV := os.Getenv(k)
if err := os.Setenv(k, v); err != nil {
t.Fatal(err)
}
return func() {
if err := os.Setenv(k, preV); err != nil {
t.Fatal(err)
}
}
}
func TestDocument_Generate(t *testing.T) {
resetF := setEnv(t, EnvHTTPDoc, "test")
defer resetF()
f, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
doc := &Document{}
if err := doc.Generate(f.Name()); err != nil {
t.Fatal(err)
}
fi, err := os.Stat(f.Name())
if err != nil {
t.Fatal(err)
}
if fi.Size() == 0 {
t.Fatalf("expect doc to be generated")
}
}
func TestDocument_Generate_noEnv(t *testing.T) {
resetF := setEnv(t, EnvHTTPDoc, "")
defer resetF()
f, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
doc := &Document{}
if err := doc.Generate(f.Name()); err != nil {
t.Fatal(err)
}
fi, err := os.Stat(f.Name())
if err != nil {
t.Fatal(err)
}
if fi.Size() > 0 {
t.Fatalf("expect doc not to be generated")
}
}
func TestFuncMap(t *testing.T) {
m := funcMap()
lower := m["lower"].(func(s string) string)
if got, want := lower("DOC"), "doc"; got != want {
t.Fatalf("got %q, want %q", got, want)
}
stripslash := m["stripslash"].(func(s string) string)
if got, want := stripslash("/v2/user/contact"), "v2usercontact"; got != want {
t.Fatalf("got %q, want %q", got, want)
}
}
func TestTemplateGenerate_NotExistDir(t *testing.T) {
resetF := setEnv(t, EnvHTTPDoc, "1")
defer resetF()
doc := &Document{}
if err := doc.Generate("/tmp/httpdoc/no-such-file-or-directory"); err != nil {
t.Fatalf("expect to be failed")
}
defer os.RemoveAll("/tmp/httpdoc")
}
func TestTemplateGenerate_InvalidTmpl(t *testing.T) {
doc := &Document{
tmpl: "no-such-template",
}
if err := doc.generate(ioutil.Discard); err == nil {
t.Fatalf("expect to be failed")
}
}
func TestTmplExecute_InvalidTemplate(t *testing.T) {
cases := []struct {
text string
}{
{
`{{ .Name }`,
},
{
`{{ .Name.NoSuchField }}`,
},
}
doc := &Document{}
for _, tc := range cases {
if err := doc.tmplExecute(ioutil.Discard, tc.text); err == nil {
t.Fatalf("expect to be failed")
}
}
}