-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtdhttpmock.go
274 lines (256 loc) · 7.86 KB
/
tdhttpmock.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
// Copyright (c) 2022-2023, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
package tdhttpmock
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil" //nolint: staticcheck
"net/http"
"reflect"
"github.com/jarcoal/httpmock"
"github.com/maxatome/go-testdeep/td"
)
func init() {
httpmock.IgnoreMatcherHelper()
}
var interfaceType = reflect.TypeOf((*any)(nil)).Elem()
func marshaledBody(
acceptEmptyBody bool,
unmarshal func([]byte, any) error,
expectedBody any,
) httpmock.MatcherFunc {
return func(req *http.Request) bool {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return false
}
if !acceptEmptyBody && len(body) == 0 {
return false
}
var bodyType reflect.Type
// If expectedBody is a TestDeep operator, try to ask it the type
// behind it.
if op, ok := expectedBody.(td.TestDeep); ok {
bodyType = op.TypeBehind()
} else {
bodyType = reflect.TypeOf(expectedBody)
}
// As the expected body type cannot be guessed, try to
// unmarshal in an any
if bodyType == nil {
bodyType = interfaceType
}
bodyPtr := reflect.New(bodyType)
if unmarshal(body, bodyPtr.Interface()) != nil {
return false
}
return td.EqDeeply(bodyPtr.Elem().Interface(), expectedBody)
}
}
// Body returns an [httpmock.Matcher] matching request body against
// expectedBody. expectedBody can be a []byte, a string or a
// [td.TestDeep] operator.
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.Body("OK!\n"),
// httpmock.NewStringResponder(200, "OK"))
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.Body(td.Re(`\d+ test`)),
// httpmock.NewStringResponder(200, "OK test"))
//
// The name of the returned [httpmock.Matcher] is auto-generated (see
// [httpmock.NewMatcher]). To name it explicitly, use
// [httpmock.Matcher.WithName] as in:
//
// tdhttpmock.Body("OK!\n").WithName("01-body-OK")
func Body(expectedBody any) httpmock.Matcher {
return httpmock.NewMatcher("",
marshaledBody(true,
func(body []byte, target any) error {
switch target := target.(type) {
case *string:
*target = string(body)
case *[]byte:
*target = body
case *any:
*target = body
default:
// marshaledBody always calls us with target as a pointer
return fmt.Errorf(
"Body only accepts expectedBody be a []byte, a string or a TestDeep operator allowing to match these types, but not type %s",
reflect.TypeOf(target).Elem())
}
return nil
},
expectedBody))
}
// JSONBody returns an [httpmock.Matcher] expecting a JSON request body
// that can be [json.Unmarshal]'ed and that matches expectedBody.
// expectedBody can be any type one can [json.Unmarshal] into, or a
// [td.TestDeep] operator.
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.JSONBody(Person{
// ID: 42,
// Name: "Bob",
// Age: 26,
// }),
// httpmock.NewStringResponder(200, "OK bob"))
//
// The same using [td.JSON]:
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.JSONBody(td.JSON(`
// {
// "id": NotZero(),
// "name": "Bob",
// "age": 26
// }`)),
// httpmock.NewStringResponder(200, "OK bob"))
//
// Note also the existence of [td.JSONPointer]:
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.JSONBody(td.JSONPointer("/name", "Bob")),
// httpmock.NewStringResponder(200, "OK bob"))
//
// The name of the returned [httpmock.Matcher] is auto-generated (see
// [httpmock.NewMatcher]). To name it explicitly, use
// [httpmock.Matcher.WithName] as in:
//
// tdhttpmock.JSONBody(td.JSONPointer("/name", "Bob")).WithName("01-bob")
func JSONBody(expectedBody any) httpmock.Matcher {
return httpmock.NewMatcher("",
marshaledBody(false, json.Unmarshal, expectedBody))
}
// XMLBody returns an [httpmock.Matcher] expecting an XML request
// body that can be [xml.Unmarshal]'ed and that matches
// expectedBody. expectedBody can be any type one can [xml.Unmarshal]
// into, or a [td.TestDeep] operator.
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.XMLBody(Person{
// ID: 42,
// Name: "Bob",
// Age: 26,
// }),
// httpmock.NewStringResponder(200, "OK bob"))
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.XMLBody(td.SStruct(
// Person{
// Name: "Bob",
// Age: 26,
// },
// td.StructFields{
// "ID": td.NotZero(),
// })),
// httpmock.NewStringResponder(200, "OK bob"))
//
// The name of the returned [httpmock.Matcher] is auto-generated (see
// [httpmock.NewMatcher]). To name it explicitly, use
// [httpmock.Matcher.WithName] as in:
//
// tdhttpmock.XMLBody(td.Struct(Person{Name: "Bob"})).WithName("01-bob")
func XMLBody(expectedBody any) httpmock.Matcher {
return httpmock.NewMatcher("",
marshaledBody(false, xml.Unmarshal, expectedBody))
}
// Header returns an [httpmock.Matcher] matching request header against
// expectedHeader. expectedHeader can be a [http.Header] or a
// [td.TestDeep] operator. Keep in mind that if it is a [http.Header],
// it has to match exactly the response header. Often only the
// presence of a header key is needed:
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.Header(td.ContainsKey("X-Custom")),
// httpmock.NewStringResponder(200, "OK custom"))
//
// or some specific key, value pairs:
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.Header(td.SuperMapOf(
// http.Header{
// "X-Account": []string{"Bob"},
// },
// td.MapEntries{
// "X-Token": td.Bag(td.Re(`^[a-z0-9-]{32}\z`)),
// },
// )),
// httpmock.NewStringResponder(200, "OK account"))
//
// The name of the returned [httpmock.Matcher] is auto-generated (see
// [httpmock.NewMatcher]). To name it explicitly, use
// [httpmock.Matcher.WithName] as in:
//
// tdhttpmock.Header(td.ContainsKey("X-Custom")).WithName("01-header-custom")
func Header(expectedHader any) httpmock.Matcher {
return httpmock.NewMatcher("",
func(req *http.Request) bool {
return td.EqDeeply(req.Header, td.Lax(expectedHader))
})
}
// Cookies returns an [httpmock.Matcher] matching request cookies
// against expectedCookies. expectedCookies can be a [][*http.Cookie]
// or a [td.TestDeep] operator. Keep in mind that if it is a
// [][*http.Cookie], it has to match exactly the response
// cookies. Often only the presence of a cookie key is needed:
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.Cookies(td.SuperBagOf(td.Smuggle("Name", "cookie_session"))),
// httpmock.NewStringResponder(200, "OK session"))
//
// To make tests easier, [http.Cookie.Raw] and [http.Cookie.RawExpires] fields
// of each [*http.Cookie] are zeroed before doing the comparison. So no need
// to fill them when comparing against a simple literal as in:
//
// httpmock.RegisterMatcherResponder(
// http.MethodPost,
// "/test",
// tdhttpmock.Cookies([]*http.Cookies{
// {Name: "cookieName1", Value: "cookieValue1"},
// {Name: "cookieName2", Value: "cookieValue2"},
// }),
// httpmock.NewStringResponder(200, "OK cookies"))
//
// The name of the returned [httpmock.Matcher] is auto-generated (see
// [httpmock.NewMatcher]). To name it explicitly, use
// [httpmock.Matcher.WithName] as in:
//
// tdhttpmock.Cookies([]*http.Cookies{}).WithName("01-cookies")
func Cookies(expectedCookies any) httpmock.Matcher {
return httpmock.NewMatcher("",
func(req *http.Request) bool {
// Empty Raw* fields to make comparisons easier
cookies := req.Cookies()
for _, c := range cookies {
c.RawExpires, c.Raw = "", ""
}
return td.EqDeeply(cookies, td.Lax(expectedCookies))
})
}