-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhydrate_test.go
226 lines (188 loc) · 5.41 KB
/
hydrate_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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package mid
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/julienschmidt/httprouter"
)
type TestUser struct {
Name string `valid:"alphanum,required"`
Email string `valid:"email,required"`
ID int `valid:"-"`
// Bio string `valid:"ascii,required"`
// Date string `valid:"-"`
}
type TestUserService struct {
Value int
}
// Test POST with JSON body
func (s *TestUserService) Save(w http.ResponseWriter, r *http.Request, u TestUser) (TestUser, error) {
u.ID = s.Value
return u, nil
}
// Test GET with single URL param
func (s *TestUserService) Get(w http.ResponseWriter, r *http.Request, params struct {
ID int `valid:"required" query:"ID"`
}) (TestUser, error) {
return TestUser{Name: "John", ID: params.ID}, nil
}
type ResultPage struct {
// We don't need the `valid:"numeric"` check since it will be converted for
// us if it fits in the int type we defined (int = 32 bits)
Page int `valid:"required" param:"page"`
}
// Test GET with multiple params for loading
func (s *TestUserService) Recent(w http.ResponseWriter, r *http.Request, params ResultPage) ([]*TestUser, error) {
if params.Page != 10 {
return nil, fmt.Errorf("Invalid result page: %v", params.Page)
}
return []*TestUser{&TestUser{Name: "Alice"}, &TestUser{Name: "Bob"}}, nil
}
func TestValidation(t *testing.T) {
controller := &TestUserService{23}
scenarios := []struct {
Name string
Method string
Path string
URL string // URL path & query string
JSON interface{}
Form url.Values
Function interface{}
StatusCode int
Response string
}{
{
Name: "Valid JSON",
URL: "/Save",
JSON: map[string]string{"name": "john", "Email": "[email protected]"},
StatusCode: http.StatusOK,
Function: controller.Save,
Response: `{"data":{"Name":"john","Email":"[email protected]","ID":23}}`,
},
{
Name: "Invalid JSON",
URL: "/Save",
JSON: map[string]string{"Email": "@"},
StatusCode: http.StatusOK,
Function: controller.Save,
Response: `{"error":"Invalid Request","fields":{"Email":"@ does not validate as email","Name":"non zero value required"}}`,
},
{
Name: "Valid Query",
URL: "/Get?ID=34",
StatusCode: http.StatusOK,
Function: controller.Get,
Response: `{"data":{"Name":"John","Email":"","ID":34}}`,
},
{
Name: "Invalid Query",
URL: "/Get?ID=foo",
StatusCode: http.StatusOK,
Function: controller.Get,
Response: `{"error":"Invalid Request","fields":{"ID":"non zero value required"}}`,
},
{
Name: "Valid Route Param",
URL: "/users/10",
Path: "/users/:page",
StatusCode: http.StatusOK,
Function: controller.Recent,
Response: `{"data":[{"Name":"Alice","Email":"","ID":0},{"Name":"Bob","Email":"","ID":0}]}`,
},
}
var err error
for _, s := range scenarios {
t.Run(s.Name, func(t *testing.T) {
var req *http.Request
if s.JSON != nil {
var b []byte
b, err = json.Marshal(s.JSON)
if err != nil {
log.Fatal(err)
}
req, err = http.NewRequest("POST", s.URL, bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
req.Header.Add("Content-Type", "application/json")
// } else if s.Form != nil {
//
// f := s.Form
// req, err = http.NewRequest("POST", s.URL, strings.NewReader(f.Encode()))
// if err != nil {
// t.Fatal(err)
// }
//
// req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
} else {
req, err = http.NewRequest("GET", s.URL, nil)
if err != nil {
t.Fatal(err)
}
}
rr := httptest.NewRecorder()
router := httprouter.New()
path := s.Path
// Get the path from the URL if not provided
if path == "" {
u, err := url.Parse(s.URL)
if err != nil {
t.Error(err)
}
path = u.Path
}
if s.JSON != nil {
router.Handler("POST", path, Hydrate(s.Function))
} else {
router.Handler("GET", path, Hydrate(s.Function))
}
router.ServeHTTP(rr, req)
if status := rr.Code; status != s.StatusCode {
t.Errorf("%s returned wrong status code: got %v want %v", s.URL, status, s.StatusCode)
// t.Log(rr.Body.String())
}
if s.Response != "" {
response := strings.TrimSpace(rr.Body.String())
if response != s.Response {
t.Errorf("%s returned wrong response:\ngot %s\nwant %s", s.URL, response, s.Response)
}
}
})
}
}
func BenchmarkHandler(b *testing.B) {
var req *http.Request
// Service we will be wrapping
controller := &TestUserService{23}
// Create HTTP router/router
router := httprouter.New()
// Our route
router.Handler("POST", "/Save", Hydrate(controller.Save))
jsonbytes, err := json.Marshal(map[string]string{"name": "john", "Email": "[email protected]"})
if err != nil {
b.Error(err)
}
for i := 0; i < b.N; i++ {
req, err = http.NewRequest("POST", "/Save", bytes.NewReader(jsonbytes))
if err != nil {
b.Fatal(err)
}
req.Header.Add("Content-Type", "application/json")
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
b.Errorf("Wrong status code: got %v want %v", status, http.StatusOK)
}
response := strings.TrimSpace(rr.Body.String())
want := `{"data":{"Name":"john","Email":"[email protected]","ID":23}}`
if response != want {
b.Errorf("Wrong response:\ngot %s\nwant %s", response, want)
}
}
}