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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
|
// Copyright (c) 2019, 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 tdhttp
import (
"encoding/json"
"encoding/xml"
"fmt"
"net/http"
"reflect"
"testing"
"github.com/maxatome/go-testdeep/helpers/tdutil"
"github.com/maxatome/go-testdeep/internal/trace"
"github.com/maxatome/go-testdeep/td"
)
func init() {
trace.IgnorePackage()
}
// Response is used by Cmp*Response functions to make the HTTP
// response match easier. Each field, can be a [td.TestDeep] operator
// as well as the exact expected value.
type Response struct {
Status any // is the expected status (ignored if nil)
Header any // is the expected header (ignored if nil)
Cookies any // is the expected cookies (ignored if nil)
Body any // is the expected body (expected to be empty if nil)
}
func cmpMarshaledResponse(tb testing.TB,
req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
acceptEmptyBody bool,
unmarshal func([]byte, any) error,
expectedResp Response,
args ...any,
) bool {
tb.Helper()
if testName := tdutil.BuildTestName(args...); testName != "" {
tb.Log(testName)
}
t := td.NewT(tb)
defer t.AnchorsPersistTemporarily()()
ta := NewTestAPI(t, http.HandlerFunc(handler)).Request(req)
// Check status, nil = ignore
if expectedResp.Status != nil {
ta.CmpStatus(expectedResp.Status)
}
// Check header, nil = ignore
if expectedResp.Header != nil {
ta.CmpHeader(expectedResp.Header)
}
// Check cookie, nil = ignore
if expectedResp.Cookies != nil {
ta.CmpCookies(expectedResp.Cookies)
}
if expectedResp.Body == nil {
ta.NoBody()
} else {
ta.cmpMarshaledBody(acceptEmptyBody, unmarshal, expectedResp.Body)
}
return !ta.Failed()
}
// CmpMarshaledResponse is the base function used by some others in
// tdhttp package. req is launched against handler. The response body
// is unmarshaled using unmarshal. The response is then tested against
// expectedResp.
//
// args... are optional and allow to name the test, a t.Log() done
// before starting any test. If len(args) > 1 and the first item of
// args is a string and contains a '%' rune then [fmt.Fprintf] is used
// to compose the name, else args are passed to [fmt.Fprint].
//
// It returns true if the tests succeed, false otherwise.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpMarshaledResponse(t testing.TB,
req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
unmarshal func([]byte, any) error,
expectedResp Response,
args ...any,
) bool {
t.Helper()
return cmpMarshaledResponse(t, req, handler, false, unmarshal, expectedResp, args...)
}
// CmpResponse is used to match a []byte or string response body. req
// is launched against handler. If expectedResp.Body is non-nil, the
// response body is converted to []byte or string, depending on the
// expectedResp.Body type. The response is then tested against
// expectedResp.
//
// args... are optional and allow to name the test, a t.Log() done
// before starting any test. If len(args) > 1 and the first item of
// args is a string and contains a '%' rune then [fmt.Fprintf] is used
// to compose the name, else args are passed to [fmt.Fprint].
//
// It returns true if the tests succeed, false otherwise.
//
// ok := tdhttp.CmpResponse(t,
// tdhttp.Get("/test"),
// myAPI.ServeHTTP,
// Response{
// Status: http.StatusOK,
// Header: td.ContainsKey("X-Custom-Header"),
// Body: "OK!\n",
// },
// "/test route")
//
// Response.Status, Response.Header and Response.Body fields can all
// be [td.TestDeep] operators as it is for Response.Header field
// here. Otherwise, Response.Status should be an int, Response.Header
// a [http.Header] and Response.Body a []byte or a string.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpResponse(t testing.TB,
req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
expectedResp Response,
args ...any) bool {
t.Helper()
return cmpMarshaledResponse(t,
req,
handler,
true,
func(body []byte, target any) error {
switch t := target.(type) {
case *string:
*t = string(body)
case *[]byte:
*t = body
case *any:
*t = body
default:
// cmpMarshaledBody (behind cmpMarshaledResponse) always calls
// us with target as a pointer
return fmt.Errorf(
"CmpResponse only accepts expectedResp.Body be a []byte, a string or a TestDeep operator allowing to match these types, but not type %s",
reflect.TypeOf(target).Elem())
}
return nil
},
expectedResp,
args...)
}
// CmpJSONResponse is used to match a JSON response body. req is
// launched against handler. If expectedResp.Body is non-nil, the
// response body is [json.Unmarshal]'ed. The response is then tested
// against expectedResp.
//
// args... are optional and allow to name the test, a t.Log() done
// before starting any test. If len(args) > 1 and the first item of
// args is a string and contains a '%' rune then [fmt.Fprintf] is used
// to compose the name, else args are passed to [fmt.Fprint].
//
// It returns true if the tests succeed, false otherwise.
//
// ok := tdhttp.CmpJSONResponse(t,
// tdhttp.Get("/person/42"),
// myAPI.ServeHTTP,
// Response{
// Status: http.StatusOK,
// Header: td.ContainsKey("X-Custom-Header"),
// Body: Person{
// ID: 42,
// Name: "Bob",
// Age: 26,
// },
// },
// "/person/{id} route")
//
// Response.Status, Response.Header and Response.Body fields can all
// be [td.TestDeep] operators as it is for Response.Header field
// here. Otherwise, Response.Status should be an int, Response.Header
// a [http.Header] and Response.Body any type one can
// [json.Unmarshal] into.
//
// If Response.Status and Response.Header are omitted (or nil), they
// are not tested.
//
// If Response.Body is omitted (or nil), it means the body response has to be
// empty. If you want to ignore the body response, use [td.Ignore]
// explicitly.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpJSONResponse(t testing.TB,
req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
expectedResp Response,
args ...any,
) bool {
t.Helper()
return CmpMarshaledResponse(t,
req,
handler,
json.Unmarshal,
expectedResp,
args...)
}
// CmpXMLResponse is used to match an XML response body. req
// is launched against handler. If expectedResp.Body is
// non-nil, the response body is [xml.Unmarshal]'ed. The response is
// then tested against expectedResp.
//
// args... are optional and allow to name the test, a t.Log() done
// before starting any test. If len(args) > 1 and the first item of
// args is a string and contains a '%' rune then [fmt.Fprintf] is used
// to compose the name, else args are passed to [fmt.Fprint].
//
// It returns true if the tests succeed, false otherwise.
//
// ok := tdhttp.CmpXMLResponse(t,
// tdhttp.Get("/person/42"),
// myAPI.ServeHTTP,
// Response{
// Status: http.StatusOK,
// Header: td.ContainsKey("X-Custom-Header"),
// Body: Person{
// ID: 42,
// Name: "Bob",
// Age: 26,
// },
// },
// "/person/{id} route")
//
// Response.Status, Response.Header and Response.Body fields can all
// be [td.TestDeep] operators as it is for Response.Header field
// here. Otherwise, Response.Status should be an int, Response.Header
// a [http.Header] and Response.Body any type one can [xml.Unmarshal]
// into.
//
// If Response.Status and Response.Header are omitted (or nil), they
// are not tested.
//
// If Response.Body is omitted (or nil), it means the body response
// has to be empty. If you want to ignore the body response, use
// [td.Ignore] explicitly.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpXMLResponse(t testing.TB,
req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
expectedResp Response,
args ...any,
) bool {
t.Helper()
return CmpMarshaledResponse(t,
req,
handler,
xml.Unmarshal,
expectedResp,
args...)
}
// CmpMarshaledResponseFunc returns a function ready to be used with
// [testing.T.Run], calling [CmpMarshaledResponse] behind the scene. As it
// is intended to be used in conjunction with [testing.T.Run] which
// names the sub-test, the test name part (args...) is voluntary
// omitted.
//
// t.Run("Subtest name", tdhttp.CmpMarshaledResponseFunc(
// tdhttp.Get("/text"),
// mux.ServeHTTP,
// tdhttp.Response{
// Status: http.StatusOK,
// }))
//
// See [CmpMarshaledResponse] for details.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpMarshaledResponseFunc(req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
unmarshal func([]byte, any) error,
expectedResp Response) func(t *testing.T) {
return func(t *testing.T) {
t.Helper()
CmpMarshaledResponse(t, req, handler, unmarshal, expectedResp)
}
}
// CmpResponseFunc returns a function ready to be used with
// [testing.T.Run], calling [CmpResponse] behind the scene. As it is
// intended to be used in conjunction with [testing.T.Run] which names
// the sub-test, the test name part (args...) is voluntary omitted.
//
// t.Run("Subtest name", tdhttp.CmpResponseFunc(
// tdhttp.Get("/text"),
// mux.ServeHTTP,
// tdhttp.Response{
// Status: http.StatusOK,
// }))
//
// See [CmpResponse] documentation for details.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpResponseFunc(req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
expectedResp Response) func(t *testing.T) {
return func(t *testing.T) {
t.Helper()
CmpResponse(t, req, handler, expectedResp)
}
}
// CmpJSONResponseFunc returns a function ready to be used with
// [testing.T.Run], calling [CmpJSONResponse] behind the scene. As it is
// intended to be used in conjunction with [testing.T.Run] which names
// the sub-test, the test name part (args...) is voluntary omitted.
//
// t.Run("Subtest name", tdhttp.CmpJSONResponseFunc(
// tdhttp.Get("/json"),
// mux.ServeHTTP,
// tdhttp.Response{
// Status: http.StatusOK,
// Body: JResp{Comment: "expected comment!"},
// }))
//
// See [CmpJSONResponse] documentation for details.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpJSONResponseFunc(req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
expectedResp Response) func(t *testing.T) {
return func(t *testing.T) {
t.Helper()
CmpJSONResponse(t, req, handler, expectedResp)
}
}
// CmpXMLResponseFunc returns a function ready to be used with
// [testing.T.Run], calling [CmpXMLResponse] behind the scene. As it is
// intended to be used in conjunction with [testing.T.Run] which names
// the sub-test, the test name part (args...) is voluntary omitted.
//
// t.Run("Subtest name", tdhttp.CmpXMLResponseFunc(
// tdhttp.Get("/xml"),
// mux.ServeHTTP,
// tdhttp.Response{
// Status: http.StatusOK,
// Body: JResp{Comment: "expected comment!"},
// }))
//
// See [CmpXMLResponse] documentation for details.
//
// See [TestAPI] type and its methods for more flexible tests.
func CmpXMLResponseFunc(req *http.Request,
handler func(w http.ResponseWriter, r *http.Request),
expectedResp Response) func(t *testing.T) {
return func(t *testing.T) {
t.Helper()
CmpXMLResponse(t, req, handler, expectedResp)
}
}
|