forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.go
61 lines (54 loc) · 1.5 KB
/
assert.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
package errorx
import (
"errors"
"fmt"
"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/internal/comfunc"
)
// IsTrue assert result is true, otherwise will return error
func IsTrue(result bool, fmtAndArgs ...any) error {
if !result {
return errors.New(formatErrMsg("result should be True", fmtAndArgs))
}
return nil
}
// IsFalse assert result is false, otherwise will return error
func IsFalse(result bool, fmtAndArgs ...any) error {
if result {
return errors.New(formatErrMsg("result should be False", fmtAndArgs))
}
return nil
}
// IsIn value should be in the list, otherwise will return error
func IsIn[T comdef.ScalarType](value T, list []T, fmtAndArgs ...any) error {
if arrutil.NotIn(value, list) {
var errMsg string
if len(fmtAndArgs) > 0 {
errMsg = comfunc.FormatTplAndArgs(fmtAndArgs)
} else {
errMsg = fmt.Sprintf("value should be in the %v", list)
}
return errors.New(errMsg)
}
return nil
}
// NotIn value should not be in the list, otherwise will return error
func NotIn[T comdef.ScalarType](value T, list []T, fmtAndArgs ...any) error {
if arrutil.In(value, list) {
var errMsg string
if len(fmtAndArgs) > 0 {
errMsg = comfunc.FormatTplAndArgs(fmtAndArgs)
} else {
errMsg = fmt.Sprintf("value should not be in the %v", list)
}
return errors.New(errMsg)
}
return nil
}
func formatErrMsg(errMsg string, fmtAndArgs []any) string {
if len(fmtAndArgs) > 0 {
errMsg = comfunc.FormatTplAndArgs(fmtAndArgs)
}
return errMsg
}