-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.go
277 lines (238 loc) · 7.66 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
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
package spectest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/textproto"
"os"
"path/filepath"
)
// Request is the user defined request that will be invoked on the handler under test
type Request struct {
specTest *SpecTest
interceptor Intercept
method string
url string
body string
query map[string][]string
queryCollection map[string][]string
headers map[string][]string
formData map[string][]string
multipartBody *bytes.Buffer
multipart *multipart.Writer
cookies []*Cookie
basicAuth string
context context.Context
}
// newRequest creates a new request
func newRequest(s *SpecTest) *Request {
return &Request{
specTest: s,
query: map[string][]string{},
queryCollection: map[string][]string{},
headers: map[string][]string{},
formData: map[string][]string{},
cookies: []*Cookie{},
}
}
// GraphQLRequestBody represents the POST request body as per the GraphQL spec
type GraphQLRequestBody struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
OperationName string `json:"operation_name,omitempty"`
}
// URL is a builder method for setting the url of the request
func (r *Request) URL(url string) *Request {
r.url = url
return r
}
// URLf is a builder method for setting the url of the request and supports a formatter
func (r *Request) URLf(format string, args ...interface{}) *Request {
r.url = fmt.Sprintf(format, args...)
return r
}
// Body is a builder method to set the request body
func (r *Request) Body(b string) *Request {
r.body = b
return r
}
// Bodyf sets the request body and supports a formatter
func (r *Request) Bodyf(format string, args ...interface{}) *Request {
r.body = fmt.Sprintf(format, args...)
return r
}
// BodyFromFile is a builder method to set the request body
func (r *Request) BodyFromFile(f string) *Request {
b, err := os.ReadFile(filepath.Clean(f))
if err != nil {
r.specTest.t.Fatal(err)
}
r.body = string(b)
return r
}
// JSON is a convenience method for setting the request body and content type header as "application/json".
// If v is not a string or []byte it will marshall the provided variable as json
func (r *Request) JSON(v interface{}) *Request {
switch x := v.(type) {
case string:
r.body = x
case []byte:
r.body = string(x)
default:
asJSON, err := json.Marshal(x)
if err != nil {
r.specTest.t.Fatal(err)
return nil
}
r.body = string(asJSON)
}
r.ContentType("application/json")
return r
}
// JSONFromFile is a convenience method for setting the request body and content type header as "application/json"
func (r *Request) JSONFromFile(f string) *Request {
r.BodyFromFile(f)
r.ContentType("application/json")
return r
}
// GraphQLQuery is a convenience method for building a graphql POST request
func (r *Request) GraphQLQuery(query string, variables ...map[string]interface{}) *Request {
q := GraphQLRequestBody{
Query: query,
}
if len(variables) > 0 {
q.Variables = variables[0]
}
return r.GraphQLRequest(q)
}
// GraphQLRequest builds a graphql POST request
func (r *Request) GraphQLRequest(body GraphQLRequestBody) *Request {
r.ContentType("application/json")
data, err := json.Marshal(body)
if err != nil {
r.specTest.t.Fatal(err)
}
r.body = string(data)
return r
}
// Query is a convenience method to add a query parameter to the request.
func (r *Request) Query(key, value string) *Request {
r.query[key] = append(r.query[key], value)
return r
}
// QueryParams is a builder method to set the request query parameters.
// This can be used in combination with request.QueryCollection
func (r *Request) QueryParams(params map[string]string) *Request {
for k, v := range params {
r.query[k] = append(r.query[k], v)
}
return r
}
// QueryCollection is a builder method to set the request query parameters
// This can be used in combination with request.Query
func (r *Request) QueryCollection(q map[string][]string) *Request {
r.queryCollection = q
return r
}
// Header is a builder method to set the request headers
func (r *Request) Header(key, value string) *Request {
normalizedKey := textproto.CanonicalMIMEHeaderKey(key)
r.headers[normalizedKey] = append(r.headers[normalizedKey], value)
return r
}
// Headers is a builder method to set the request headers
func (r *Request) Headers(headers map[string]string) *Request {
for k, v := range headers {
normalizedKey := textproto.CanonicalMIMEHeaderKey(k)
r.headers[normalizedKey] = append(r.headers[normalizedKey], v)
}
return r
}
// ContentType is a builder method to set the Content-Type header of the request
func (r *Request) ContentType(contentType string) *Request {
normalizedKey := textproto.CanonicalMIMEHeaderKey("Content-Type")
r.headers[normalizedKey] = []string{contentType}
return r
}
// Cookie is a convenience method for setting a single request cookies by name and value
func (r *Request) Cookie(name, value string) *Request {
r.cookies = append(r.cookies, &Cookie{name: &name, value: &value})
return r
}
// Cookies is a builder method to set the request cookies
func (r *Request) Cookies(c ...*Cookie) *Request {
r.cookies = append(r.cookies, c...)
return r
}
// BasicAuth is a builder method to sets basic auth on the request.
func (r *Request) BasicAuth(username, password string) *Request {
r.basicAuth = fmt.Sprintf("%s:%s", username, password)
return r
}
// WithContext is a builder method to set a context on the request
func (r *Request) WithContext(ctx context.Context) *Request {
r.context = ctx
return r
}
// FormData is a builder method to set the body form data
// Also sets the content type of the request to application/x-www-form-urlencoded
func (r *Request) FormData(name string, values ...string) *Request {
defer r.checkCombineFormDataWithMultipart()
r.ContentType("application/x-www-form-urlencoded")
r.formData[name] = append(r.formData[name], values...)
return r
}
// MultipartFormData is a builder method to set the field in multipart form data
// Also sets the content type of the request to multipart/form-data
func (r *Request) MultipartFormData(name string, values ...string) *Request {
defer r.checkCombineFormDataWithMultipart()
r.setMultipartWriter()
for _, value := range values {
if err := r.multipart.WriteField(name, value); err != nil {
r.specTest.t.Fatal(err)
}
}
return r
}
// MultipartFile is a builder method to set the file in multipart form data
// Also sets the content type of the request to multipart/form-data
func (r *Request) MultipartFile(name string, ff ...string) *Request {
defer r.checkCombineFormDataWithMultipart()
r.setMultipartWriter()
for _, f := range ff {
func() {
file, err := os.Open(filepath.Clean(f))
if err != nil {
r.specTest.t.Fatal(err)
}
defer file.Close() //nolint
part, err := r.multipart.CreateFormFile(name, filepath.Base(file.Name()))
if err != nil {
r.specTest.t.Fatal(err)
}
if _, err = io.Copy(part, file); err != nil {
r.specTest.t.Fatal(err)
}
}()
}
return r
}
func (r *Request) setMultipartWriter() {
if r.multipart == nil {
r.multipartBody = &bytes.Buffer{}
r.multipart = multipart.NewWriter(r.multipartBody)
}
}
func (r *Request) checkCombineFormDataWithMultipart() {
if r.multipart != nil && len(r.formData) > 0 {
r.specTest.t.Fatal("FormData (application/x-www-form-urlencoded) and MultiPartFormData(multipart/form-data) cannot be combined")
}
}
// Expect marks the request spec as complete and following code will define the expected response
func (r *Request) Expect(t TestingT) *Response {
r.specTest.t = t
return r.specTest.response
}