summaryrefslogtreecommitdiff
path: root/internal/funcs/test.go
blob: 9f14c5af456be9fa23c31f7c25a2c3840261dfa3 (plain)
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
package funcs

import (
	"context"
	"fmt"
	"reflect"

	"github.com/hairyhenderson/gomplate/v4/conv"
	"github.com/hairyhenderson/gomplate/v4/test"
)

// CreateTestFuncs -
func CreateTestFuncs(ctx context.Context) map[string]any {
	f := map[string]any{}

	ns := &TestFuncs{ctx}
	f["test"] = func() any { return ns }

	f["assert"] = ns.Assert
	f["fail"] = ns.Fail
	f["required"] = ns.Required
	f["ternary"] = ns.Ternary
	f["kind"] = ns.Kind
	f["isKind"] = ns.IsKind
	return f
}

// TestFuncs -
type TestFuncs struct {
	ctx context.Context
}

// Assert -
func (TestFuncs) Assert(args ...any) (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 "", fmt.Errorf("at <1>: expected string; found %T", args[0])
		}
		return test.Assert(input, message)
	default:
		return "", fmt.Errorf("wrong number of args: want 1 or 2, got %d", len(args))
	}
}

// Fail -
func (TestFuncs) Fail(args ...any) (string, error) {
	switch len(args) {
	case 0:
		return "", test.Fail("")
	case 1:
		return "", test.Fail(conv.ToString(args[0]))
	default:
		return "", fmt.Errorf("wrong number of args: want 0 or 1, got %d", len(args))
	}
}

// Required -
func (TestFuncs) Required(args ...any) (any, error) {
	switch len(args) {
	case 1:
		return test.Required("", args[0])
	case 2:
		message, ok := args[0].(string)
		if !ok {
			return nil, fmt.Errorf("at <1>: expected string; found %T", args[0])
		}
		return test.Required(message, args[1])
	default:
		return nil, fmt.Errorf("wrong number of args: want 1 or 2, got %d", len(args))
	}
}

// Ternary -
func (TestFuncs) Ternary(tval, fval, b any) any {
	if conv.ToBool(b) {
		return tval
	}
	return fval
}

// Kind - return the kind of the argument
func (TestFuncs) Kind(arg any) string {
	return reflect.ValueOf(arg).Kind().String()
}

// IsKind - return whether or not the argument is of the given kind
func (f TestFuncs) IsKind(kind string, arg any) bool {
	k := f.Kind(arg)
	if kind == "number" {
		switch k {
		case "int", "int8", "int16", "int32", "int64",
			"uint", "uint8", "uint16", "uint32", "uint64", "uintptr",
			"float32", "float64",
			"complex64", "complex128":
			kind = k
		}
	}
	return k == kind
}