-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuncmap_test.go
More file actions
115 lines (91 loc) · 2.08 KB
/
funcmap_test.go
File metadata and controls
115 lines (91 loc) · 2.08 KB
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
package tmpl
import (
"bytes"
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
type AddFunctionComponent struct {
A, B int
}
func (*AddFunctionComponent) TemplateText() string {
return `{{ add .A .B }}`
}
func (*AddFunctionComponent) TemplateFuncMap() FuncMap {
return FuncMap{
"add": func(a, b int) string {
return fmt.Sprintf("%d", a+b)
},
}
}
type SubFunctionComponent struct {
A, B int
}
func (*SubFunctionComponent) TemplateText() string {
return `{{ sub .A .B }}`
}
func (*SubFunctionComponent) TemplateFuncMap() FuncMap {
return FuncMap{
"sub": func(a, b int) string {
return fmt.Sprintf("%d", a-b)
},
}
}
type MergedFunctionComponent struct {
A, B int
AddFunctionComponent
SubFunctionComponent
}
func (*MergedFunctionComponent) TemplateText() string {
return `{{ add .A .B }}, {{ sub .A .B }}`
}
type NestedFunctionComponent struct {
A, B int
Nested struct {
AddFunctionComponent
Nested struct {
SubFunctionComponent
}
}
}
func (*NestedFunctionComponent) TemplateText() string {
return `{{ add .A .B }}, {{ sub .A .B }}`
}
func TestCompile_FuncMapProvider(t *testing.T) {
t.Run("success", func(t *testing.T) {
templateProvider := &AddFunctionComponent{
A: 1,
B: 2,
}
tmpl, err := Compile(templateProvider)
require.NoError(t, err)
buf := bytes.Buffer{}
err = tmpl.Render(&buf, templateProvider)
require.NoError(t, err)
require.Equal(t, "3", buf.String())
})
t.Run("merged_func_map_providers", func(t *testing.T) {
templateProvider := &MergedFunctionComponent{
A: 1,
B: 2,
}
tmpl, err := Compile(templateProvider)
require.NoError(t, err)
buf := bytes.Buffer{}
err = tmpl.Render(&buf, templateProvider)
require.NoError(t, err)
require.Equal(t, "3, -1", buf.String())
})
t.Run("nested_func_map_providers", func(t *testing.T) {
templateProvider := &NestedFunctionComponent{
A: 1,
B: 2,
}
tmpl, err := Compile(templateProvider)
require.NoError(t, err)
buf := bytes.Buffer{}
err = tmpl.Render(&buf, templateProvider)
require.NoError(t, err)
require.Equal(t, "3, -1", buf.String())
})
}