-
Notifications
You must be signed in to change notification settings - Fork 19
/
utils_test.go
92 lines (74 loc) · 1.92 KB
/
utils_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
package gongular
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"net/url"
"github.com/stretchr/testify/assert"
)
func respBytes(t *testing.T, e *Engine, path, method string) (*httptest.ResponseRecorder, []byte) {
resp := httptest.NewRecorder()
uri := path
req, err := http.NewRequest(method, uri, nil)
if err != nil {
t.Fatal(err)
}
e.GetHandler().ServeHTTP(resp, req)
p, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fail()
return resp, nil
}
return resp, p
}
func respWrap(t *testing.T, e *Engine, path, method string, reader io.Reader) (*httptest.ResponseRecorder, string) {
resp := httptest.NewRecorder()
uri := path
req, err := http.NewRequest(method, uri, reader)
if err != nil {
t.Fatal(err)
}
e.GetHandler().ServeHTTP(resp, req)
p, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fail()
return resp, ""
}
return resp, string(p)
}
func get(t *testing.T, e *Engine, path string) (*httptest.ResponseRecorder, string) {
return respWrap(t, e, path, "GET", nil)
}
func post(t *testing.T, e *Engine, path string, body interface{}) (*httptest.ResponseRecorder, string) {
if body != nil {
b, err := json.Marshal(body)
assert.NoError(t, err)
return respWrap(t, e, path, "POST", bytes.NewBuffer(b))
}
return respWrap(t, e, path, "POST", nil)
}
func postForm(t *testing.T, e *Engine, path string, values url.Values) (*httptest.ResponseRecorder, string) {
resp := httptest.NewRecorder()
uri := path
req, err := http.NewRequest(http.MethodPost, uri, bytes.NewBufferString(values.Encode()))
if err != nil {
t.Fatal(err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
e.GetHandler().ServeHTTP(resp, req)
p, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fail()
return resp, ""
}
return resp, string(p)
}
func newEngineTest() *Engine {
e := NewEngine()
e.SetRouteCallback(NoOpRouteCallback)
return e
}