forked from hashicorp/consul-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate_test.go
698 lines (607 loc) · 15.3 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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
package main
import (
"bytes"
"os"
"strings"
"testing"
"time"
dep "github.com/hashicorp/consul-template/dependency"
"github.com/hashicorp/consul-template/test"
)
func TestNewTemplate_missingPath(t *testing.T) {
_, err := NewTemplate("/path/to/non-existent/file")
if err == nil {
t.Fatal("expected error, but nothing was returned")
}
expected := "no such file or directory"
if !strings.Contains(err.Error(), expected) {
t.Errorf("expected %q to be %q", err.Error(), expected)
}
}
func TestNewTemplate_setsPathAndContents(t *testing.T) {
contents := []byte("some content")
in := test.CreateTempfile(contents, t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
if tmpl.Path != in.Name() {
t.Errorf("expected %q to be %q", tmpl.Path, in.Name())
}
if tmpl.contents != string(contents) {
t.Errorf("expected %q to be %q", tmpl.contents, string(contents))
}
}
func TestNewTemplate_setsPathAndMD5(t *testing.T) {
contents := []byte("some content")
in := test.CreateTempfile(contents, t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
if tmpl.Path != in.Name() {
t.Errorf("expected %q to be %q", tmpl.Path, in.Name())
}
expect := "9893532233caff98cd083a116b013c0b"
if tmpl.hexMD5 != expect {
t.Errorf("expected %q to be %q", tmpl.hexMD5, expect)
}
}
func TestExecute_noDependencies(t *testing.T) {
contents := []byte("This is a template with just text")
in := test.CreateTempfile(contents, t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
brain := NewBrain()
used, missing, result, err := tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
if num := len(used); num != 0 {
t.Errorf("expected 0 missing, got: %d", num)
}
if num := len(missing); num != 0 {
t.Errorf("expected 0 missing, got: %d", num)
}
if !bytes.Equal(result, contents) {
t.Errorf("expected %q to be %q", result, contents)
}
}
func TestExecute_missingDependencies(t *testing.T) {
contents := []byte(`{{key "foo"}}`)
in := test.CreateTempfile(contents, t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
brain := NewBrain()
used, missing, result, err := tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
if num := len(used); num != 1 {
t.Fatalf("expected 1 used, got: %d", num)
}
if num := len(missing); num != 1 {
t.Fatalf("expected 1 missing, got: %d", num)
}
expectedResult := []byte("")
if !bytes.Equal(result, expectedResult) {
t.Errorf("expected %q to be %q", result, expectedResult)
}
}
func TestExecte_badFuncs(t *testing.T) {
in := test.CreateTempfile([]byte(`{{ tickle_me_pink }}`), t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
brain := NewBrain()
used, missing, result, err := tmpl.Execute(brain)
if err == nil {
t.Fatal("expected error, but nothing was returned")
}
expected := `function "tickle_me_pink" not defined`
if !strings.Contains(err.Error(), expected) {
t.Errorf("expected %q to contain %q", err.Error(), expected)
}
if used != nil {
t.Errorf("expected used to be nil")
}
if missing != nil {
t.Errorf("expected missing to be nil")
}
if result != nil {
t.Errorf("expected result to be nil")
}
}
func TestExecute_funcs(t *testing.T) {
in := test.CreateTempfile([]byte(`
{{ range service "release.webapp" }}{{.Address}}{{ end }}
{{ key "service/redis/maxconns" }}
{{ range ls "service/redis/config" }}{{.Key}}{{ end }}
`), t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
brain := NewBrain()
used, missing, _, err := tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
if num := len(missing); num != 3 {
t.Fatalf("expected 3 missing, got: %d", num)
}
if num := len(used); num != 3 {
t.Fatalf("expected 3 used, got: %d", num)
}
}
func TestExecute_duplicateFuncs(t *testing.T) {
in := test.CreateTempfile([]byte(`
{{ key "service/redis/maxconns" }}
{{ key "service/redis/maxconns" }}
{{ key "service/redis/maxconns" }}
`), t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
brain := NewBrain()
used, missing, _, err := tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
if num := len(missing); num != 1 {
t.Fatalf("expected 1 missing, got: %d", num)
}
if num := len(used); num != 1 {
t.Fatalf("expected 1 used, got: %d", num)
}
}
func TestExecute_renders(t *testing.T) {
// Stub out the time.
now = func() time.Time { return time.Unix(0, 0).UTC() }
in := test.CreateTempfile([]byte(`
API Functions
-------------
datacenters:{{ range datacenters }}
{{.}}{{ end }}
file: {{ file "/path/to/file" }}
key: {{ key "config/redis/maxconns" }}
key_or_default (exists): {{ key_or_default "config/redis/minconns" "100" }}
key_or_default (missing): {{ key_or_default "config/redis/maxconns" "200" }}
ls:{{ range ls "config/redis" }}
{{.Key}}={{.Value}}{{ end }}
node:{{ with node }}
{{.Node.Node}}{{ range .Services}}
{{.Service}}{{ end }}{{ end }}
nodes:{{ range nodes }}
{{.Node}}{{ end }}
secret: {{ with secret "secret/foo/bar" }}{{.Data.zip}}{{ end }}
secrets:{{ range secrets "secret/" }}
{{.}}{{ end }}
service:{{ range service "webapp" }}
{{.Address}}{{ end }}
service (any):{{ range service "webapp" "any" }}
{{.Address}}{{ end }}
service (tag.Contains):{{ range service "webapp" }}{{ if .Tags.Contains "production" }}
{{.Node}}{{ end }}{{ end }}
services:{{ range services }}
{{.Name}}{{ end }}
tree:{{ range tree "config/redis" }}
{{.Key}}={{.Value}}{{ end }}
vault: {{ with vault "secret/foo/bar" }}{{.Data.zip}}{{ end }}
Helper Functions
----------------
byKey:{{ range $key, $pairs := tree "config/redis" | byKey }}
{{$key}}:{{ range $pairs }}
{{.Key}}={{.Value}}{{ end }}{{ end }}
byTag (health service):{{ range $tag, $services := service "webapp" | byTag }}
{{$tag}}:{{ range $services }}
{{.Address}}{{ end }}{{ end }}
byTag (catalog services):{{ range $tag, $services := services | byTag }}
{{$tag}}:{{ range $services }}
{{.Name}}{{ end }}{{ end }}
contains:{{ range service "webapp" }}{{ if .Tags | contains "production" }}
{{.Node}}{{ end }}{{ end }}
env: {{ env "foo" }}
explode:{{ range $k, $v := tree "config/redis" | explode }}
{{$k}}{{$v}}{{ end }}
in:{{ range service "webapp" }}{{ if in .Tags "production" }}
{{.Node}}{{ end }}{{ end }}
loop:{{ range loop 3 }}
test{{ end }}
loop(i):{{ range $i := loop 5 8 }}
test{{$i}}{{ end }}
join: {{ "a,b,c" | split "," | join ";" }}
trimSpace: {{ "\t Hello, World\n " | trimSpace }}
parseBool: {{"true" | parseBool}}
parseFloat: {{"1.2" | parseFloat}}
parseInt: {{"-1" | parseInt}}
parseJSON (string):{{ range $key, $value := "{\"foo\": \"bar\"}" | parseJSON }}
{{$key}}={{$value}}{{ end }}
parseJSON (file):{{ range $key, $value := file "/path/to/json/file" | parseJSON }}
{{$key}}={{$value}}{{ end }}
parseJSON (env):{{ range $key, $value := env "json" | parseJSON }}
{{$key}}={{$value}}{{ end }}
parseUint: {{"1" | parseUint}}
plugin: {{ file "/path/to/json/file" | plugin "echo" }}
timestamp: {{ timestamp }}
timestamp (formatted): {{ timestamp "2006-01-02" }}
regexMatch: {{ file "/path/to/file" | regexMatch ".*[cont][a-z]+" }}
regexMatch: {{ file "/path/to/file" | regexMatch "v[0-9]*" }}
regexReplaceAll: {{ file "/path/to/file" | regexReplaceAll "\\w" "x" }}
replaceAll: {{ file "/path/to/file" | replaceAll "some" "this" }}
split:{{ range "a,b,c" | split "," }}
{{.}}{{end}}
toLower: {{ file "/path/to/file" | toLower }}
toJSON: {{ tree "config/redis" | explode | toJSON }}
toJSONPretty:
{{ tree "config/redis" | explode | toJSONPretty }}
toTitle: {{ file "/path/to/file" | toTitle }}
toUpper: {{ file "/path/to/file" | toUpper }}
toYAML:
{{ tree "config/redis" | explode | toYAML }}
Math Functions
--------------
add:{{ 2 | add 2 }}
subtract:{{ 2 | subtract 2 }}
multiply:{{ 2 | multiply 2 }}
divide:{{ 2 | divide 2 }}
`), t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
brain := NewBrain()
var d dep.Dependency
d, err = dep.ParseDatacenters()
if err != nil {
t.Fatal(err)
}
brain.Remember(d, []string{"dc1", "dc2"})
d, err = dep.ParseFile("/path/to/file")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, "some content")
d, err = dep.ParseStoreKey("config/redis/maxconns")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, "5")
d, err = dep.ParseStoreKey("config/redis/minconns")
if err != nil {
t.Fatal(err)
}
d.(*dep.StoreKey).SetDefault("100")
brain.Remember(d, "150")
d, err = dep.ParseStoreKey("config/redis/maxconns")
if err != nil {
t.Fatal(err)
}
d.(*dep.StoreKey).SetDefault("200")
d, err = dep.ParseStoreKeyPrefix("config/redis")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, []*dep.KeyPair{
&dep.KeyPair{Key: "", Value: ""},
&dep.KeyPair{Key: "admin/port", Value: "1134"},
&dep.KeyPair{Key: "maxconns", Value: "5"},
&dep.KeyPair{Key: "minconns", Value: "2"},
})
d, err = dep.ParseCatalogNode()
if err != nil {
t.Fatal(err)
}
brain.Remember(d, &dep.NodeDetail{
Node: &dep.Node{Node: "node1"},
Services: dep.NodeServiceList([]*dep.NodeService{
&dep.NodeService{
Service: "service1",
},
}),
})
d, err = dep.ParseCatalogNodes("")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, []*dep.Node{
&dep.Node{Node: "node1"},
&dep.Node{Node: "node2"},
})
d, err = dep.ParseHealthServices("webapp")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, []*dep.HealthService{
&dep.HealthService{
Node: "node1",
Address: "1.2.3.4",
Tags: []string{"release"},
},
&dep.HealthService{
Node: "node2",
Address: "5.6.7.8",
Tags: []string{"release", "production"},
},
&dep.HealthService{
Node: "node3",
Address: "9.10.11.12",
Tags: []string{"production"},
},
})
d, err = dep.ParseHealthServices("webapp", "any")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, []*dep.HealthService{
&dep.HealthService{Node: "node1", Address: "1.2.3.4"},
&dep.HealthService{Node: "node2", Address: "5.6.7.8"},
})
d, err = dep.ParseCatalogServices("")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, []*dep.CatalogService{
&dep.CatalogService{
Name: "service1",
Tags: []string{"production"},
},
&dep.CatalogService{
Name: "service2",
Tags: []string{"release", "production"},
},
})
d, err = dep.ParseVaultSecrets("secret/")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, []string{"bar", "foo"})
d, err = dep.ParseVaultSecret("secret/foo/bar")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, &dep.Secret{
LeaseID: "abcd1234",
LeaseDuration: 120,
Renewable: true,
Data: map[string]interface{}{"zip": "zap"},
})
if err := os.Setenv("foo", "bar"); err != nil {
t.Fatal(err)
}
d, err = dep.ParseFile("/path/to/json/file")
if err != nil {
t.Fatal(err)
}
brain.Remember(d, `{"foo": "bar"}`)
if err := os.Setenv("json", `{"foo": "bar"}`); err != nil {
t.Fatal(err)
}
_, _, result, err := tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
expected := []byte(`
API Functions
-------------
datacenters:
dc1
dc2
file: some content
key: 5
key_or_default (exists): 150
key_or_default (missing): 200
ls:
maxconns=5
minconns=2
node:
node1
service1
nodes:
node1
node2
secret: zap
secrets:
bar
foo
service:
1.2.3.4
5.6.7.8
9.10.11.12
service (any):
1.2.3.4
5.6.7.8
service (tag.Contains):
node2
node3
services:
service1
service2
tree:
admin/port=1134
maxconns=5
minconns=2
vault: zap
Helper Functions
----------------
byKey:
admin:
port=1134
byTag (health service):
production:
5.6.7.8
9.10.11.12
release:
1.2.3.4
5.6.7.8
byTag (catalog services):
production:
service1
service2
release:
service2
contains:
node2
node3
env: bar
explode:
adminmap[port:1134]
maxconns5
minconns2
in:
node2
node3
loop:
test
test
test
loop(i):
test5
test6
test7
join: a;b;c
trimSpace: Hello, World
parseBool: true
parseFloat: 1.2
parseInt: -1
parseJSON (string):
foo=bar
parseJSON (file):
foo=bar
parseJSON (env):
foo=bar
parseUint: 1
plugin: {"foo": "bar"}
timestamp: 1970-01-01T00:00:00Z
timestamp (formatted): 1970-01-01
regexMatch: true
regexMatch: false
regexReplaceAll: xxxx xxxxxxx
replaceAll: this content
split:
a
b
c
toLower: some content
toJSON: {"admin":{"port":"1134"},"maxconns":"5","minconns":"2"}
toJSONPretty:
{
"admin": {
"port": "1134"
},
"maxconns": "5",
"minconns": "2"
}
toTitle: Some Content
toUpper: SOME CONTENT
toYAML:
admin:
port: "1134"
maxconns: "5"
minconns: "2"
Math Functions
--------------
add:4
subtract:0
multiply:4
divide:1
`)
if !bytes.Equal(result, expected) {
t.Errorf("expected \n\n%q\n\n to be \n\n%q\n\n", result, expected)
}
}
func TestExecute_multipass(t *testing.T) {
in := test.CreateTempfile([]byte(`
{{ range ls "services" }}{{.Key}}:{{ range service .Key }}
{{.Node}} {{.Address}}:{{.Port}}{{ end }}
{{ end }}
`), t)
defer test.DeleteTempfile(in, t)
tmpl, err := NewTemplate(in.Name())
if err != nil {
t.Fatal(err)
}
brain := NewBrain()
used, missing, result, err := tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
if num := len(missing); num != 1 {
t.Errorf("expected 1 missing, got: %d", num)
}
if num := len(used); num != 1 {
t.Errorf("expected 1 used, got: %d", num)
}
expected := bytes.TrimSpace([]byte(""))
result = bytes.TrimSpace(result)
if !bytes.Equal(result, expected) {
t.Errorf("expected %q to be %q", result, expected)
}
// Receive data for the key prefix dependency
d1, err := dep.ParseStoreKeyPrefix("services")
brain.Remember(d1, []*dep.KeyPair{
&dep.KeyPair{Key: "webapp", Value: "1"},
&dep.KeyPair{Key: "database", Value: "1"},
})
used, missing, result, err = tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
if num := len(missing); num != 2 {
t.Errorf("expected 2 missing, got: %d", num)
}
if num := len(used); num != 3 {
t.Errorf("expected 3 used, got: %d", num)
}
expected = bytes.TrimSpace([]byte(`
webapp:
database:
`))
result = bytes.TrimSpace(result)
if !bytes.Equal(result, expected) {
t.Errorf("expected \n%q\n to be \n%q\n", result, expected)
}
// Receive data for the services
d2, err := dep.ParseHealthServices("webapp")
brain.Remember(d2, []*dep.HealthService{
&dep.HealthService{Node: "web01", Address: "1.2.3.4", Port: 1234},
})
d3, err := dep.ParseHealthServices("database")
brain.Remember(d3, []*dep.HealthService{
&dep.HealthService{Node: "db01", Address: "5.6.7.8", Port: 5678},
})
used, missing, result, err = tmpl.Execute(brain)
if err != nil {
t.Fatal(err)
}
if num := len(missing); num != 0 {
t.Errorf("expected 0 missing, got: %d", num)
}
if num := len(used); num != 3 {
t.Errorf("expected 3 used, got: %d", num)
}
expected = bytes.TrimSpace([]byte(`
webapp:
web01 1.2.3.4:1234
database:
db01 5.6.7.8:5678
`))
result = bytes.TrimSpace(result)
if !bytes.Equal(result, expected) {
t.Errorf("expected \n%q\n to be \n%q\n", result, expected)
}
}