-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_test.go
More file actions
417 lines (400 loc) · 10.4 KB
/
request_test.go
File metadata and controls
417 lines (400 loc) · 10.4 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package greq_test
import (
"bytes"
"context"
greq "github.com/og/go-request"
"github.com/og/go-request/testserver"
gjson "github.com/og/json"
gconv "github.com/og/x/conv"
ge "github.com/og/x/error"
gtest "github.com/og/x/test"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"testing"
"time"
)
func init () {
go testserver.Run()
}
func hosturl(path string) string {
return "http://127.0.0.1:2421" + path
}
func formatMessage(s string) string {
s = strings.TrimSpace(s)
s = strings.ReplaceAll(s, "\n", "\r\n")
s = strings.TrimSpace(s)
return s
}
func formatFormDataMessage(respString string) string {
rBoundary := regexp.MustCompile(`boundary=.{60}`)
boundary := strings.Replace(rBoundary.FindString(respString), "boundary=", "", 1)
return strings.ReplaceAll(respString, boundary, "testboundarytestboundarytestboundarytestboundarytestboundary")
}
type GetQuery struct {
ID string
}
func (q GetQuery) Query() (url.Values, error) {
v := url.Values{}
v.Set("id", q.ID)
return v, nil
}
func TestGet(t *testing.T) {
as := gtest.NewAS(t)
c := greq.New(greq.Config{})
data := testserver.Data{
Method: "GET",
Path: "/TestGet",
Func: func(w http.ResponseWriter, r *http.Request) {
testserver.Send(w, greq.HttpMessage(*r))
},
}
testserver.Add(data)
query := GetQuery{
ID: "a",
}
{
var respBytes []byte
statusCode, err := c.Send(context.TODO(), data.Method, hosturl(data.Path), greq.Request{
Query: query,
}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
}) ; if err != nil { panic(err)}
as.Equal(statusCode, 200)
as.Equal(string(respBytes), formatMessage(`
GET /TestGet?id=a HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
User-Agent: Go-http-client/1.1`))
}
{
httpResp, statusCode, err := c.Do(context.TODO(), data.Method, hosturl(data.Path), greq.Request{
Query: query,
}) ; if err != nil { panic(err)}
as.Equal(statusCode, 200)
defer httpResp.Body.Close()
data ,readErr := ioutil.ReadAll(httpResp.Body) ; if readErr != nil {panic(readErr)}
as.Equal(string(data), formatMessage(`
GET /TestGet?id=a HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
User-Agent: Go-http-client/1.1`))
}
{
var respBytes []byte
statusCode, err := c.Send(context.TODO(), greq.POST, hosturl(data.Path), greq.Request{
Query: query,
}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
}) ; ge.Check(err)
as.Equal(statusCode, 200)
as.Equal(string(respBytes), "method is error: should be GET. request method is POST")
}
}
type PostJSON struct {
Name string `json:"name"`
}
func TestPost(t *testing.T) {
as := gtest.NewAS(t)
c := greq.New(greq.Config{})
{
data := testserver.Data{
Method: "POST",
Path: "/TestPost",
Func: func(w http.ResponseWriter, r *http.Request) {
testserver.Send(w, greq.HttpMessage(*r))
},
}
testserver.Add(data)
var respBytes []byte
statusCode, err := c.Send(context.TODO(), greq.POST, hosturl(data.Path), greq.Request{
JSON: PostJSON{Name: "nimoc"},
}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
}) ; ge.Check(err)
as.Equal(statusCode, 200)
message := formatMessage(`
POST /TestPost HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
Content-Length: 16
Content-Type: application/json
User-Agent: Go-http-client/1.1
{"name":"nimoc"}`)
as.Equal(string(respBytes), message)
}
}
func TestGetCookieJar(t *testing.T) {
data := testserver.Data{
Method: "GET",
Path: "/TestGetCookieJar",
Func: func(w http.ResponseWriter, r *http.Request) {
count := 0
{
requestCookie, err := r.Cookie("count")
if err != nil {
if err == http.ErrNoCookie {
count = 0
} else {
panic(err)
}
} else {
value := requestCookie.Value
count = ge.Int(strconv.Atoi(value))
}
}
count++
cookie := &http.Cookie{
Name: "count",
Value: strconv.Itoa(count),
Expires: time.Now().AddDate(0,0,1),
}
http.SetCookie(w, cookie)
testserver.Send(w, gconv.IntString(count) + "\r\n" + "" + greq.HttpMessage(*r))
},
}
testserver.Add(data)
as := gtest.NewAS(t)
cookieJar, err := cookiejar.New(nil) ; ge.Check(err)
c := greq.New(greq.Config{
HttpClient: &http.Client{
Jar: cookieJar,
},
})
{
var respBytes []byte
c.Send(context.TODO(), greq.Method(data.Method), hosturl(data.Path), greq.Request{}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
})
as.Equal(string(respBytes),
formatMessage(`1
GET /TestGetCookieJar HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
User-Agent: Go-http-client/1.1`),
)
}
{
var respBytes []byte
c.Send(context.TODO(), greq.Method(data.Method),hosturl(data.Path), greq.Request{}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
})
as.Equal(
string(respBytes),
formatMessage(`2
GET /TestGetCookieJar HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
Cookie: count=1
User-Agent: Go-http-client/1.1`),
)
}
{
var respBytes []byte
c.Send(context.TODO(), greq.Method(data.Method),hosturl(data.Path), greq.Request{}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
})
as.Equal(string(respBytes),
formatMessage(`3
GET /TestGetCookieJar HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
Cookie: count=2
User-Agent: Go-http-client/1.1`),
)
}
}
type Header struct {
APIKey string
User string
Age int
Float float64
Bool bool
List []string
}
func (h Header) Header () (http.Header, error) {
header := http.Header{}
header.Set("apiKey", h.APIKey)
header.Set("user", h.User)
return header, nil
}
func TestHeader(t *testing.T) {
as := gtest.NewAS(t)
c := greq.New(greq.Config{})
data := testserver.Data{
Method: "GET",
Path: "/TestHeader",
Func: func(w http.ResponseWriter, r *http.Request) {
testserver.Send(w, gjson.String(r.Header))
},
}
testserver.Add(data)
header := Header {
APIKey: "password",
User: "nimoc",
Age: 1,
Float: 1.2,
Bool: true,
List: []string{"a", "c"},
}
var respBytes []byte
statusCode, err := c.Send(context.TODO(), greq.Method(data.Method), hosturl(data.Path), greq.Request{
Header: header,
}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
})
ge.Check(err)
as.Equal(statusCode, 200)
as.Equal(string(respBytes), formatMessage(`{"Accept-Encoding":["gzip"],"Apikey":["password"],"User":["nimoc"],"User-Agent":["Go-http-client/1.1"]}`))
}
type WWWForm struct {
Name string
Age int
}
func (f WWWForm) FormUrlencoded() (url.Values, error) {
v := url.Values{}
v.Set("name", f.Name)
v.Set("age", gconv.IntString(f.Age))
return v, nil
}
func TestWWWFormUrlencoded(t *testing.T) {
as := gtest.NewAS(t)
c := greq.New(greq.Config{})
data := testserver.Data{
Method: "GET",
Path: "/TestWWWFormUrlencoded",
Func: func(w http.ResponseWriter, r *http.Request) {
testserver.Send(w, greq.HttpMessage(*r))
},
}
testserver.Add(data)
wwwForm := WWWForm {
Name: "nimo",
Age: 27,
}
{
var respBytes []byte
statusCode, err := c.Send(context.TODO(), greq.Method(data.Method), hosturl(data.Path), greq.Request{
FormUrlencoded: wwwForm,
}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
})
as.NoError(err)
as.Equal(statusCode, 200)
as.Equal(string(respBytes), formatMessage(`
GET /TestWWWFormUrlencoded HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
Content-Length: 16
Content-Type: application/x-www-form-urlencoded
User-Agent: Go-http-client/1.1
age=27&name=nimo`))
}
}
func TestJSON(t *testing.T) {
as := gtest.NewAS(t)
data := testserver.Data{
Method: "POST",
Path: "/TestJSON",
Func: func(w http.ResponseWriter, r *http.Request) {
testserver.Send(w, `{"name":"nimoc","age":18}`)
},
}
testserver.Add(data)
c := greq.New(greq.Config{})
type RespData struct {
Name string `json:"name"`
Age int `json:"age"`
}
var respData RespData
statusCode, err := c.Send(context.TODO(), greq.Method(data.Method), hosturl(data.Path), greq.Request{}, greq.Response{
JSON: greq.BindJSON(&respData),
})
as.NoError(err)
as.Equal(statusCode, 200)
as.Equal(respData, RespData{
Name: "nimoc",
Age: 18,
})
}
type UploadPhoto struct {
Photo string
}
type FormData struct {
Name string
File string
UploadPhoto
}
func (data FormData) FormData(bufferData *bytes.Buffer) (*multipart.Writer, error) {
write := multipart.NewWriter(bufferData)
var err error
err = write.WriteField("name", data.Name) ; if err != nil {return nil, err}
{
fileField := "file"
file, err := os.OpenFile(data.File,os.O_RDONLY, 0666) ; if err != nil {return nil, err}
defer file.Close()
fileWrite, err := write.CreateFormFile(fileField, file.Name()) ; if err != nil {return nil, err}
_, err = io.Copy(fileWrite, file) ; if err != nil {return nil, err}
}
{
fileField := "photo"
file, err := os.OpenFile(data.Photo,os.O_RDONLY, 0666) ; if err != nil {return nil, err}
defer file.Close()
fileWrite, err := write.CreateFormFile(fileField, file.Name()) ; if err != nil {return nil, err}
_, err = io.Copy(fileWrite, file) ; if err != nil {return nil, err}
}
return write, nil
}
func TestFormData(t *testing.T) {
as := gtest.NewAS(t)
_=as
c := greq.New(greq.Config{})
data := testserver.Data{
Method: "POST",
Path: "/TestFormData",
Func: func(w http.ResponseWriter, r *http.Request) {
testserver.Send(w, greq.HttpMessage(*r))
},
}
testserver.Add(data)
form := FormData {
Name: "nimo",
File: "mock/json-1.json",
UploadPhoto: UploadPhoto{
"mock/json-1.json",
},
}
var respBytes []byte
statusCode, err := c.Send(context.TODO(), greq.Method(data.Method), hosturl(data.Path), greq.Request{
FormData: form,
}, greq.Response{
Bytes: greq.BindBytes(&respBytes),
}) ; ge.Check(err)
as.Equal(statusCode, 200)
as.Equal(formatFormDataMessage(string(respBytes)), formatMessage(`
POST /TestFormData HTTP/1.1
Host: 127.0.0.1:2421
Accept-Encoding: gzip
Content-Length: 654
Content-Type: multipart/form-data; boundary=testboundarytestboundarytestboundarytestboundarytestboundary
User-Agent: Go-http-client/1.1
--testboundarytestboundarytestboundarytestboundarytestboundary
Content-Disposition: form-data; name="name"
nimo
--testboundarytestboundarytestboundarytestboundarytestboundary
Content-Disposition: form-data; name="file"; filename="mock/json-1.json"
Content-Type: application/octet-stream
{"name": "nimoc","github": "http://github.com/nimoc"}
--testboundarytestboundarytestboundarytestboundarytestboundary
Content-Disposition: form-data; name="photo"; filename="mock/json-1.json"
Content-Type: application/octet-stream
{"name": "nimoc","github": "http://github.com/nimoc"}
--testboundarytestboundarytestboundarytestboundarytestboundary--`) + "\r\n")
}