/
request.go
121 lines (99 loc) · 2.44 KB
/
request.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
package testutil
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"app/api/config"
"app/api/endpoint"
)
// Request is a test request.
type Request struct {
// Request is cleared before use.
Request *http.Request
// Header clears after use.
Header http.Header
// SkipMiddleware resets to false after use.
SkipMiddleware bool
// SkipRoutes resets to false after use.
SkipRoutes bool
}
// NewRequest returns a new test request.
func NewRequest() *Request {
return &Request{
Request: new(http.Request),
Header: make(http.Header),
SkipMiddleware: false,
SkipRoutes: false,
}
}
// SendForm is a helper to quickly make a form request.
func (tr *Request) SendForm(t *testing.T, core endpoint.Core, method string, target string,
v url.Values) *httptest.ResponseRecorder {
if !tr.SkipRoutes {
// Load the routes.
config.LoadRoutes(core)
}
var body io.Reader
if v != nil {
body = strings.NewReader(v.Encode())
}
tr.Request = httptest.NewRequest(method, target, body)
tr.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for k, v := range tr.Header {
tr.Request.Header.Set(k, v[0])
}
// Reset the header values.
tr.Header = make(http.Header)
w := httptest.NewRecorder()
if !tr.SkipMiddleware {
config.Middleware(core).ServeHTTP(w, tr.Request)
} else {
tr.SkipMiddleware = false
core.Router.ServeHTTP(w, tr.Request)
}
return w
}
// SendJSON is a helper to quickly make a JSON request.
func (tr *Request) SendJSON(t *testing.T, core endpoint.Core, method string, target string,
v url.Values) *httptest.ResponseRecorder {
if !tr.SkipRoutes {
// Load the routes.
config.LoadRoutes(core)
}
var body io.Reader
if v != nil {
body = strings.NewReader(ToJSON(v))
}
tr.Request = httptest.NewRequest(method, target, body)
tr.Header.Set("Content-Type", "application/json")
for k, v := range tr.Header {
tr.Request.Header.Set(k, v[0])
}
// Reset the header values.
tr.Header = make(http.Header)
w := httptest.NewRecorder()
if !tr.SkipMiddleware {
config.Middleware(core).ServeHTTP(w, tr.Request)
} else {
tr.SkipMiddleware = false
core.Router.ServeHTTP(w, tr.Request)
}
return w
}
// ToJSON converts a url.Values to a JSON string.
func ToJSON(values url.Values) string {
m := make(map[string]string)
for k, v := range values {
if len(v) > 0 {
m[k] = v[0]
} else {
m[k] = ""
}
}
js, _ := json.Marshal(m)
return string(js)
}