forked from go-ozzo/ozzo-validation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_test.go
106 lines (85 loc) · 2.09 KB
/
string_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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package validation
import (
"database/sql"
"testing"
"reflect"
"github.com/stretchr/testify/assert"
)
func validateMe(s string) bool {
return s == "me"
}
func TestNewStringRule(t *testing.T) {
v := NewStringRule(validateMe, "abc")
assert.NotNil(t, v.validate)
assert.Equal(t, "abc", v.message)
}
func TestStringValidator_Error(t *testing.T) {
v := NewStringRule(validateMe, "abc")
assert.Equal(t, "abc", v.message)
v2 := v.Error("correct")
assert.Equal(t, "correct", v2.message)
assert.Equal(t, "abc", v.message)
}
func TestStringValidator_Validate(t *testing.T) {
v := NewStringRule(validateMe, "wrong")
value := "me"
err := v.Validate(value)
assert.Nil(t, err)
err = v.Validate(&value)
assert.Nil(t, err)
value = ""
err = v.Validate(value)
assert.Nil(t, err)
err = v.Validate(&value)
assert.Nil(t, err)
nullValue := sql.NullString{String: "me", Valid: true}
err = v.Validate(nullValue)
assert.Nil(t, err)
nullValue = sql.NullString{String: "", Valid: true}
err = v.Validate(nullValue)
assert.Nil(t, err)
var s *string
err = v.Validate(s)
assert.Nil(t, err)
err = v.Validate("not me")
if assert.NotNil(t, err) {
assert.Equal(t, "wrong", err.Error())
}
err = v.Validate(100)
if assert.NotNil(t, err) {
assert.NotEqual(t, "wrong", err.Error())
}
v2 := v.Error("Wrong!")
err = v2.Validate("not me")
if assert.NotNil(t, err) {
assert.Equal(t, "Wrong!", err.Error())
}
}
func TestGetErrorFieldName(t *testing.T) {
type A struct {
T0 string
T1 string `json:"t1"`
T2 string `json:"t2,omitempty"`
T3 string `json:",omitempty"`
T4 string `json:"t4,x1,omitempty"`
}
tests := []struct {
tag string
field string
name string
}{
{"t1", "T0", "T0"},
{"t2", "T1", "t1"},
{"t3", "T2", "t2"},
{"t4", "T3", "T3"},
{"t5", "T4", "t4"},
}
a := reflect.TypeOf(A{})
for _, test := range tests {
field, _ := a.FieldByName(test.field)
assert.Equal(t, test.name, getErrorFieldName(&field), test.tag)
}
}