forked from hairyhenderson/gomplate
/
test.go
87 lines (75 loc) · 1.81 KB
/
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
package funcs
import (
"sync"
"github.com/hairyhenderson/gomplate/conv"
"github.com/pkg/errors"
"github.com/hairyhenderson/gomplate/test"
)
var (
testNS *TestFuncs
testNSInit sync.Once
)
// TestNS -
func TestNS() *TestFuncs {
testNSInit.Do(func() { testNS = &TestFuncs{} })
return testNS
}
// AddTestFuncs -
func AddTestFuncs(f map[string]interface{}) {
f["test"] = TestNS
f["assert"] = TestNS().Assert
f["fail"] = TestNS().Fail
f["required"] = TestNS().Required
f["ternary"] = TestNS().Ternary
}
// TestFuncs -
type TestFuncs struct{}
// Assert -
func (f *TestFuncs) Assert(args ...interface{}) (string, error) {
input := conv.ToBool(args[len(args)-1])
switch len(args) {
case 1:
return test.Assert(input, "")
case 2:
message, ok := args[0].(string)
if !ok {
return "", errors.Errorf("at <1>: expected string; found %T", args[0])
}
return test.Assert(input, message)
default:
return "", errors.Errorf("wrong number of args: want 1 or 2, got %d", len(args))
}
}
// Fail -
func (f *TestFuncs) Fail(args ...interface{}) (string, error) {
switch len(args) {
case 0:
return "", test.Fail("")
case 1:
return "", test.Fail(conv.ToString(args[0]))
default:
return "", errors.Errorf("wrong number of args: want 0 or 1, got %d", len(args))
}
}
// Required -
func (f *TestFuncs) Required(args ...interface{}) (interface{}, error) {
switch len(args) {
case 1:
return test.Required("", args[0])
case 2:
message, ok := args[0].(string)
if !ok {
return nil, errors.Errorf("at <1>: expected string; found %T", args[0])
}
return test.Required(message, args[1])
default:
return nil, errors.Errorf("wrong number of args: want 1 or 2, got %d", len(args))
}
}
// Ternary -
func (f *TestFuncs) Ternary(tval, fval, b interface{}) interface{} {
if conv.ToBool(b) {
return tval
}
return fval
}