github.com/hairyhenderson/templater@v3.5.0+incompatible/funcs/test.go (about) 1 package funcs 2 3 import ( 4 "sync" 5 6 "github.com/hairyhenderson/gomplate/conv" 7 "github.com/pkg/errors" 8 9 "github.com/hairyhenderson/gomplate/test" 10 ) 11 12 var ( 13 testNS *TestFuncs 14 testNSInit sync.Once 15 ) 16 17 // TestNS - 18 func TestNS() *TestFuncs { 19 testNSInit.Do(func() { testNS = &TestFuncs{} }) 20 return testNS 21 } 22 23 // AddTestFuncs - 24 func AddTestFuncs(f map[string]interface{}) { 25 f["test"] = TestNS 26 27 f["assert"] = TestNS().Assert 28 f["fail"] = TestNS().Fail 29 f["required"] = TestNS().Required 30 f["ternary"] = TestNS().Ternary 31 } 32 33 // TestFuncs - 34 type TestFuncs struct{} 35 36 // Assert - 37 func (f *TestFuncs) Assert(args ...interface{}) (string, error) { 38 input := conv.ToBool(args[len(args)-1]) 39 switch len(args) { 40 case 1: 41 return test.Assert(input, "") 42 case 2: 43 message, ok := args[0].(string) 44 if !ok { 45 return "", errors.Errorf("at <1>: expected string; found %T", args[0]) 46 } 47 return test.Assert(input, message) 48 default: 49 return "", errors.Errorf("wrong number of args: want 1 or 2, got %d", len(args)) 50 } 51 } 52 53 // Fail - 54 func (f *TestFuncs) Fail(args ...interface{}) (string, error) { 55 switch len(args) { 56 case 0: 57 return "", test.Fail("") 58 case 1: 59 return "", test.Fail(conv.ToString(args[0])) 60 default: 61 return "", errors.Errorf("wrong number of args: want 0 or 1, got %d", len(args)) 62 } 63 } 64 65 // Required - 66 func (f *TestFuncs) Required(args ...interface{}) (interface{}, error) { 67 switch len(args) { 68 case 1: 69 return test.Required("", args[0]) 70 case 2: 71 message, ok := args[0].(string) 72 if !ok { 73 return nil, errors.Errorf("at <1>: expected string; found %T", args[0]) 74 } 75 return test.Required(message, args[1]) 76 default: 77 return nil, errors.Errorf("wrong number of args: want 1 or 2, got %d", len(args)) 78 } 79 } 80 81 // Ternary - 82 func (f *TestFuncs) Ternary(tval, fval, b interface{}) interface{} { 83 if conv.ToBool(b) { 84 return tval 85 } 86 return fval 87 }