forked from Masterminds/sprig
-
Notifications
You must be signed in to change notification settings - Fork 2
/
functions_test.go
225 lines (192 loc) · 6.17 KB
/
functions_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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package sprig
import (
"bytes"
"errors"
"fmt"
"math/rand"
"os"
"regexp"
"testing"
"text/template"
"time"
"github.com/stretchr/testify/assert"
)
func TestEnv(t *testing.T) {
os.Setenv("FOO", "bar")
tpl := `{{env "FOO"}}`
if err := runt(tpl, "bar"); err != nil {
t.Error(err)
}
}
func TestExpandEnv(t *testing.T) {
os.Setenv("FOO", "bar")
tpl := `{{expandenv "Hello $FOO"}}`
if err := runt(tpl, "Hello bar"); err != nil {
t.Error(err)
}
}
func TestBase(t *testing.T) {
assert.NoError(t, runt(`{{ base "foo/bar" }}`, "bar"))
}
func TestDir(t *testing.T) {
assert.NoError(t, runt(`{{ dir "foo/bar/baz" }}`, "foo/bar"))
}
func TestIsAbs(t *testing.T) {
assert.NoError(t, runt(`{{ isAbs "/foo" }}`, "true"))
assert.NoError(t, runt(`{{ isAbs "foo" }}`, "false"))
}
func TestClean(t *testing.T) {
assert.NoError(t, runt(`{{ clean "/foo/../foo/../bar" }}`, "/bar"))
}
func TestExt(t *testing.T) {
assert.NoError(t, runt(`{{ ext "/foo/bar/baz.txt" }}`, ".txt"))
}
func TestSnakeCase(t *testing.T) {
assert.NoError(t, runt(`{{ snakecase "FirstName" }}`, "first_name"))
assert.NoError(t, runt(`{{ snakecase "HTTPServer" }}`, "http_server"))
assert.NoError(t, runt(`{{ snakecase "NoHTTPS" }}`, "no_https"))
assert.NoError(t, runt(`{{ snakecase "GO_PATH" }}`, "go_path"))
assert.NoError(t, runt(`{{ snakecase "GO PATH" }}`, "go_path"))
assert.NoError(t, runt(`{{ snakecase "GO-PATH" }}`, "go_path"))
}
func TestCamelCase(t *testing.T) {
assert.NoError(t, runt(`{{ camelcase "http_server" }}`, "HttpServer"))
assert.NoError(t, runt(`{{ camelcase "_camel_case" }}`, "_CamelCase"))
assert.NoError(t, runt(`{{ camelcase "no_https" }}`, "NoHttps"))
assert.NoError(t, runt(`{{ camelcase "_complex__case_" }}`, "_Complex_Case_"))
assert.NoError(t, runt(`{{ camelcase "all" }}`, "All"))
}
func TestKebabCase(t *testing.T) {
assert.NoError(t, runt(`{{ kebabcase "FirstName" }}`, "first-name"))
assert.NoError(t, runt(`{{ kebabcase "HTTPServer" }}`, "http-server"))
assert.NoError(t, runt(`{{ kebabcase "NoHTTPS" }}`, "no-https"))
assert.NoError(t, runt(`{{ kebabcase "GO_PATH" }}`, "go-path"))
assert.NoError(t, runt(`{{ kebabcase "GO PATH" }}`, "go-path"))
assert.NoError(t, runt(`{{ kebabcase "GO-PATH" }}`, "go-path"))
}
func TestShuffle(t *testing.T) {
defer rand.Seed(time.Now().UnixNano())
rand.Seed(1)
// Because we're using a random number generator, we need these to go in
// a predictable sequence:
assert.NoError(t, runt(`{{ shuffle "Hello World" }}`, "rldo HWlloe"))
}
func TestRegex(t *testing.T) {
assert.NoError(t, runt(`{{ regexQuoteMeta "1.2.3" }}`, "1\\.2\\.3"))
assert.NoError(t, runt(`{{ regexQuoteMeta "pretzel" }}`, "pretzel"))
}
func TestRandStringFromRegex(t *testing.T) {
tmplStr := "{{randFromRegex \"https://(www[.])example[.]com/[a-zA-Z0-9]{9,15}\"}}"
tmpl, err := template.New("randFromRegex").Funcs(FuncMap()).Parse(tmplStr)
if err != nil {
panic(err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, nil)
if err != nil {
panic(err)
}
// Print the generated random string
fmt.Println(buf.String())
tmplStr = "{{randFromRegex \"/v4/providers/[^/]+/roles/[^/]+/groups$\"}}"
tmpl, err = template.New("randFromRegex").Funcs(FuncMap()).Parse(tmplStr)
if err != nil {
panic(err)
}
var buf2 bytes.Buffer
err = tmpl.Execute(&buf2, nil)
if err != nil {
panic(err)
}
// Print the generated random string
fmt.Println(buf2.String())
/*
further make sure it accept perl chars
*/
tmplStr = `{{randFromRegex "/v\\d+/providers/[^/]+/roles\\b"}}`
tmpl, err = template.New("randFromRegex").Funcs(FuncMap()).Parse(tmplStr)
if err != nil {
panic(err)
}
var buf3 bytes.Buffer
err = tmpl.Execute(&buf3, nil)
if err != nil {
panic(err)
}
// Print the generated random string
fmt.Println(buf3.String())
}
func TestRandStringFromUrlRegex(t *testing.T) {
regexStrs := []string{
`/test/path/.+`,
`/test/[.]/haha/-~/allowed/.*`,
`https://(www[.])example[.]com/[a-zA-Z0-9]{9,15}/test@url/[a-e]+/[^/]+$`,
`/directory/v1/customers/[^/?]+/domains/[^/?]+/products(/[^/]+)?`,
`/directory/v1/customers/[^/?]+/domains/[^/?]+/products($|(/[^/]+$))`,
}
for _, regexStr := range regexStrs {
tmplStr := fmt.Sprintf("{{randFromUrlRegex \"%s\"}}", regexStr)
tmpl, err := template.New("randFromUrlRegex").Funcs(FuncMap()).Parse(tmplStr)
if err != nil {
panic(err)
}
var buf bytes.Buffer
err1 := tmpl.Execute(&buf, nil)
if err1 != nil {
panic(err1)
}
randomUrl := buf.String()
regexMatcher, err2 := regexp.Compile(regexStr)
if err2 != nil {
panic(err2)
}
matched := regexMatcher.MatchString(randomUrl)
if !matched {
panic(errors.New("the generated random url does not match the original regular expression"))
}
reservedChars := getIllegalUrlCharMap()
runeSlice := []rune(randomUrl)
for _, curChar := range runeSlice {
// the following chars could be explicitly specified in the original regex, swallow the risk if found
if curChar == ':' || curChar == '/' || curChar == '@' || curChar == '.' || curChar == '-' || curChar == '~' {
continue
}
if _, exists := reservedChars[curChar]; exists {
panic(fmt.Sprintf("char [%c] exists in generated random url string", curChar))
}
}
// Print the generated random string
fmt.Println(randomUrl)
}
}
// runt runs a template and checks that the output exactly matches the expected string.
func runt(tpl, expect string) error {
return runtv(tpl, expect, map[string]string{})
}
// runtv takes a template, and expected return, and values for substitution.
//
// It runs the template and verifies that the output is an exact match.
func runtv(tpl, expect string, vars interface{}) error {
fmap := TxtFuncMap()
t := template.Must(template.New("test").Funcs(fmap).Parse(tpl))
var b bytes.Buffer
err := t.Execute(&b, vars)
if err != nil {
return err
}
if expect != b.String() {
return fmt.Errorf("Expected '%s', got '%s'", expect, b.String())
}
return nil
}
// runRaw runs a template with the given variables and returns the result.
func runRaw(tpl string, vars interface{}) (string, error) {
fmap := TxtFuncMap()
t := template.Must(template.New("test").Funcs(fmap).Parse(tpl))
var b bytes.Buffer
err := t.Execute(&b, vars)
if err != nil {
return "", err
}
return b.String(), nil
}