-
Notifications
You must be signed in to change notification settings - Fork 12
/
custom_test.go
44 lines (36 loc) · 951 Bytes
/
custom_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
package checker
import (
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCustom(t *testing.T) {
type customStruct struct {
Inner struct {
Str string
}
}
checkFn := func(exprValue interface{}) (bool, string) {
res, ok := exprValue.(string)
if !ok {
res = reflect.ValueOf(exprValue).String()
}
if !strings.Contains(res, "checker") {
return false, "String should contain checker."
}
return true, ""
}
rule := Custom("Inner.Str", checkFn)
validator := NewChecker()
validator.Add(rule, "wrong Custom")
custom := customStruct{}
custom.Inner.Str = "checker custom function"
isValid, _, _ := validator.Check(&custom)
assert.Equal(t, true, isValid)
custom.Inner.Str = "abc"
isValid, prompt, errMsg := validator.Check(&custom)
assert.Equal(t, false, isValid)
assert.Equal(t, "wrong Custom", prompt)
assert.Equal(t, "[Custom]:Inner.Str String should contain checker.", errMsg)
}