forked from oapi-codegen/oapi-codegen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request_helpers.go
194 lines (164 loc) · 5.29 KB
/
request_helpers.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
// Copyright 2019 DeepMap, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package testutil
// This is a set of fluent request builders for tests, which help us to
// simplify constructing and unmarshaling test objects. For example, to post
// a body and return a response, you would do something like:
//
// var body RequestBody
// var response ResponseBody
// t is *testing.T, from a unit test
// e is *echo.Echo
// response := NewRequest().Post("/path").WithJsonBody(body).Go(t, e)
// err := response.UnmarshalBodyToObject(&response)
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/labstack/echo/v4"
)
func NewRequest() *RequestBuilder {
return &RequestBuilder{
Headers: make(map[string]string),
}
}
// This structure caches request settings as we build up the request.
type RequestBuilder struct {
Method string
Path string
Headers map[string]string
Body []byte
Error error
Cookies []*http.Cookie
}
// Path operations
func (r *RequestBuilder) WithMethod(method string, path string) *RequestBuilder {
r.Method = method
r.Path = path
return r
}
func (r *RequestBuilder) Get(path string) *RequestBuilder {
return r.WithMethod("GET", path)
}
func (r *RequestBuilder) Post(path string) *RequestBuilder {
return r.WithMethod("POST", path)
}
func (r *RequestBuilder) Put(path string) *RequestBuilder {
return r.WithMethod("PUT", path)
}
func (r *RequestBuilder) Delete(path string) *RequestBuilder {
return r.WithMethod("DELETE", path)
}
// Header operations
func (r *RequestBuilder) WithHeader(header, value string) *RequestBuilder {
r.Headers[header] = value
return r
}
func (r *RequestBuilder) WithContentType(value string) *RequestBuilder {
return r.WithHeader("Content-Type", value)
}
func (r *RequestBuilder) WithJsonContentType() *RequestBuilder {
return r.WithContentType("application/json")
}
func (r *RequestBuilder) WithAccept(value string) *RequestBuilder {
return r.WithHeader("Accept", value)
}
func (r *RequestBuilder) WithAcceptJson() *RequestBuilder {
return r.WithAccept("application/json")
}
func (r *RequestBuilder) WithAcceptScim() *RequestBuilder {
return r.WithAccept("application/scim+json")
}
// Request body operations
func (r *RequestBuilder) WithBody(body []byte) *RequestBuilder {
r.Body = body
return r
}
// This function takes an object as input, marshals it to JSON, and sends it
// as the body with Content-Type: application/json
func (r *RequestBuilder) WithJsonBody(obj interface{}) *RequestBuilder {
var err error
r.Body, err = json.Marshal(obj)
if err != nil {
r.Error = fmt.Errorf("failed to marshal json object: %s", err)
}
return r.WithJsonContentType()
}
// Cookie operations
func (r *RequestBuilder) WithCookie(c *http.Cookie) *RequestBuilder {
r.Cookies = append(r.Cookies, c)
return r
}
func (r *RequestBuilder) WithCookieNameValue(name, value string) *RequestBuilder {
return r.WithCookie(&http.Cookie{Name: name, Value: value})
}
// This function performs the request, it takes a pointer to a testing context
// to print messages, and a pointer to an echo context for request handling.
func (r *RequestBuilder) Go(t *testing.T, e *echo.Echo) *CompletedRequest {
if r.Error != nil {
// Fail the test if we had an error
t.Errorf("error constructing request: %s", r.Error)
return nil
}
var bodyReader io.Reader
if r.Body != nil {
bodyReader = bytes.NewReader(r.Body)
}
req := httptest.NewRequest(r.Method, r.Path, bodyReader)
for h, v := range r.Headers {
req.Header.Add(h, v)
}
for _, c := range r.Cookies {
req.AddCookie(c)
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
return &CompletedRequest{
Recorder: rec,
}
}
// This is the result of calling Go() on the request builder. We're wrapping the
// ResponseRecorder with some nice helper functions.
type CompletedRequest struct {
Recorder *httptest.ResponseRecorder
}
// This function takes a destination object as input, and unmarshals the object
// in the response based on the Content-Type header.
func (c *CompletedRequest) UnmarshalBodyToObject(obj interface{}) error {
ctype := c.Recorder.Header().Get("Content-Type")
// Content type can have an annotation after ;
contentParts := strings.Split(ctype, ";")
switch strings.TrimSpace(contentParts[0]) {
case "application/json":
return json.Unmarshal(c.Recorder.Body.Bytes(), obj)
case "application/scim+json":
return json.Unmarshal(c.Recorder.Body.Bytes(), obj)
default:
return fmt.Errorf("no Content-Type on response")
}
}
// This function assumes that the response contains JSON and unmarshals it
// into the specified object.
func (c *CompletedRequest) UnmarshalJsonToObject(obj interface{}) error {
return json.Unmarshal(c.Recorder.Body.Bytes(), obj)
}
// Shortcut for response code
func (c *CompletedRequest) Code() int {
return c.Recorder.Code
}