Debian Codegraph @

helpers/tdhttp/test_api.go

raw
1 // Copyright (c) 2020-2022, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package tdhttp
8
9 import (
10 "encoding/json"
11 "encoding/xml"
12 "fmt"
13 "io"
14 "net/http"
15 "net/http/httptest"
16 "net/url"
17 "reflect"
18 "runtime"
19 "strings"
20 "testing"
21 "time"
22
23 "github.com/maxatome/go-testdeep/helpers/tdhttp/internal"
24 "github.com/maxatome/go-testdeep/helpers/tdutil"
25 "github.com/maxatome/go-testdeep/internal/color"
26 "github.com/maxatome/go-testdeep/internal/ctxerr"
27 "github.com/maxatome/go-testdeep/internal/types"
28 "github.com/maxatome/go-testdeep/td"
29 )
30
31 type failed uint8
32
33 const (
34 responseFailed failed = 1 << iota
35 statusFailed
36 headerFailed
37 trailerFailed
38 cookiesFailed
39 bodyFailed
40 )
41
42 // TestAPI allows to test one HTTP API. See [NewTestAPI] function to
43 // create a new instance and get some examples of use.
44 type TestAPI struct {
45 t *td.T
46 handler http.Handler
47 name string
48
49 sentAt time.Time
50 response *httptest.ResponseRecorder
51 failed failed
52
53 // autoDumpResponse dumps the received response when a test fails.
54 autoDumpResponse bool
55 responseDumped bool
56
57 defaultHeader http.Header
58 defaultQParams url.Values
59 defaultCookies []*http.Cookie
60 defaultHook func(*http.Request) error
61 }
62
63 // NewTestAPI creates a [TestAPI] that can be used to test routes of the
64 // API behind handler.
65 //
66 // tdhttp.NewTestAPI(t, mux).
67 // Get("/test").
68 // CmpStatus(200).
69 // CmpBody("OK!")
70 //
71 // Several routes can be tested with the same instance as in:
72 //
73 // ta := tdhttp.NewTestAPI(t, mux)
74 //
75 // ta.Get("/test").
76 // CmpStatus(200).
77 // CmpBody("OK!")
78 //
79 // ta.Get("/ping").
80 // CmpStatus(200).
81 // CmpBody("pong")
82 //
83 // Note that tb can be a [*testing.T] as well as a [*td.T].
84 func NewTestAPI(tb testing.TB, handler http.Handler) *TestAPI {
85 return &TestAPI{
86 t: td.NewT(tb),
87 handler: handler,
88 }
89 }
90
91 // Clone creates a new [*TestAPI] instance copied from ta. The
92 // returned instance is independent from ta, sharing only the same
93 // handler. The header values, query params, cookies and hooks defined
94 // using [TestAPI.DefaultRequestParams] or
95 // [TestAPI.AddDefaultRequestParams] are also copied.
96 //
97 // It is typically used when the [TestAPI] instance is “reused” with
98 // additionnal configuration, as in:
99 //
100 // func TestMyAPI(t *testing.T) {
101 // ta := tdhttp.NewTestAPI(t, MyAPIHandler())
102 // taWithHeaders := ta.Clone().DefaultRequestParams("X-Header", "value")
103 //
104 // ta.Get("/test").CmpStatus(400)
105 // taWithHeaders.Get("/test").CmpStatus(200)
106 // }
107 func (ta *TestAPI) Clone() *TestAPI {
108 nta := &TestAPI{
109 t: ta.t,
110 handler: ta.handler,
111 autoDumpResponse: ta.autoDumpResponse,
112 }
113 return nta.DefaultRequestParams(
114 ta.defaultHeader, ta.defaultQParams, ta.defaultCookies, ta.defaultHook)
115 }
116
117 // With creates a new [*TestAPI] instance copied from ta, but
118 // resetting the [testing.TB] instance the tests are based on to
119 // tb. The returned instance is independent from ta, sharing only the
120 // same handler. The header values, query params, cookies and hooks
121 // defined using [TestAPI.DefaultRequestParams] or
122 // [TestAPI.AddDefaultRequestParams] are also copied.
123 //
124 // It is typically used when the [TestAPI] instance is “reused” in
125 // sub-tests, as in:
126 //
127 // func TestMyAPI(t *testing.T) {
128 // ta := tdhttp.NewTestAPI(t, MyAPIHandler())
129 //
130 // ta.Get("/test").CmpStatus(200)
131 //
132 // t.Run("errors", func (t *testing.T) {
133 // ta := ta.With(t)
134 //
135 // ta.Get("/test?bad=1").CmpStatus(400)
136 // ta.Get("/test?bad=buzz").CmpStatus(400)
137 // }
138 //
139 // ta.Get("/next").CmpStatus(200)
140 // }
141 //
142 // Note that tb can be a [*testing.T] as well as a [*td.T].
143 //
144 // See [TestAPI.Run] for another way to handle subtests.
145 func (ta *TestAPI) With(tb testing.TB) *TestAPI {
146 nta := ta.Clone()
147 nta.t = td.NewT(tb)
148 return nta
149 }
150
151 // T returns the internal instance of [*td.T].
152 func (ta *TestAPI) T() *td.T {
153 return ta.t
154 }
155
156 // Run runs f as a subtest of t called name.
157 func (ta *TestAPI) Run(name string, f func(ta *TestAPI)) bool {
158 return ta.t.Run(name, func(tdt *td.T) {
159 f(NewTestAPI(tdt, ta.handler))
160 })
161 }
162
163 // AutoDumpResponse allows to dump the HTTP response when the first
164 // error is encountered after a request.
165 //
166 // ta.AutoDumpResponse()
167 // ta.AutoDumpResponse(true)
168 //
169 // both enable the dump.
170 func (ta *TestAPI) AutoDumpResponse(enable ...bool) *TestAPI {
171 ta.autoDumpResponse = len(enable) == 0 || enable[0]
172 return ta
173 }
174
175 // DefaultRequestParams allows to define header values, query params,
176 // cookies and hooks to be automatically set for each future requests
177 // sent by [TestAPI.Request], [TestAPI.Get], [TestAPI.Head],
178 // [TestAPI.Options], [TestAPI.Post], [TestAPI.PostForm],
179 // [TestAPI.PostMultipartFormData], [TestAPI.Put], [TestAPI.Path],
180 // [TestAPI.Delete] and all derived JSON and XML methods.
181 //
182 // See [NewRequest] for all possible formats accepted in newRequestParams.
183 //
184 // The passed newRequestParams resets existing default params, so
185 // calling
186 //
187 // ta.DefaultRequestParams()
188 //
189 // discards any previously set default params.
190 //
191 // See [TestAPI.AddDefaultRequestParams] to add new default params
192 // instead of entirely replacing them.
193 //
194 // See also [TestAPI.DefaultHook] and [TestAPI.DefaultHeader].
195 func (ta *TestAPI) DefaultRequestParams(newRequestParams ...any) *TestAPI {
196 ta.t.Helper()
197 header, qp, cookies, hook, err := collateRequestParams(newRequestParams)
198 if err != nil {
199 ta.t.Fatal(err)
200 }
201 ta.defaultHeader = header
202 ta.defaultQParams = qp
203 ta.defaultCookies = cookies
204 ta.defaultHook = hook
205 return ta
206 }
207
208 // DefaultHook allows to define a hook to be automatically called for
209 // each future requests sent by [TestAPI.Request], [TestAPI.Get],
210 // [TestAPI.Head], [TestAPI.Options], [TestAPI.Post],
211 // [TestAPI.PostForm], [TestAPI.PostMultipartFormData], [TestAPI.Put],
212 // [TestAPI.Path], [TestAPI.Delete] and all derived JSON and XML
213 // methods.
214 //
215 // Previously defined hooks are discarded.
216 //
217 // See also [TestAPI.DefaultRequestParams] and
218 // [TestAPI.AddDefaultRequestParams].
219 func (ta *TestAPI) DefaultHook(hook func(*http.Request) error) *TestAPI {
220 ta.defaultHook = hook
221 return ta
222 }
223
224 // DefaultHeader allows to define header values to be automatically
225 // set for each future requests sent by [TestAPI.Request],
226 // [TestAPI.Get], [TestAPI.Head], [TestAPI.Options], [TestAPI.Post],
227 // [TestAPI.PostForm], [TestAPI.PostMultipartFormData], [TestAPI.Put],
228 // [TestAPI.Path], [TestAPI.Delete] and all derived JSON and XML
229 // methods.
230 //
231 // Previously defined header values are discarded.
232 //
233 // See also [TestAPI.DefaultRequestParams] and
234 // [TestAPI.AddDefaultRequestParams].
235 func (ta *TestAPI) DefaultHeader(h http.Header) *TestAPI {
236 header, _, _, _, _ := collateRequestParams([]any{h})
237 ta.defaultHeader = header
238 return ta
239 }
240
241 // AddDefaultRequestParams allows to define header values, query
242 // params, cookies and hooks to be automatically set for each future
243 // requests sent by [TestAPI.Request], [TestAPI.Get], [TestAPI.Head],
244 // [TestAPI.Options], [TestAPI.Post], [TestAPI.PostForm],
245 // [TestAPI.PostMultipartFormData], [TestAPI.Put], [TestAPI.Path],
246 // [TestAPI.Delete] and all derived JSON and XML methods.
247 //
248 // See [NewRequest] for all possible formats accepted in newRequestParams.
249 //
250 // The passed newRequestParams are merged with already existing
251 // default params, set by a previous call of this method or
252 // of [TestAPI.DefaultRequestParams], replacing the common ones.
253 //
254 // See [TestAPI.DefaultRequestParams] to entirely replace default
255 // params instead of modifying them.
256 //
257 // See also [TestAPI.DefaultHook] and [TestAPI.DefaultHeader].
258 func (ta *TestAPI) AddDefaultRequestParams(newRequestParams ...any) *TestAPI {
259 ta.t.Helper()
260 header, qp, cookies, hook, err := collateRequestParams(newRequestParams)
261 if err != nil {
262 ta.t.Fatal(err)
263 }
264 ta.defaultHeader = mergeHeader(header, ta.defaultHeader)
265 ta.defaultQParams, _ = mergeQParams(qp, ta.defaultQParams)
266 default_cookie:
267 for _, dflt := range ta.defaultCookies {
268 for _, c := range cookies {
269 if dflt.Name == c.Name {
270 continue default_cookie
271 }
272 }
273 cookies = append(cookies, dflt)
274 }
275 ta.defaultCookies = cookies
276 ta.defaultHook = mergeHooks(hook, ta.defaultHook)
277 return ta
278 }
279
280 // Name allows to name the series of tests that follow. This name is
281 // used as a prefix for all following tests, in case of failure to
282 // qualify each test. If len(args) > 1 and the first item of args is
283 // a string and contains a '%' rune then [fmt.Fprintf] is used to
284 // compose the name, else args are passed to [fmt.Fprint].
285 func (ta *TestAPI) Name(args ...any) *TestAPI {
286 ta.name = tdutil.BuildTestName(args...)
287 if ta.name != "" {
288 ta.name += ": "
289 }
290 return ta
291 }
292
293 func mergeHeader(cur, dflt http.Header) http.Header {
294 if cur == nil && len(dflt) > 0 {
295 cur = make(http.Header, len(dflt))
296 }
297 for k, v := range dflt {
298 if _, exists := cur[k]; !exists {
299 cur[k] = append([]string(nil), v...)
300 }
301 }
302 return cur
303 }
304
305 func mergeQParams(cur, dflt url.Values) (url.Values, bool) {
306 if cur == nil && len(dflt) > 0 {
307 cur = make(url.Values, len(dflt))
308 }
309 altered := false
310 for k, v := range dflt {
311 if _, exists := cur[k]; !exists {
312 cur[k] = append([]string(nil), v...)
313 altered = true
314 }
315 }
316 return cur, altered
317 }
318
319 func mergeHooks(cur, dflt func(*http.Request) error) func(*http.Request) error {
320 if cur == nil {
321 return dflt
322 }
323 if dflt == nil {
324 return cur
325 }
326 return func(req *http.Request) error {
327 err := dflt(req)
328 if err == nil {
329 err = cur(req)
330 }
331 return err
332 }
333 }
334
335 // Request sends a new HTTP request to the tested API. Any Cmp* or
336 // [TestAPI.NoBody] methods can now be called.
337 //
338 // It merges header values, query params, cookies and hooks defined
339 // using [TestAPI.DefaultRequestParams] only if each of them does not
340 // already exist in req.
341 //
342 // Note that [TestAPI.Failed] status is reset just after this call.
343 func (ta *TestAPI) Request(req *http.Request) *TestAPI {
344 ta.t.Helper()
345 req.Header = mergeHeader(req.Header, ta.defaultHeader)
346 if len(ta.defaultQParams) > 0 && req.URL != nil {
347 qv, altered := mergeQParams(req.URL.Query(), ta.defaultQParams)
348 if altered {
349 req.URL.RawQuery = qv.Encode()
350 }
351 }
352 for _, c := range ta.defaultCookies {
353 if _, err := req.Cookie(c.Name); err != nil {
354 req.AddCookie(c)
355 }
356 }
357 if ta.defaultHook != nil {
358 if err := ta.defaultHook(req); err != nil {
359 ta.t.Fatalf("hook failed: %s", err)
360 }
361 }
362
363 ta.response = httptest.NewRecorder()
364
365 ta.failed = 0
366 ta.sentAt = time.Now().Truncate(0)
367 ta.responseDumped = false
368
369 ta.handler.ServeHTTP(ta.response, req)
370
371 return ta
372 }
373
374 func (ta *TestAPI) checkRequestSent() bool {
375 ta.t.Helper()
376
377 // If no request has been sent, display a nice error message
378 return ta.t.RootName("Request").
379 Code(ta.response != nil,
380 func(sent bool) error {
381 if sent {
382 return nil
383 }
384 return &ctxerr.Error{
385 Message: "%% not sent!",
386 Summary: ctxerr.NewSummary("A request must be sent before testing status, header, body or full response"),
387 }
388 },
389 ta.name+"request is sent")
390 }
391
392 // Failed returns true if any Cmp* or [TestAPI.NoBody] method failed since last
393 // request sending.
394 func (ta *TestAPI) Failed() bool {
395 return ta.failed != 0
396 }
397
398 // Get sends a HTTP GET to the tested API. Any Cmp* or [TestAPI.NoBody] methods
399 // can now be called.
400 //
401 // The header values, query params, cookies and hooks defined using
402 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
403 // are merged only if each of them does not already exist in
404 // newRequestParams.
405 //
406 // Note that [TestAPI.Failed] status is reset just after this call.
407 //
408 // See [NewRequest] for all possible formats accepted in newRequestParams.
409 func (ta *TestAPI) Get(target string, newRequestParams ...any) *TestAPI {
410 ta.t.Helper()
411 req, err := get(target, newRequestParams...)
412 if err != nil {
413 ta.t.Fatal(err)
414 }
415 return ta.Request(req)
416 }
417
418 // Head sends a HTTP HEAD to the tested API. Any Cmp* or
419 // [TestAPI.NoBody] methods can now be called.
420 //
421 // The header values, query params, cookies and hooks defined using
422 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
423 // are merged only if each of them does not already exist in
424 // newRequestParams.
425 //
426 // Note that [TestAPI.Failed] status is reset just after this call.
427 //
428 // See [NewRequest] for all possible formats accepted in newRequestParams.
429 func (ta *TestAPI) Head(target string, newRequestParams ...any) *TestAPI {
430 ta.t.Helper()
431 req, err := head(target, newRequestParams...)
432 if err != nil {
433 ta.t.Fatal(err)
434 }
435 return ta.Request(req)
436 }
437
438 // Options sends a HTTP OPTIONS to the tested API. Any Cmp* or
439 // [TestAPI.NoBody] methods can now be called.
440 //
441 // The header values, query params, cookies and hooks defined using
442 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
443 // are merged only if each of them does not already exist in
444 // newRequestParams.
445 //
446 // Note that [TestAPI.Failed] status is reset just after this call.
447 //
448 // See [NewRequest] for all possible formats accepted in newRequestParams.
449 func (ta *TestAPI) Options(target string, body io.Reader, newRequestParams ...any) *TestAPI {
450 ta.t.Helper()
451 req, err := options(target, body, newRequestParams...)
452 if err != nil {
453 ta.t.Fatal(err)
454 }
455 return ta.Request(req)
456 }
457
458 // Post sends a HTTP POST to the tested API. Any Cmp* or
459 // [TestAPI.NoBody] methods can now be called.
460 //
461 // The header values, query params, cookies and hooks defined using
462 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
463 // are merged only if each of them does not already exist in
464 // newRequestParams.
465 //
466 // Note that [TestAPI.Failed] status is reset just after this call.
467 //
468 // See [NewRequest] for all possible formats accepted in newRequestParams.
469 func (ta *TestAPI) Post(target string, body io.Reader, newRequestParams ...any) *TestAPI {
470 ta.t.Helper()
471 req, err := post(target, body, newRequestParams...)
472 if err != nil {
473 ta.t.Fatal(err)
474 }
475 return ta.Request(req)
476 }
477
478 // PostForm sends a HTTP POST with data's keys and values URL-encoded
479 // as the request body to the tested API. "Content-Type" header is
480 // automatically set to "application/x-www-form-urlencoded". Any Cmp*
481 // or [TestAPI.NoBody] methods can now be called.
482 //
483 // The header values, query params, cookies and hooks defined using
484 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
485 // are merged only if each of them does not already exist in
486 // newRequestParams.
487 //
488 // Note that [TestAPI.Failed] status is reset just after this call.
489 //
490 // See [NewRequest] for all possible formats accepted in newRequestParams.
491 func (ta *TestAPI) PostForm(target string, data URLValuesEncoder, newRequestParams ...any) *TestAPI {
492 ta.t.Helper()
493 req, err := postForm(target, data, newRequestParams...)
494 if err != nil {
495 ta.t.Fatal(err)
496 }
497 return ta.Request(req)
498 }
499
500 // PostMultipartFormData sends a HTTP POST multipart request, like
501 // multipart/form-data one for example. See [MultipartBody] type for
502 // details. "Content-Type" header is automatically set depending on
503 // data.MediaType (defaults to "multipart/form-data") and
504 // data.Boundary (defaults to "go-testdeep-42"). Any Cmp* or
505 // [TestAPI.NoBody] methods can now be called.
506 //
507 // The header values, query params, cookies and hooks defined using
508 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
509 // are merged only if each of them does not already exist in
510 // newRequestParams.
511 //
512 // Note that [TestAPI.Failed] status is reset just after this call.
513 //
514 // ta.PostMultipartFormData("/data",
515 // &tdhttp.MultipartBody{
516 // // "multipart/form-data" by default
517 // Parts: []*tdhttp.MultipartPart{
518 // tdhttp.NewMultipartPartString("type", "Sales"),
519 // tdhttp.NewMultipartPartFile("report", "report.json", "application/json"),
520 // },
521 // },
522 // "X-Foo", "Foo-value",
523 // "X-Zip", "Zip-value",
524 // )
525 //
526 // See [NewRequest] for all possible formats accepted in newRequestParams.
527 func (ta *TestAPI) PostMultipartFormData(target string, data *MultipartBody, newRequestParams ...any) *TestAPI {
528 ta.t.Helper()
529 req, err := postMultipartFormData(target, data, newRequestParams...)
530 if err != nil {
531 ta.t.Fatal(err)
532 }
533 return ta.Request(req)
534 }
535
536 // Put sends a HTTP PUT to the tested API. Any Cmp* or [TestAPI.NoBody] methods
537 // can now be called.
538 //
539 // The header values, query params, cookies and hooks defined using
540 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
541 // are merged only if each of them does not already exist in
542 // newRequestParams.
543 //
544 // Note that [TestAPI.Failed] status is reset just after this call.
545 //
546 // See [NewRequest] for all possible formats accepted in newRequestParams.
547 func (ta *TestAPI) Put(target string, body io.Reader, newRequestParams ...any) *TestAPI {
548 ta.t.Helper()
549 req, err := put(target, body, newRequestParams...)
550 if err != nil {
551 ta.t.Fatal(err)
552 }
553 return ta.Request(req)
554 }
555
556 // Patch sends a HTTP PATCH to the tested API. Any Cmp* or
557 // [TestAPI.NoBody] methods can now be called.
558 //
559 // The header values, query params, cookies and hooks defined using
560 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
561 // are merged only if each of them does not already exist in
562 // newRequestParams.
563 //
564 // Note that [TestAPI.Failed] status is reset just after this call.
565 //
566 // See [NewRequest] for all possible formats accepted in newRequestParams.
567 func (ta *TestAPI) Patch(target string, body io.Reader, newRequestParams ...any) *TestAPI {
568 ta.t.Helper()
569 req, err := patch(target, body, newRequestParams...)
570 if err != nil {
571 ta.t.Fatal(err)
572 }
573 return ta.Request(req)
574 }
575
576 // Delete sends a HTTP DELETE to the tested API. Any Cmp* or
577 // [TestAPI.NoBody] methods can now be called.
578 //
579 // The header values, query params, cookies and hooks defined using
580 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
581 // are merged only if each of them does not already exist in
582 // newRequestParams.
583 //
584 // Note that [TestAPI.Failed] status is reset just after this call.
585 //
586 // See [NewRequest] for all possible formats accepted in newRequestParams.
587 func (ta *TestAPI) Delete(target string, body io.Reader, newRequestParams ...any) *TestAPI {
588 ta.t.Helper()
589 req, err := del(target, body, newRequestParams...)
590 if err != nil {
591 ta.t.Fatal(err)
592 }
593 return ta.Request(req)
594 }
595
596 // NewJSONRequest sends a HTTP request with body marshaled to
597 // JSON. "Content-Type" header is automatically set to
598 // "application/json". Any Cmp* or [TestAPI.NoBody] methods can now be called.
599 //
600 // The header values, query params, cookies and hooks defined using
601 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
602 // are merged only if each of them does not already exist in
603 // newRequestParams.
604 //
605 // Note that [TestAPI.Failed] status is reset just after this call.
606 //
607 // See [NewRequest] for all possible formats accepted in newRequestParams.
608 func (ta *TestAPI) NewJSONRequest(method, target string, body any, newRequestParams ...any) *TestAPI {
609 ta.t.Helper()
610 req, err := newJSONRequest(method, target, body, newRequestParams...)
611 if err != nil {
612 ta.t.Fatal(err)
613 }
614 return ta.Request(req)
615 }
616
617 // PostJSON sends a HTTP POST with body marshaled to
618 // JSON. "Content-Type" header is automatically set to
619 // "application/json". Any Cmp* or [TestAPI.NoBody] methods can now be called.
620 //
621 // The header values, query params, cookies and hooks defined using
622 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
623 // are merged only if each of them does not already exist in
624 // newRequestParams.
625 //
626 // Note that [TestAPI.Failed] status is reset just after this call.
627 //
628 // See [NewRequest] for all possible formats accepted in newRequestParams.
629 func (ta *TestAPI) PostJSON(target string, body any, newRequestParams ...any) *TestAPI {
630 ta.t.Helper()
631 req, err := newJSONRequest(http.MethodPost, target, body, newRequestParams...)
632 if err != nil {
633 ta.t.Fatal(err)
634 }
635 return ta.Request(req)
636 }
637
638 // PutJSON sends a HTTP PUT with body marshaled to
639 // JSON. "Content-Type" header is automatically set to
640 // "application/json". Any Cmp* or [TestAPI.NoBody] methods can now be called.
641 //
642 // The header values, query params, cookies and hooks defined using
643 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
644 // are merged only if each of them does not already exist in
645 // newRequestParams.
646 //
647 // Note that [TestAPI.Failed] status is reset just after this call.
648 //
649 // See [NewRequest] for all possible formats accepted in newRequestParams.
650 func (ta *TestAPI) PutJSON(target string, body any, newRequestParams ...any) *TestAPI {
651 ta.t.Helper()
652 req, err := newJSONRequest(http.MethodPut, target, body, newRequestParams...)
653 if err != nil {
654 ta.t.Fatal(err)
655 }
656 return ta.Request(req)
657 }
658
659 // PatchJSON sends a HTTP PATCH with body marshaled to
660 // JSON. "Content-Type" header is automatically set to
661 // "application/json". Any Cmp* or [TestAPI.NoBody] methods can now be called.
662 //
663 // The header values, query params, cookies and hooks defined using
664 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
665 // are merged only if each of them does not already exist in
666 // newRequestParams.
667 //
668 // Note that [TestAPI.Failed] status is reset just after this call.
669 //
670 // See [NewRequest] for all possible formats accepted in newRequestParams.
671 func (ta *TestAPI) PatchJSON(target string, body any, newRequestParams ...any) *TestAPI {
672 ta.t.Helper()
673 req, err := newJSONRequest(http.MethodPatch, target, body, newRequestParams...)
674 if err != nil {
675 ta.t.Fatal(err)
676 }
677 return ta.Request(req)
678 }
679
680 // DeleteJSON sends a HTTP DELETE with body marshaled to
681 // JSON. "Content-Type" header is automatically set to
682 // "application/json". Any Cmp* or [TestAPI.NoBody] methods can now be called.
683 //
684 // The header values, query params, cookies and hooks defined using
685 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
686 // are merged only if each of them does not already exist in
687 // newRequestParams.
688 //
689 // Note that [TestAPI.Failed] status is reset just after this call.
690 //
691 // See [NewRequest] for all possible formats accepted in newRequestParams.
692 func (ta *TestAPI) DeleteJSON(target string, body any, newRequestParams ...any) *TestAPI {
693 ta.t.Helper()
694 req, err := newJSONRequest(http.MethodDelete, target, body, newRequestParams...)
695 if err != nil {
696 ta.t.Fatal(err)
697 }
698 return ta.Request(req)
699 }
700
701 // NewXMLRequest sends a HTTP request with body marshaled to
702 // XML. "Content-Type" header is automatically set to
703 // "application/xml". Any Cmp* or [TestAPI.NoBody] methods can now be called.
704 //
705 // The header values, query params, cookies and hooks defined using
706 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
707 // are merged only if each of them does not already exist in
708 // newRequestParams.
709 //
710 // Note that [TestAPI.Failed] status is reset just after this call.
711 //
712 // See [NewRequest] for all possible formats accepted in newRequestParams.
713 func (ta *TestAPI) NewXMLRequest(method, target string, body any, newRequestParams ...any) *TestAPI {
714 ta.t.Helper()
715 req, err := newXMLRequest(method, target, body, newRequestParams...)
716 if err != nil {
717 ta.t.Fatal(err)
718 }
719 return ta.Request(req)
720 }
721
722 // PostXML sends a HTTP POST with body marshaled to
723 // XML. "Content-Type" header is automatically set to
724 // "application/xml". Any Cmp* or [TestAPI.NoBody] methods can now be called.
725 //
726 // The header values, query params, cookies and hooks defined using
727 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
728 // are merged only if each of them does not already exist in
729 // newRequestParams.
730 //
731 // Note that [TestAPI.Failed] status is reset just after this call.
732 //
733 // See [NewRequest] for all possible formats accepted in newRequestParams.
734 func (ta *TestAPI) PostXML(target string, body any, newRequestParams ...any) *TestAPI {
735 ta.t.Helper()
736 req, err := newXMLRequest(http.MethodPost, target, body, newRequestParams...)
737 if err != nil {
738 ta.t.Fatal(err)
739 }
740 return ta.Request(req)
741 }
742
743 // PutXML sends a HTTP PUT with body marshaled to
744 // XML. "Content-Type" header is automatically set to
745 // "application/xml". Any Cmp* or [TestAPI.NoBody] methods can now be called.
746 //
747 // The header values, query params, cookies and hooks defined using
748 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
749 // are merged only if each of them does not already exist in
750 // newRequestParams.
751 //
752 // Note that [TestAPI.Failed] status is reset just after this call.
753 //
754 // See [NewRequest] for all possible formats accepted in newRequestParams.
755 func (ta *TestAPI) PutXML(target string, body any, newRequestParams ...any) *TestAPI {
756 ta.t.Helper()
757 req, err := newXMLRequest(http.MethodPut, target, body, newRequestParams...)
758 if err != nil {
759 ta.t.Fatal(err)
760 }
761 return ta.Request(req)
762 }
763
764 // PatchXML sends a HTTP PATCH with body marshaled to
765 // XML. "Content-Type" header is automatically set to
766 // "application/xml". Any Cmp* or [TestAPI.NoBody] methods can now be called.
767 //
768 // The header values, query params, cookies and hooks defined using
769 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
770 // are merged only if each of them does not already exist in
771 // newRequestParams.
772 //
773 // Note that [TestAPI.Failed] status is reset just after this call.
774 //
775 // See [NewRequest] for all possible formats accepted in newRequestParams.
776 func (ta *TestAPI) PatchXML(target string, body any, newRequestParams ...any) *TestAPI {
777 ta.t.Helper()
778 req, err := newXMLRequest(http.MethodPatch, target, body, newRequestParams...)
779 if err != nil {
780 ta.t.Fatal(err)
781 }
782 return ta.Request(req)
783 }
784
785 // DeleteXML sends a HTTP DELETE with body marshaled to
786 // XML. "Content-Type" header is automatically set to
787 // "application/xml". Any Cmp* or [TestAPI.NoBody] methods can now be called.
788 //
789 // The header values, query params, cookies and hooks defined using
790 // [TestAPI.DefaultRequestParams] or [TestAPI.AddDefaultRequestParams]
791 // are merged only if each of them does not already exist in
792 // newRequestParams.
793 //
794 // Note that [TestAPI.Failed] status is reset just after this call.
795 //
796 // See [NewRequest] for all possible formats accepted in newRequestParams.
797 func (ta *TestAPI) DeleteXML(target string, body any, newRequestParams ...any) *TestAPI {
798 ta.t.Helper()
799 req, err := newXMLRequest(http.MethodDelete, target, body, newRequestParams...)
800 if err != nil {
801 ta.t.Fatal(err)
802 }
803 return ta.Request(req)
804 }
805
806 // CmpResponse tests the last request response status against
807 // expectedResponse. expectedResponse can be a *http.Response or more
808 // probably a [td.TestDeep] operator.
809 //
810 // ta := tdhttp.NewTestAPI(t, mux)
811 //
812 // ta.Get("/test").
813 // CmpResponse(td.Struct(
814 // &http.Response{Status: http.StatusOK}, td.StructFields{
815 // "Header": td.SuperMapOf(http.Header{"X-Test": {"pipo"}}),
816 // "ContentLength": td.Gt(10),
817 // }))
818 //
819 // Some tests can be hard to achieve using operators chaining. In this
820 // case, the [td.Code] operator can be used to take the full control
821 // over the extractions and comparisons to do:
822 //
823 // ta.Get("/test").
824 // CmpResponse(td.Code(func (assert, require *td.T, r *http.Response) {
825 // token, err := ParseToken(r.Header.Get("X-Token"))
826 // require.CmpNoError(err)
827 //
828 // baseURL,err := url.Parse(r.Header.Get("X-Base-URL"))
829 // require.CmpNoError(err)
830 //
831 // assert.Cmp(baseURL.Query().Get("id"), token.ID)
832 // }))
833 //
834 // It fails if no request has been sent yet.
835 func (ta *TestAPI) CmpResponse(expectedResponse any) *TestAPI {
836 defer ta.t.AnchorsPersistTemporarily()()
837
838 ta.t.Helper()
839
840 if !ta.checkRequestSent() {
841 ta.failed |= responseFailed
842 return ta
843 }
844
845 if !ta.t.RootName("Response").
846 Cmp(ta.response.Result(), expectedResponse, ta.name+"full response should match") {
847 ta.failed |= responseFailed
848
849 if ta.autoDumpResponse {
850 ta.dumpResponse()
851 }
852 }
853
854 return ta
855 }
856
857 // CmpStatus tests the last request response status against
858 // expectedStatus. expectedStatus can be an int to match a fixed HTTP
859 // status code, or a [td.TestDeep] operator.
860 //
861 // ta := tdhttp.NewTestAPI(t, mux)
862 //
863 // ta.Get("/test").
864 // CmpStatus(http.StatusOK)
865 //
866 // ta.PostJSON("/new", map[string]string{"name": "Bob"}).
867 // CmpStatus(td.Between(200, 202))
868 //
869 // It fails if no request has been sent yet.
870 func (ta *TestAPI) CmpStatus(expectedStatus any) *TestAPI {
871 defer ta.t.AnchorsPersistTemporarily()()
872
873 ta.t.Helper()
874
875 if !ta.checkRequestSent() {
876 ta.failed |= statusFailed
877 return ta
878 }
879
880 if !ta.t.RootName("Response.Status").
881 CmpLax(ta.response.Code, expectedStatus, ta.name+"status code should match") {
882 ta.failed |= statusFailed
883
884 if ta.autoDumpResponse {
885 ta.dumpResponse()
886 }
887 }
888
889 return ta
890 }
891
892 // CmpHeader tests the last request response header against
893 // expectedHeader. expectedHeader can be a [http.Header] or a
894 // [td.TestDeep] operator. Keep in mind that if it is a [http.Header],
895 // it has to match exactly the response header. Often only the
896 // presence of a header key is needed:
897 //
898 // ta := tdhttp.NewTestAPI(t, mux).
899 // PostJSON("/new", map[string]string{"name": "Bob"}).
900 // CmdStatus(201).
901 // CmpHeader(td.ContainsKey("X-Custom"))
902 //
903 // or some specific key, value pairs:
904 //
905 // ta.CmpHeader(td.SuperMapOf(
906 // http.Header{
907 // "X-Account": []string{"Bob"},
908 // },
909 // td.MapEntries{
910 // "X-Token": td.Bag(td.Re(`^[a-z0-9-]{32}\z`)),
911 // }),
912 // )
913 //
914 // Note that CmpHeader calls can be chained:
915 //
916 // ta.CmpHeader(td.ContainsKey("X-Account")).
917 // CmpHeader(td.ContainsKey("X-Token"))
918 //
919 // instead of doing all tests in one call as [td.All] operator allows it:
920 //
921 // ta.CmpHeader(td.All(
922 // td.ContainsKey("X-Account"),
923 // td.ContainsKey("X-Token"),
924 // ))
925 //
926 // It fails if no request has been sent yet.
927 func (ta *TestAPI) CmpHeader(expectedHeader any) *TestAPI {
928 defer ta.t.AnchorsPersistTemporarily()()
929
930 ta.t.Helper()
931
932 if !ta.checkRequestSent() {
933 ta.failed |= headerFailed
934 return ta
935 }
936
937 if !ta.t.RootName("Response.Header").
938 CmpLax(ta.response.Result().Header, expectedHeader, ta.name+"header should match") {
939 ta.failed |= headerFailed
940
941 if ta.autoDumpResponse {
942 ta.dumpResponse()
943 }
944 }
945
946 return ta
947 }
948
949 // CmpTrailer tests the last request response trailer against
950 // expectedTrailer. expectedTrailer can be a [http.Header] or a
951 // [td.TestDeep] operator. Keep in mind that if it is a [http.Header],
952 // it has to match exactly the response trailer. Often only the
953 // presence of a trailer key is needed:
954 //
955 // ta := tdhttp.NewTestAPI(t, mux).
956 // PostJSON("/new", map[string]string{"name": "Bob"}).
957 // CmdStatus(201).
958 // CmpTrailer(td.ContainsKey("X-Custom"))
959 //
960 // or some specific key, value pairs:
961 //
962 // ta.CmpTrailer(td.SuperMapOf(
963 // http.Header{
964 // "X-Account": []string{"Bob"},
965 // },
966 // td.MapEntries{
967 // "X-Token": td.Re(`^[a-z0-9-]{32}\z`),
968 // }),
969 // )
970 //
971 // Note that CmpTrailer calls can be chained:
972 //
973 // ta.CmpTrailer(td.ContainsKey("X-Account")).
974 // CmpTrailer(td.ContainsKey("X-Token"))
975 //
976 // instead of doing all tests in one call as [td.All] operator allows it:
977 //
978 // ta.CmpTrailer(td.All(
979 // td.ContainsKey("X-Account"),
980 // td.ContainsKey("X-Token"),
981 // ))
982 //
983 // It fails if no request has been sent yet.
984 //
985 // Note that until go1.19, it does not handle multiple values in
986 // a single Trailer header field.
987 func (ta *TestAPI) CmpTrailer(expectedTrailer any) *TestAPI {
988 defer ta.t.AnchorsPersistTemporarily()()
989
990 ta.t.Helper()
991
992 if !ta.checkRequestSent() {
993 ta.failed |= trailerFailed
994 return ta
995 }
996
997 if !ta.t.RootName("Response.Trailer").
998 CmpLax(ta.response.Result().Trailer, expectedTrailer, ta.name+"trailer should match") {
999 ta.failed |= trailerFailed
1000
1001 if ta.autoDumpResponse {
1002 ta.dumpResponse()
1003 }
1004 }
1005
1006 return ta
1007 }
1008
1009 // CmpCookies tests the last request response cookies against
1010 // expectedCookies. expectedCookies can be a [][*http.Cookie] or a
1011 // [td.TestDeep] operator. Keep in mind that if it is a
1012 // [][*http.Cookie], it has to match exactly the response
1013 // cookies. Often only the presence of a cookie key is needed:
1014 //
1015 // ta := tdhttp.NewTestAPI(t, mux).
1016 // PostJSON("/login", map[string]string{"name": "Bob", "password": "Sponge"}).
1017 // CmdStatus(200).
1018 // CmpCookies(td.SuperBagOf(td.Struct(&http.Cookie{Name: "cookie_session"}, nil))).
1019 // CmpCookies(td.SuperBagOf(td.Smuggle("Name", "cookie_session"))) // shorter
1020 //
1021 // To make tests easier, [http.Cookie.Raw] and [http.Cookie.RawExpires] fields
1022 // of each [*http.Cookie] are zeroed before doing the comparison. So no need
1023 // to fill them when comparing against a simple literal as in:
1024 //
1025 // ta := tdhttp.NewTestAPI(t, mux).
1026 // PostJSON("/login", map[string]string{"name": "Bob", "password": "Sponge"}).
1027 // CmdStatus(200).
1028 // CmpCookies([]*http.Cookies{
1029 // {Name: "cookieName1", Value: "cookieValue1"},
1030 // {Name: "cookieName2", Value: "cookieValue2"},
1031 // })
1032 //
1033 // It fails if no request has been sent yet.
1034 func (ta *TestAPI) CmpCookies(expectedCookies any) *TestAPI {
1035 defer ta.t.AnchorsPersistTemporarily()()
1036
1037 ta.t.Helper()
1038
1039 if !ta.checkRequestSent() {
1040 ta.failed |= cookiesFailed
1041 return ta
1042 }
1043
1044 // Empty Raw* fields to make comparisons easier
1045 cookies := ta.response.Result().Cookies()
1046 for _, c := range cookies {
1047 c.RawExpires, c.Raw = "", ""
1048 }
1049
1050 if !ta.t.RootName("Response.Cookie").
1051 CmpLax(cookies, expectedCookies, ta.name+"cookies should match") {
1052 ta.failed |= cookiesFailed
1053
1054 if ta.autoDumpResponse {
1055 ta.dumpResponse()
1056 }
1057 }
1058
1059 return ta
1060 }
1061
1062 // findCmpXBodyCaller finds the oldest Cmp* method called.
1063 func findCmpXBodyCaller() string {
1064 var (
1065 fn string
1066 pc [20]uintptr
1067 found bool
1068 )
1069 if num := runtime.Callers(5, pc[:]); num > 0 {
1070 frames := runtime.CallersFrames(pc[:num])
1071 for {
1072 frame, more := frames.Next()
1073 if pos := strings.Index(frame.Function, "tdhttp.(*TestAPI).Cmp"); pos > 0 {
1074 fn = frame.Function[pos+18:]
1075 found = true
1076 } else if found {
1077 more = false
1078 }
1079 if !more {
1080 break
1081 }
1082 }
1083 }
1084 return fn
1085 }
1086
1087 func (ta *TestAPI) cmpMarshaledBody(
1088 acceptEmptyBody bool,
1089 unmarshal func([]byte, any) error,
1090 expectedBody any,
1091 ) *TestAPI {
1092 defer ta.t.AnchorsPersistTemporarily()()
1093
1094 ta.t.Helper()
1095
1096 if !ta.checkRequestSent() {
1097 ta.failed |= bodyFailed
1098 return ta
1099 }
1100
1101 if !acceptEmptyBody &&
1102 !ta.t.RootName("Response body").Code(ta.response.Body.Bytes(),
1103 func(b []byte) error {
1104 if len(b) > 0 {
1105 return nil
1106 }
1107 return &ctxerr.Error{
1108 Message: "%% is empty!",
1109 Summary: ctxerr.NewSummary(
1110 "Body cannot be empty when using " + findCmpXBodyCaller()),
1111 }
1112 },
1113 ta.name+"body should not be empty") {
1114 ta.failed |= bodyFailed
1115 if ta.autoDumpResponse {
1116 ta.dumpResponse()
1117 }
1118 return ta
1119 }
1120
1121 tt := ta.t.RootName("Response.Body")
1122
1123 var bodyType reflect.Type
1124
1125 // If expectedBody is a TestDeep operator, try to ask it the type
1126 // behind it. It should work in most cases (typically Struct(),
1127 // Map() & Slice()).
1128 var unknownExpectedType, showRawBody bool
1129 op, ok := expectedBody.(td.TestDeep)
1130 if ok {
1131 bodyType = op.TypeBehind()
1132 if bodyType == nil {
1133 // As the expected body type cannot be guessed, try to
1134 // unmarshal in an any
1135 bodyType = types.Interface
1136 unknownExpectedType = true
1137
1138 // Special case for Ignore & NotEmpty operators
1139 switch op.GetLocation().Func {
1140 case "Ignore", "NotEmpty":
1141 showRawBody = (ta.failed & statusFailed) != 0 // Show real body if status failed
1142 }
1143 }
1144 } else {
1145 bodyType = reflect.TypeOf(expectedBody)
1146 if bodyType == nil {
1147 bodyType = types.Interface
1148 }
1149 }
1150
1151 // For unmarshaling below, body must be a pointer
1152 bodyPtr := reflect.New(bodyType)
1153
1154 // Try to unmarshal body
1155 if !tt.RootName("unmarshal(Response.Body)").
1156 CmpNoError(unmarshal(ta.response.Body.Bytes(), bodyPtr.Interface()), ta.name+"body unmarshaling") {
1157 // If unmarshal failed, perhaps it's coz the expected body type
1158 // is unknown?
1159 if unknownExpectedType {
1160 tt.Logf("Cannot guess the body expected type as %[1]s TestDeep\n"+
1161 "operator does not know the type behind it.\n"+
1162 "You can try All(Isa(EXPECTED_TYPE), %[1]s(…)) to disambiguate…",
1163 op.GetLocation().Func)
1164 }
1165 showRawBody = true // let's show its real body contents
1166 ta.failed |= bodyFailed
1167 } else if !tt.Cmp(bodyPtr.Elem().Interface(), expectedBody, ta.name+"body contents is OK") {
1168 // Try to catch bad body expected type when nothing has been set
1169 // to non-zero during unmarshaling body. In this case, require
1170 // to show raw body contents.
1171 if len(ta.response.Body.Bytes()) > 0 &&
1172 td.EqDeeply(bodyPtr.Interface(), reflect.New(bodyType).Interface()) {
1173 showRawBody = true
1174 tt.Log("Hmm… It seems nothing has been set during unmarshaling…")
1175 }
1176 ta.failed |= bodyFailed
1177 }
1178
1179 if showRawBody || ((ta.failed&bodyFailed) != 0 && ta.autoDumpResponse) {
1180 ta.dumpResponse()
1181 }
1182
1183 return ta
1184 }
1185
1186 // CmpMarshaledBody tests that the last request response body can be
1187 // unmarshaled using unmarshal function and then, that it matches
1188 // expectedBody. expectedBody can be any type unmarshal function can
1189 // handle, or a [td.TestDeep] operator.
1190 //
1191 // See [TestAPI.CmpJSONBody] and [TestAPI.CmpXMLBody] sources for
1192 // examples of use.
1193 //
1194 // It fails if no request has been sent yet.
1195 func (ta *TestAPI) CmpMarshaledBody(unmarshal func([]byte, any) error, expectedBody any) *TestAPI {
1196 ta.t.Helper()
1197 return ta.cmpMarshaledBody(false, unmarshal, expectedBody)
1198 }
1199
1200 // CmpBody tests the last request response body against
1201 // expectedBody. expectedBody can be a []byte, a string or a
1202 // [td.TestDeep] operator.
1203 //
1204 // ta := tdhttp.NewTestAPI(t, mux)
1205 //
1206 // ta.Get("/test").
1207 // CmpStatus(http.StatusOK).
1208 // CmpBody("OK!\n")
1209 //
1210 // ta.Get("/test").
1211 // CmpStatus(http.StatusOK).
1212 // CmpBody(td.Contains("OK"))
1213 //
1214 // It fails if no request has been sent yet.
1215 func (ta *TestAPI) CmpBody(expectedBody any) *TestAPI {
1216 ta.t.Helper()
1217
1218 if expectedBody == nil {
1219 return ta.NoBody()
1220 }
1221
1222 return ta.cmpMarshaledBody(
1223 true, // accept empty body
1224 func(body []byte, target any) error {
1225 switch target := target.(type) {
1226 case *string:
1227 *target = string(body)
1228 case *[]byte:
1229 *target = body
1230 case *any:
1231 *target = body
1232 default:
1233 // cmpMarshaledBody always calls us with target as a pointer
1234 return fmt.Errorf(
1235 "CmpBody only accepts expectedBody be a []byte, a string or a TestDeep operator allowing to match these types, but not type %s",
1236 reflect.TypeOf(target).Elem())
1237 }
1238 return nil
1239 },
1240 expectedBody)
1241 }
1242
1243 // CmpJSONBody tests that the last request response body can be
1244 // [json.Unmarshal]'ed and that it matches expectedBody. expectedBody
1245 // can be any type one can [json.Unmarshal] into, or a [td.TestDeep]
1246 // operator.
1247 //
1248 // ta := tdhttp.NewTestAPI(t, mux)
1249 //
1250 // ta.Get("/person/42").
1251 // CmpStatus(http.StatusOK).
1252 // CmpJSONBody(Person{
1253 // ID: 42,
1254 // Name: "Bob",
1255 // Age: 26,
1256 // })
1257 //
1258 // ta.PostJSON("/person", Person{Name: "Bob", Age: 23}).
1259 // CmpStatus(http.StatusCreated).
1260 // CmpJSONBody(td.SStruct(
1261 // Person{
1262 // Name: "Bob",
1263 // Age: 26,
1264 // },
1265 // td.StructFields{
1266 // "ID": td.NotZero(),
1267 // }))
1268 //
1269 // The same with anchoring, and so without [td.SStruct]:
1270 //
1271 // ta := tdhttp.NewTestAPI(tt, mux)
1272 //
1273 // ta.PostJSON("/person", Person{Name: "Bob", Age: 23}).
1274 // CmpStatus(http.StatusCreated).
1275 // CmpJSONBody(Person{
1276 // ID: ta.Anchor(td.NotZero(), uint64(0)).(uint64),
1277 // Name: "Bob",
1278 // Age: 26,
1279 // })
1280 //
1281 // The same using [td.JSON]:
1282 //
1283 // ta.PostJSON("/person", Person{Name: "Bob", Age: 23}).
1284 // CmpStatus(http.StatusCreated).
1285 // CmpJSONBody(td.JSON(`
1286 // {
1287 // "id": NotZero(),
1288 // "name": "Bob",
1289 // "age": 26
1290 // }`))
1291 //
1292 // It fails if no request has been sent yet.
1293 func (ta *TestAPI) CmpJSONBody(expectedBody any) *TestAPI {
1294 ta.t.Helper()
1295 return ta.CmpMarshaledBody(json.Unmarshal, expectedBody)
1296 }
1297
1298 // CmpXMLBody tests that the last request response body can be
1299 // [xml.Unmarshal]'ed and that it matches expectedBody. expectedBody
1300 // can be any type one can [xml.Unmarshal] into, or a [td.TestDeep]
1301 // operator.
1302 //
1303 // ta := tdhttp.NewTestAPI(t, mux)
1304 //
1305 // ta.Get("/person/42").
1306 // CmpStatus(http.StatusOK).
1307 // CmpXMLBody(Person{
1308 // ID: 42,
1309 // Name: "Bob",
1310 // Age: 26,
1311 // })
1312 //
1313 // ta.Get("/person/43").
1314 // CmpStatus(http.StatusOK).
1315 // CmpXMLBody(td.SStruct(
1316 // Person{
1317 // Name: "Bob",
1318 // Age: 26,
1319 // },
1320 // td.StructFields{
1321 // "ID": td.NotZero(),
1322 // }))
1323 //
1324 // The same with anchoring:
1325 //
1326 // ta := tdhttp.NewTestAPI(tt, mux)
1327 //
1328 // ta.Get("/person/42").
1329 // CmpStatus(http.StatusOK).
1330 // CmpXMLBody(Person{
1331 // ID: ta.Anchor(td.NotZero(), uint64(0)).(uint64),
1332 // Name: "Bob",
1333 // Age: 26,
1334 // })
1335 //
1336 // It fails if no request has been sent yet.
1337 func (ta *TestAPI) CmpXMLBody(expectedBody any) *TestAPI {
1338 ta.t.Helper()
1339 return ta.CmpMarshaledBody(xml.Unmarshal, expectedBody)
1340 }
1341
1342 // NoBody tests that the last request response body is empty.
1343 //
1344 // It fails if no request has been sent yet.
1345 func (ta *TestAPI) NoBody() *TestAPI {
1346 defer ta.t.AnchorsPersistTemporarily()()
1347
1348 ta.t.Helper()
1349
1350 if !ta.checkRequestSent() {
1351 ta.failed |= bodyFailed
1352 return ta
1353 }
1354
1355 ok := ta.t.RootName("Response.Body").
1356 Code(len(ta.response.Body.Bytes()) == 0,
1357 func(empty bool) error {
1358 if empty {
1359 return nil
1360 }
1361 return &ctxerr.Error{
1362 Message: "%% is not empty",
1363 Got: types.RawString("not empty"),
1364 Expected: types.RawString("empty"),
1365 }
1366 },
1367 "body should be empty")
1368 if !ok {
1369 ta.failed |= bodyFailed
1370
1371 // Systematically dump response, no AutoDumpResponse needed
1372 ta.dumpResponse()
1373 }
1374
1375 return ta
1376 }
1377
1378 // Or executes function fn if ta.Failed() is true at the moment it is called.
1379 //
1380 // fn can have several types:
1381 // - func(body string) or func(t *td.T, body string)
1382 // → fn is called with response body as a string.
1383 // If no response has been received yet, body is "";
1384 // - func(body []byte) or func(t *td.T, body []byte)
1385 // → fn is called with response body as a []byte.
1386 // If no response has been received yet, body is nil;
1387 // - func(t *td.T, resp *httptest.ResponseRecorder)
1388 // → fn is called with the internal object containing the response.
1389 // See net/http/httptest for details.
1390 // If no response has been received yet, resp is nil.
1391 //
1392 // If fn type is not one of these types, it calls ta.T().Fatal().
1393 func (ta *TestAPI) Or(fn any) *TestAPI {
1394 ta.t.Helper()
1395 switch fn := fn.(type) {
1396 case func(string):
1397 if ta.Failed() {
1398 var body string
1399 if ta.response != nil && ta.response.Body != nil {
1400 body = ta.response.Body.String()
1401 }
1402 fn(body)
1403 }
1404
1405 case func(*td.T, string):
1406 if ta.Failed() {
1407 var body string
1408 if ta.response != nil && ta.response.Body != nil {
1409 body = ta.response.Body.String()
1410 }
1411 fn(ta.t, body)
1412 }
1413
1414 case func([]byte):
1415 if ta.Failed() {
1416 var body []byte
1417 if ta.response != nil && ta.response.Body != nil {
1418 body = ta.response.Body.Bytes()
1419 }
1420 fn(body)
1421 }
1422
1423 case func(*td.T, []byte):
1424 if ta.Failed() {
1425 var body []byte
1426 if ta.response != nil && ta.response.Body != nil {
1427 body = ta.response.Body.Bytes()
1428 }
1429 fn(ta.t, body)
1430 }
1431
1432 case func(*td.T, *httptest.ResponseRecorder):
1433 if ta.Failed() {
1434 fn(ta.t, ta.response)
1435 }
1436
1437 default:
1438 ta.t.Fatal(color.BadUsage(
1439 "Or(func([*td.T,]string) | func([*td.T,][]byte) | func(*td.T,*httptest.ResponseRecorder))",
1440 fn, 1, true))
1441 }
1442
1443 return ta
1444 }
1445
1446 // OrDumpResponse dumps the response if at least one previous test failed.
1447 //
1448 // ta := tdhttp.NewTestAPI(t, handler)
1449 //
1450 // ta.Get("/foo").
1451 // CmpStatus(200).
1452 // OrDumpResponse(). // if status check failed, dumps the response
1453 // CmpBody("bar") // if it fails, the response is not dumped
1454 //
1455 // ta.Get("/foo").
1456 // CmpStatus(200).
1457 // CmpBody("bar").
1458 // OrDumpResponse() // dumps the response if status and/or body checks fail
1459 //
1460 // See [TestAPI.AutoDumpResponse] method to automatize this dump.
1461 func (ta *TestAPI) OrDumpResponse() *TestAPI {
1462 if ta.Failed() {
1463 ta.dumpResponse()
1464 }
1465 return ta
1466 }
1467
1468 func (ta *TestAPI) dumpResponse() {
1469 if ta.responseDumped {
1470 return
1471 }
1472
1473 ta.t.Helper()
1474 if ta.response != nil {
1475 ta.responseDumped = true
1476 internal.DumpResponse(ta.t, ta.response.Result())
1477 return
1478 }
1479
1480 ta.t.Logf("No response received yet")
1481 }
1482
1483 // Anchor returns a typed value allowing to anchor the [td.TestDeep]
1484 // operator operator in a go classic literal like a struct, slice,
1485 // array or map value.
1486 //
1487 // ta := tdhttp.NewTestAPI(tt, mux)
1488 //
1489 // ta.Get("/person/42").
1490 // CmpStatus(http.StatusOK).
1491 // CmpJSONBody(Person{
1492 // ID: ta.Anchor(td.NotZero(), uint64(0)).(uint64),
1493 // Name: "Bob",
1494 // Age: 26,
1495 // })
1496 //
1497 // See [td.T.Anchor] for details.
1498 //
1499 // See [TestAPI.A] method for a shorter synonym of Anchor.
1500 func (ta *TestAPI) Anchor(operator td.TestDeep, model ...any) any {
1501 return ta.t.Anchor(operator, model...)
1502 }
1503
1504 // A is a synonym for [TestAPI.Anchor]. It returns a typed value allowing to
1505 // anchor the [td.TestDeep] operator in a go classic literal
1506 // like a struct, slice, array or map value.
1507 //
1508 // ta := tdhttp.NewTestAPI(tt, mux)
1509 //
1510 // ta.Get("/person/42").
1511 // CmpStatus(http.StatusOK).
1512 // CmpJSONBody(Person{
1513 // ID: ta.A(td.NotZero(), uint64(0)).(uint64),
1514 // Name: "Bob",
1515 // Age: 26,
1516 // })
1517 //
1518 // See [td.T.Anchor] for details.
1519 func (ta *TestAPI) A(operator td.TestDeep, model ...any) any {
1520 return ta.Anchor(operator, model...)
1521 }
1522
1523 // SentAt returns the time just before the last request is handled. It
1524 // can be used to check the time a route sets and returns, as in:
1525 //
1526 // ta.PostJSON("/person/42", Person{Name: "Bob", Age: 23}).
1527 // CmpStatus(http.StatusCreated).
1528 // CmpJSONBody(Person{
1529 // ID: ta.A(td.NotZero(), uint64(0)).(uint64),
1530 // Name: "Bob",
1531 // Age: 23,
1532 // CreatedAt: ta.A(td.Between(ta.SentAt(), time.Now())).(time.Time),
1533 // })
1534 //
1535 // checks that CreatedAt field is included between the time when the
1536 // request has been sent, and the time when the comparison occurs.
1537 func (ta *TestAPI) SentAt() time.Time {
1538 return ta.sentAt
1539 }