-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidation_test.go
77 lines (67 loc) · 1.74 KB
/
validation_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
package httpsuite
import (
"github.com/go-playground/validator/v10"
"testing"
"github.com/stretchr/testify/assert"
)
type TestValidationRequest struct {
Name string `validate:"required"`
Age int `validate:"required,min=18"`
}
func TestNewValidationErrors(t *testing.T) {
validate := validator.New()
request := TestValidationRequest{} // Missing required fields to trigger validation errors
err := validate.Struct(request)
if err == nil {
t.Fatal("Expected validation errors, but got none")
}
validationErrors := NewValidationErrors(err)
expectedErrors := map[string][]string{
"Name": {"Name required"},
"Age": {"Age required"},
}
assert.Equal(t, expectedErrors, validationErrors.Errors)
}
func TestIsRequestValid(t *testing.T) {
tests := []struct {
name string
request TestValidationRequest
expectedErrors *ValidationErrors
}{
{
name: "Valid request",
request: TestValidationRequest{Name: "Alice", Age: 25},
expectedErrors: nil, // No errors expected for valid input
},
{
name: "Missing Name and Age below minimum",
request: TestValidationRequest{Age: 17},
expectedErrors: &ValidationErrors{
Errors: map[string][]string{
"Name": {"Name required"},
"Age": {"Age min"},
},
},
},
{
name: "Missing Age",
request: TestValidationRequest{Name: "Alice"},
expectedErrors: &ValidationErrors{
Errors: map[string][]string{
"Age": {"Age required"},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
errs := IsRequestValid(tt.request)
if tt.expectedErrors == nil {
assert.Nil(t, errs)
} else {
assert.NotNil(t, errs)
assert.Equal(t, tt.expectedErrors.Errors, errs.Errors)
}
})
}
}