-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate_test.go
111 lines (83 loc) · 2.45 KB
/
validate_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
107
108
109
110
111
package config
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
type validateCustom struct{ mock.Mock }
func (m *validateCustom) Validate() error { return m.Called().Error(0) }
type validateStruct struct {
F1 bool
F2 validateCustom
F3 *validateCustom
}
func (sv *validateStruct) Validate() error {
if sv.F1 == true {
return errors.New("f1 is true and should not")
}
return nil
}
func Test_Validate(t *testing.T) {
var sv *validateStruct
t.Run("nil value", func(t *testing.T) {
require.Error(t, Validate(nil))
})
t.Run("one ptr is nil", func(t *testing.T) {
sv = new(validateStruct)
sv.F1 = false
sv.F2.On("Validate").Return(nil).Once()
err := Validate(&sv)
assert.NoError(t, err)
sv.F2.AssertExpectations(t)
})
t.Run("no validation error", func(t *testing.T) {
sv = new(validateStruct)
sv.F3 = new(validateCustom)
sv.F1 = false
sv.F2.On("Validate").Return(nil).Once()
sv.F3.On("Validate").Return(nil).Once()
err := Validate(&sv)
assert.NoError(t, err)
sv.F2.AssertExpectations(t)
sv.F3.AssertExpectations(t)
})
t.Run("one reflect validation error", func(t *testing.T) {
sv = new(validateStruct)
sv.F3 = new(validateCustom)
sv.F1 = false
sv.F2.On("Validate").Return(nil).Once()
sv.F3.On("Validate").Return(errors.New("should be true")).Once()
err := Validate(&sv)
assert.Error(t, err)
assert.Equal(t, "validation error: field f3 should be true", err.Error())
sv.F2.AssertExpectations(t)
sv.F3.AssertExpectations(t)
})
t.Run("multiple reflect validation error", func(t *testing.T) {
sv = new(validateStruct)
sv.F3 = new(validateCustom)
sv.F1 = false
sv.F2.On("Validate").Return(errors.New("should be nil")).Once()
sv.F3.On("Validate").Return(errors.New("should be non nil")).Once()
err := Validate(&sv)
assert.Error(t, err)
assert.Contains(t, err.Error(), "field f2 should be nil")
assert.Contains(t, err.Error(), "field f3 should be non nil")
sv.F2.AssertExpectations(t)
sv.F3.AssertExpectations(t)
})
t.Run("validation error", func(t *testing.T) {
sv = new(validateStruct)
sv.F3 = new(validateCustom)
sv.F1 = true
sv.F2.On("Validate").Return(nil).Once()
sv.F3.On("Validate").Return(nil).Once()
err := Validate(&sv)
assert.Error(t, err)
assert.Equal(t, "validation error: f1 is true and should not", err.Error())
sv.F2.AssertExpectations(t)
sv.F3.AssertExpectations(t)
})
}