Debian Codegraph @

helpers/tdhttp/test_api_test.go

raw
1 // Copyright (c) 2020, 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_test
8
9 import (
10 "encoding/json"
11 "fmt"
12 "io"
13 "net/http"
14 "net/http/httptest"
15 "net/url"
16 "strings"
17 "testing"
18 "time"
19
20 "github.com/maxatome/go-testdeep/helpers/tdhttp"
21 "github.com/maxatome/go-testdeep/helpers/tdutil"
22 "github.com/maxatome/go-testdeep/td"
23 )
24
25 func server() *http.ServeMux {
26 mux := http.NewServeMux()
27
28 mux.HandleFunc("/any", func(w http.ResponseWriter, req *http.Request) {
29 w.Header().Set("X-TestDeep-Method", req.Method)
30 if req.Method == "HEAD" {
31 w.WriteHeader(http.StatusOK)
32 return
33 }
34 w.Header().Set("Content-Type", "text/plain")
35 w.WriteHeader(http.StatusOK)
36
37 fmt.Fprintf(w, "%s!", req.Method) //nolint: errcheck
38 if req.ContentLength != 0 {
39 w.Write([]byte("\n---\n")) //nolint: errcheck
40 io.Copy(w, req.Body) //nolint: errcheck
41 }
42 })
43
44 mux.HandleFunc("/any/json", func(w http.ResponseWriter, req *http.Request) {
45 w.Header().Set("X-TestDeep-Method", req.Method)
46 if req.Method == "HEAD" {
47 w.WriteHeader(http.StatusOK)
48 return
49 }
50 w.Header().Set("Content-Type", "application/json")
51 w.WriteHeader(http.StatusOK)
52
53 m := map[string]any{
54 "method": req.Method,
55 }
56 if req.ContentLength != 0 {
57 var body any
58 if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
59 http.Error(w, err.Error(), http.StatusInternalServerError)
60 return
61 }
62 m["body"] = body
63 }
64 json.NewEncoder(w).Encode(m) //nolint: errcheck
65 })
66
67 mux.HandleFunc("/mirror/json", func(w http.ResponseWriter, req *http.Request) {
68 w.Header().Set("X-TestDeep-Method", req.Method)
69 if req.Method == "HEAD" {
70 w.WriteHeader(http.StatusOK)
71 return
72 }
73 w.Header().Set("Content-Type", "application/json")
74 w.WriteHeader(http.StatusOK)
75
76 io.Copy(w, req.Body) //nolint: errcheck
77 })
78
79 mux.HandleFunc("/hq/json", func(w http.ResponseWriter, req *http.Request) {
80 if req.Method == "HEAD" {
81 w.WriteHeader(http.StatusOK)
82 return
83 }
84 w.Header().Set("Content-Type", "application/json")
85 w.WriteHeader(http.StatusOK)
86 m := map[string]any{
87 "header": req.Header,
88 "query_params": req.URL.Query(),
89 }
90 json.NewEncoder(w).Encode(m) //nolint: errcheck
91 })
92
93 mux.HandleFunc("/any/xml", func(w http.ResponseWriter, req *http.Request) {
94 w.Header().Set("X-TestDeep-Method", req.Method)
95 if req.Method == "HEAD" {
96 w.WriteHeader(http.StatusOK)
97 return
98 }
99 w.Header().Set("Content-Type", "application/xml")
100 w.WriteHeader(http.StatusOK)
101
102 fmt.Fprintf(w, `<XResp><method>%s</method>`, req.Method) //nolint: errcheck
103 if req.ContentLength != 0 {
104 io.Copy(w, req.Body) //nolint: errcheck
105 }
106 w.Write([]byte(`</XResp>`)) //nolint: errcheck
107 })
108
109 mux.HandleFunc("/any/cookies", func(w http.ResponseWriter, req *http.Request) {
110 w.Header().Set("X-TestDeep-Method", req.Method)
111 if req.Method == "HEAD" {
112 w.WriteHeader(http.StatusOK)
113 return
114 }
115 w.Header().Set("Content-Type", "text/plain")
116
117 http.SetCookie(w, &http.Cookie{
118 Name: "first",
119 Value: "cookie1",
120 MaxAge: 123456,
121 Expires: time.Date(2021, time.August, 12, 11, 22, 33, 0, time.UTC),
122 })
123 http.SetCookie(w, &http.Cookie{
124 Name: "second",
125 Value: "cookie2",
126 MaxAge: 654321,
127 })
128
129 w.WriteHeader(http.StatusOK)
130
131 fmt.Fprintf(w, "%s!", req.Method) //nolint: errcheck
132 if req.ContentLength != 0 {
133 w.Write([]byte("\n---\n")) //nolint: errcheck
134 io.Copy(w, req.Body) //nolint: errcheck
135 }
136 })
137
138 mux.HandleFunc("/any/trailer", func(w http.ResponseWriter, req *http.Request) {
139 w.Header().Set("Trailer", "X-TestDeep-Method")
140 w.Header().Add("Trailer", "X-TestDeep-Foo")
141
142 io.WriteString(w, "Hey!") //nolint: errcheck
143
144 w.Header().Set("X-TestDeep-Method", req.Method)
145 w.Header().Set("X-TestDeep-Foo", "bar")
146 })
147
148 return mux
149 }
150
151 func TestNewTestAPI(t *testing.T) {
152 mux := server()
153
154 containsKey := td.ContainsKey("X-Testdeep-Method")
155
156 t.Run("No error", func(t *testing.T) {
157 mockT := tdutil.NewT("test")
158 td.CmpFalse(t,
159 tdhttp.NewTestAPI(mockT, mux).
160 Head("/any").
161 CmpStatus(200).
162 CmpHeader(containsKey).
163 CmpHeader(td.SuperMapOf(http.Header{}, td.MapEntries{
164 "X-Testdeep-Method": td.Bag(td.Re(`(?i)^head\z`)),
165 })).
166 NoBody().
167 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
168 assert.Cmp(resp.StatusCode, 200)
169 assert.Cmp(resp.Header, containsKey)
170 assert.Smuggle(resp.Body, io.ReadAll, td.Empty())
171 })).
172 Failed())
173 td.CmpEmpty(t, mockT.LogBuf())
174
175 mockT = tdutil.NewT("test")
176 td.CmpFalse(t,
177 tdhttp.NewTestAPI(mockT, mux).
178 Head("/any").
179 CmpStatus(200).
180 CmpHeader(containsKey).
181 CmpBody(td.Empty()).
182 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
183 assert.Cmp(resp.StatusCode, 200)
184 assert.Cmp(resp.Header, containsKey)
185 assert.Smuggle(resp.Body, io.ReadAll, td.Empty())
186 })).
187 Failed())
188 td.CmpEmpty(t, mockT.LogBuf())
189
190 mockT = tdutil.NewT("test")
191 td.CmpFalse(t,
192 tdhttp.NewTestAPI(mockT, mux).
193 Get("/any").
194 CmpStatus(200).
195 CmpHeader(containsKey).
196 CmpBody("GET!").
197 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
198 assert.Cmp(resp.StatusCode, 200)
199 assert.Cmp(resp.Header, containsKey)
200 assert.Smuggle(resp.Body, io.ReadAll, td.String("GET!"))
201 })).
202 Failed())
203 td.CmpEmpty(t, mockT.LogBuf())
204
205 mockT = tdutil.NewT("test")
206 td.CmpFalse(t,
207 tdhttp.NewTestAPI(mockT, mux).
208 Get("/any").
209 CmpStatus(200).
210 CmpHeader(containsKey).
211 CmpBody(td.Contains("GET")).
212 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
213 assert.Cmp(resp.StatusCode, 200)
214 assert.Cmp(resp.Header, containsKey)
215 assert.Smuggle(resp.Body, io.ReadAll, td.Contains("GET"))
216 })).
217 Failed())
218 td.CmpEmpty(t, mockT.LogBuf())
219
220 mockT = tdutil.NewT("test")
221 td.CmpFalse(t,
222 tdhttp.NewTestAPI(mockT, mux).
223 Options("/any", strings.NewReader("OPTIONS body")).
224 CmpStatus(200).
225 CmpHeader(containsKey).
226 CmpBody("OPTIONS!\n---\nOPTIONS body").
227 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
228 assert.Cmp(resp.StatusCode, 200)
229 assert.Cmp(resp.Header, containsKey)
230 assert.Smuggle(resp.Body, io.ReadAll, td.String("OPTIONS!\n---\nOPTIONS body"))
231 })).
232 Failed())
233 td.CmpEmpty(t, mockT.LogBuf())
234
235 mockT = tdutil.NewT("test")
236 td.CmpFalse(t,
237 tdhttp.NewTestAPI(mockT, mux).
238 Post("/any", strings.NewReader("POST body")).
239 CmpStatus(200).
240 CmpHeader(containsKey).
241 CmpBody("POST!\n---\nPOST body").
242 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
243 assert.Cmp(resp.StatusCode, 200)
244 assert.Cmp(resp.Header, containsKey)
245 assert.Smuggle(resp.Body, io.ReadAll, td.String("POST!\n---\nPOST body"))
246 })).
247 Failed())
248 td.CmpEmpty(t, mockT.LogBuf())
249
250 mockT = tdutil.NewT("test")
251 td.CmpFalse(t,
252 tdhttp.NewTestAPI(mockT, mux).
253 PostForm("/any", url.Values{"p1": {"v1"}, "p2": {"v2"}}).
254 CmpStatus(200).
255 CmpHeader(containsKey).
256 CmpBody("POST!\n---\np1=v1&p2=v2").
257 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
258 assert.Cmp(resp.StatusCode, 200)
259 assert.Cmp(resp.Header, containsKey)
260 assert.Smuggle(resp.Body, io.ReadAll, td.String("POST!\n---\np1=v1&p2=v2"))
261 })).
262 Failed())
263 td.CmpEmpty(t, mockT.LogBuf())
264
265 mockT = tdutil.NewT("test")
266 td.CmpFalse(t,
267 tdhttp.NewTestAPI(mockT, mux).
268 PostForm("/any", tdhttp.Q{"p1": "v1", "p2": "v2"}).
269 CmpStatus(200).
270 CmpHeader(containsKey).
271 CmpBody("POST!\n---\np1=v1&p2=v2").
272 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {
273 assert.Cmp(resp.StatusCode, 200)
274 assert.Cmp(resp.Header, containsKey)
275 assert.Smuggle(resp.Body, io.ReadAll, td.String("POST!\n---\np1=v1&p2=v2"))
276 })).
277 Failed())
278 td.CmpEmpty(t, mockT.LogBuf())
279
280 mockT = tdutil.NewT("test")
281 td.CmpFalse(t,
282 tdhttp.NewTestAPI(mockT, mux).
283 PostMultipartFormData("/any", &tdhttp.MultipartBody{
284 Boundary: "BoUnDaRy",
285 Parts: []*tdhttp.MultipartPart{
286 tdhttp.NewMultipartPartString("pipo", "bingo"),
287 },
288 }).
289 CmpStatus(200).
290 CmpHeader(containsKey).
291 CmpBody(strings.ReplaceAll(
292 `POST!
293 ---
294 --BoUnDaRy%CR
295 Content-Disposition: form-data; name="pipo"%CR
296 Content-Type: text/plain; charset=utf-8%CR
297 %CR
298 bingo%CR
299 --BoUnDaRy--%CR
300 `,
301 "%CR", "\r")).
302 Failed())
303 td.CmpEmpty(t, mockT.LogBuf())
304
305 mockT = tdutil.NewT("test")
306 td.CmpFalse(t,
307 tdhttp.NewTestAPI(mockT, mux).
308 Put("/any", strings.NewReader("PUT body")).
309 CmpStatus(200).
310 CmpHeader(containsKey).
311 CmpBody("PUT!\n---\nPUT body").
312 Failed())
313 td.CmpEmpty(t, mockT.LogBuf())
314
315 mockT = tdutil.NewT("test")
316 td.CmpFalse(t,
317 tdhttp.NewTestAPI(mockT, mux).
318 Patch("/any", strings.NewReader("PATCH body")).
319 CmpStatus(200).
320 CmpHeader(containsKey).
321 CmpBody("PATCH!\n---\nPATCH body").
322 Failed())
323 td.CmpEmpty(t, mockT.LogBuf())
324
325 mockT = tdutil.NewT("test")
326 td.CmpFalse(t,
327 tdhttp.NewTestAPI(mockT, mux).
328 Delete("/any", strings.NewReader("DELETE body")).
329 CmpStatus(200).
330 CmpHeader(containsKey).
331 CmpBody("DELETE!\n---\nDELETE body").
332 Failed())
333 td.CmpEmpty(t, mockT.LogBuf())
334 })
335
336 t.Run("No JSON error", func(t *testing.T) {
337 requestBody := map[string]any{"hey": 123}
338 expectedBody := func(m string) td.TestDeep {
339 return td.JSON(`{"method": $1, "body": {"hey": 123}}`, m)
340 }
341
342 mockT := tdutil.NewT("test")
343 td.CmpFalse(t,
344 tdhttp.NewTestAPI(mockT, mux).
345 NewJSONRequest("GET", "/mirror/json", json.RawMessage(`null`)).
346 CmpStatus(200).
347 CmpHeader(containsKey).
348 CmpJSONBody(nil).
349 Failed())
350 td.CmpEmpty(t, mockT.LogBuf())
351
352 mockT = tdutil.NewT("test")
353 td.CmpFalse(t,
354 tdhttp.NewTestAPI(mockT, mux).
355 NewJSONRequest("ZIP", "/any/json", requestBody).
356 CmpStatus(200).
357 CmpHeader(containsKey).
358 CmpJSONBody(expectedBody("ZIP")).
359 Failed())
360 td.CmpEmpty(t, mockT.LogBuf())
361
362 mockT = tdutil.NewT("test")
363 td.CmpFalse(t,
364 tdhttp.NewTestAPI(mockT, mux).
365 NewJSONRequest("ZIP", "/any/json", requestBody).
366 CmpStatus(200).
367 CmpHeader(containsKey).
368 CmpJSONBody(td.JSONPointer("/body/hey", 123)).
369 Failed())
370 td.CmpEmpty(t, mockT.LogBuf())
371
372 mockT = tdutil.NewT("test")
373 td.CmpFalse(t,
374 tdhttp.NewTestAPI(mockT, mux).
375 PostJSON("/any/json", requestBody).
376 CmpStatus(200).
377 CmpHeader(containsKey).
378 CmpJSONBody(expectedBody("POST")).
379 Failed())
380 td.CmpEmpty(t, mockT.LogBuf())
381
382 mockT = tdutil.NewT("test")
383 td.CmpFalse(t,
384 tdhttp.NewTestAPI(mockT, mux).
385 PutJSON("/any/json", requestBody).
386 CmpStatus(200).
387 CmpHeader(containsKey).
388 CmpJSONBody(expectedBody("PUT")).
389 Failed())
390 td.CmpEmpty(t, mockT.LogBuf())
391
392 mockT = tdutil.NewT("test")
393 td.CmpFalse(t,
394 tdhttp.NewTestAPI(mockT, mux).
395 PatchJSON("/any/json", requestBody).
396 CmpStatus(200).
397 CmpHeader(containsKey).
398 CmpJSONBody(expectedBody("PATCH")).
399 Failed())
400 td.CmpEmpty(t, mockT.LogBuf())
401
402 mockT = tdutil.NewT("test")
403 td.CmpFalse(t,
404 tdhttp.NewTestAPI(mockT, mux).
405 DeleteJSON("/any/json", requestBody).
406 CmpStatus(200).
407 CmpHeader(containsKey).
408 CmpJSONBody(expectedBody("DELETE")).
409 Failed())
410 td.CmpEmpty(t, mockT.LogBuf())
411
412 // With anchors
413 type ReqBody struct {
414 Hey int `json:"hey"`
415 }
416 type Resp struct {
417 Method string `json:"method"`
418 ReqBody ReqBody `json:"body"`
419 }
420 mockT = tdutil.NewT("test")
421 tt := td.NewT(mockT)
422 td.CmpFalse(t,
423 tdhttp.NewTestAPI(mockT, mux).
424 DeleteJSON("/any/json", requestBody).
425 CmpStatus(200).
426 CmpHeader(containsKey).
427 CmpJSONBody(Resp{
428 Method: tt.A(td.Re(`^(?i)delete\z`), "").(string),
429 ReqBody: ReqBody{
430 Hey: tt.A(td.Between(120, 130)).(int),
431 },
432 }).
433 Failed())
434 td.CmpEmpty(t, mockT.LogBuf())
435
436 // JSON and root operator (here SuperMapOf)
437 mockT = tdutil.NewT("test")
438 td.CmpFalse(t,
439 tdhttp.NewTestAPI(mockT, mux).
440 PostJSON("/any/json", true).
441 CmpStatus(200).
442 CmpJSONBody(td.JSON(`SuperMapOf({"body":Ignore()})`)).
443 Failed())
444 td.CmpEmpty(t, mockT.LogBuf())
445
446 // td.Bag+td.JSON
447 mockT = tdutil.NewT("test")
448 td.CmpFalse(t,
449 tdhttp.NewTestAPI(mockT, mux).
450 PostJSON("/mirror/json",
451 json.RawMessage(`[{"name":"Bob"},{"name":"Alice"}]`)).
452 CmpStatus(200).
453 CmpJSONBody(td.Bag(
454 td.JSON(`{"name":"Alice"}`),
455 td.JSON(`{"name":"Bob"}`),
456 )).
457 Failed())
458 td.CmpEmpty(t, mockT.LogBuf())
459
460 // td.Bag+literal
461 type People struct {
462 Name string `json:"name"`
463 }
464 mockT = tdutil.NewT("test")
465 td.CmpFalse(t,
466 tdhttp.NewTestAPI(mockT, mux).
467 PostJSON("/mirror/json",
468 json.RawMessage(`[{"name":"Bob"},{"name":"Alice"}]`)).
469 CmpStatus(200).
470 CmpJSONBody(td.Bag(People{"Alice"}, People{"Bob"})).
471 Failed())
472 td.CmpEmpty(t, mockT.LogBuf())
473 })
474
475 t.Run("No XML error", func(t *testing.T) {
476 type XBody struct {
477 Hey int `xml:"hey"`
478 }
479 type XResp struct {
480 Method string `xml:"method"`
481 ReqBody *XBody `xml:"XBody"`
482 }
483
484 requestBody := XBody{Hey: 123}
485 expectedBody := func(m string) XResp {
486 return XResp{
487 Method: m,
488 ReqBody: &requestBody,
489 }
490 }
491
492 mockT := tdutil.NewT("test")
493 td.CmpFalse(t,
494 tdhttp.NewTestAPI(mockT, mux).
495 NewXMLRequest("ZIP", "/any/xml", requestBody).
496 CmpStatus(200).
497 CmpHeader(containsKey).
498 CmpXMLBody(expectedBody("ZIP")).
499 Failed())
500 td.CmpEmpty(t, mockT.LogBuf())
501
502 mockT = tdutil.NewT("test")
503 td.CmpFalse(t,
504 tdhttp.NewTestAPI(mockT, mux).
505 PostXML("/any/xml", requestBody).
506 CmpStatus(200).
507 CmpHeader(containsKey).
508 CmpXMLBody(expectedBody("POST")).
509 Failed())
510 td.CmpEmpty(t, mockT.LogBuf())
511
512 mockT = tdutil.NewT("test")
513 td.CmpFalse(t,
514 tdhttp.NewTestAPI(mockT, mux).
515 PutXML("/any/xml", requestBody).
516 CmpStatus(200).
517 CmpHeader(containsKey).
518 CmpXMLBody(expectedBody("PUT")).
519 Failed())
520 td.CmpEmpty(t, mockT.LogBuf())
521
522 mockT = tdutil.NewT("test")
523 td.CmpFalse(t,
524 tdhttp.NewTestAPI(mockT, mux).
525 PatchXML("/any/xml", requestBody).
526 CmpStatus(200).
527 CmpHeader(containsKey).
528 CmpXMLBody(expectedBody("PATCH")).
529 Failed())
530 td.CmpEmpty(t, mockT.LogBuf())
531
532 mockT = tdutil.NewT("test")
533 td.CmpFalse(t,
534 tdhttp.NewTestAPI(mockT, mux).
535 DeleteXML("/any/xml", requestBody).
536 CmpStatus(200).
537 CmpHeader(containsKey).
538 CmpXMLBody(expectedBody("DELETE")).
539 Failed())
540 td.CmpEmpty(t, mockT.LogBuf())
541
542 // With anchors
543 mockT = tdutil.NewT("test")
544 tt := td.NewT(mockT)
545 td.CmpFalse(tt,
546 tdhttp.NewTestAPI(mockT, mux).
547 DeleteXML("/any/xml", requestBody).
548 CmpStatus(200).
549 CmpHeader(containsKey).
550 CmpXMLBody(XResp{
551 Method: tt.A(td.Re(`^(?i)delete\z`), "").(string),
552 ReqBody: &XBody{
553 Hey: tt.A(td.Between(120, 130)).(int),
554 },
555 }).
556 Failed())
557 td.CmpEmpty(t, mockT.LogBuf())
558 })
559
560 t.Run("Cookies", func(t *testing.T) {
561 mockT := tdutil.NewT("test")
562 td.CmpFalse(t,
563 tdhttp.NewTestAPI(mockT, mux).
564 Get("/any/cookies").
565 CmpCookies([]*http.Cookie{
566 {
567 Name: "first",
568 Value: "cookie1",
569 MaxAge: 123456,
570 Expires: time.Date(2021, time.August, 12, 11, 22, 33, 0, time.UTC),
571 },
572 {
573 Name: "second",
574 Value: "cookie2",
575 MaxAge: 654321,
576 },
577 }).
578 Failed())
579 td.CmpEmpty(t, mockT.LogBuf())
580
581 mockT = tdutil.NewT("test")
582 td.CmpTrue(t,
583 tdhttp.NewTestAPI(mockT, mux).
584 Get("/any/cookies").
585 CmpCookies([]*http.Cookie{
586 {
587 Name: "first",
588 Value: "cookie1",
589 MaxAge: 123456,
590 Expires: time.Date(2021, time.August, 12, 11, 22, 33, 0, time.UTC),
591 },
592 }).
593 Failed())
594 td.CmpContains(t, mockT.LogBuf(),
595 "Failed test 'cookies should match'")
596 td.CmpContains(t, mockT.LogBuf(),
597 "Response.Cookie: comparing slices, from index #1")
598
599 // 2 cookies are here whatever their order is using Bag
600 mockT = tdutil.NewT("test")
601 td.CmpFalse(t,
602 tdhttp.NewTestAPI(mockT, mux).
603 Get("/any/cookies").
604 CmpCookies(td.Bag(
605 td.Smuggle("Name", "second"),
606 td.Smuggle("Name", "first"),
607 )).
608 Failed())
609 td.CmpEmpty(t, mockT.LogBuf())
610
611 // Testing only Name & Value whatever their order is using Bag
612 mockT = tdutil.NewT("test")
613 td.CmpFalse(t,
614 tdhttp.NewTestAPI(mockT, mux).
615 Get("/any/cookies").
616 CmpCookies(td.Bag(
617 td.Struct(&http.Cookie{Name: "first", Value: "cookie1"}, nil),
618 td.Struct(&http.Cookie{Name: "second", Value: "cookie2"}, nil),
619 )).
620 Failed())
621 td.CmpEmpty(t, mockT.LogBuf())
622
623 // Testing the presence of only one using SuperBagOf
624 mockT = tdutil.NewT("test")
625 td.CmpFalse(t,
626 tdhttp.NewTestAPI(mockT, mux).
627 Get("/any/cookies").
628 CmpCookies(td.SuperBagOf(
629 td.Struct(&http.Cookie{Name: "first", Value: "cookie1"}, nil),
630 )).
631 Failed())
632 td.CmpEmpty(t, mockT.LogBuf())
633
634 // Testing only the number of cookies
635 mockT = tdutil.NewT("test")
636 td.CmpFalse(t,
637 tdhttp.NewTestAPI(mockT, mux).
638 Get("/any/cookies").
639 CmpCookies(td.Len(2)).
640 Failed())
641 td.CmpEmpty(t, mockT.LogBuf())
642
643 // Error followed by a success: Failed() should return true anyway
644 mockT = tdutil.NewT("test")
645 td.CmpTrue(t,
646 tdhttp.NewTestAPI(mockT, mux).
647 Get("/any").
648 CmpCookies(td.Len(100)). // fails
649 CmpCookies(td.Len(2)). // succeeds
650 Failed())
651 td.CmpContains(t, mockT.LogBuf(),
652 "Failed test 'cookies should match'")
653
654 // AutoDumpResponse
655 mockT = tdutil.NewT("test")
656 td.CmpTrue(t,
657 tdhttp.NewTestAPI(mockT, mux).
658 AutoDumpResponse().
659 Get("/any/cookies").
660 Name("my test").
661 CmpCookies(td.Len(100)).
662 Failed())
663 td.CmpContains(t, mockT.LogBuf(),
664 "Failed test 'my test: cookies should match'")
665 td.CmpContains(t, mockT.LogBuf(), "Response.Cookie: bad length")
666 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))
667
668 // Request not sent
669 mockT = tdutil.NewT("test")
670 ta := tdhttp.NewTestAPI(mockT, mux).
671 Name("my test").
672 CmpCookies(td.Len(2))
673 td.CmpTrue(t, ta.Failed())
674 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")
675 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")
676 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")
677 td.CmpNot(t, mockT.LogBuf(), td.Contains("No response received yet\n"))
678 })
679
680 t.Run("Trailer", func(t *testing.T) {
681 mockT := tdutil.NewT("test")
682 td.CmpFalse(t,
683 tdhttp.NewTestAPI(mockT, mux).
684 Get("/any").
685 CmpStatus(200).
686 CmpTrailer(nil). // No trailer at all
687 Failed())
688
689 mockT = tdutil.NewT("test")
690 td.CmpFalse(t,
691 tdhttp.NewTestAPI(mockT, mux).
692 Get("/any/trailer").
693 CmpStatus(200).
694 CmpTrailer(containsKey).
695 Failed())
696
697 mockT = tdutil.NewT("test")
698 td.CmpFalse(t,
699 tdhttp.NewTestAPI(mockT, mux).
700 Get("/any/trailer").
701 CmpStatus(200).
702 CmpTrailer(http.Header{
703 "X-Testdeep-Method": {"GET"},
704 "X-Testdeep-Foo": {"bar"},
705 }).
706 Failed())
707
708 // AutoDumpResponse
709 mockT = tdutil.NewT("test")
710 td.CmpTrue(t,
711 tdhttp.NewTestAPI(mockT, mux).
712 AutoDumpResponse().
713 Get("/any/trailer").
714 Name("my test").
715 CmpTrailer(http.Header{}).
716 Failed())
717 td.CmpContains(t, mockT.LogBuf(),
718 "Failed test 'my test: trailer should match'")
719 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))
720
721 // OrDumpResponse
722 mockT = tdutil.NewT("test")
723 td.CmpTrue(t,
724 tdhttp.NewTestAPI(mockT, mux).
725 Get("/any/trailer").
726 Name("my test").
727 CmpTrailer(http.Header{}).
728 OrDumpResponse().
729 OrDumpResponse(). // only one log
730 Failed())
731 td.CmpContains(t, mockT.LogBuf(),
732 "Failed test 'my test: trailer should match'")
733 logPos := strings.Index(mockT.LogBuf(), "Received response:\n")
734 if td.Cmp(t, logPos, td.Gte(0)) {
735 // Only one occurrence
736 td.Cmp(t,
737 strings.Index(mockT.LogBuf()[logPos+1:], "Received response:\n"),
738 -1)
739 }
740
741 mockT = tdutil.NewT("test")
742 ta := tdhttp.NewTestAPI(mockT, mux).
743 Name("my test").
744 CmpTrailer(http.Header{})
745 td.CmpTrue(t, ta.Failed())
746 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")
747 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")
748 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")
749 td.CmpNot(t, mockT.LogBuf(), td.Contains("No response received yet\n"))
750
751 end := len(mockT.LogBuf())
752 ta.OrDumpResponse()
753 td.CmpContains(t, mockT.LogBuf()[end:], "No response received yet\n")
754 })
755
756 t.Run("Status error", func(t *testing.T) {
757 mockT := tdutil.NewT("test")
758 td.CmpTrue(t,
759 tdhttp.NewTestAPI(mockT, mux).
760 Get("/any").
761 CmpStatus(400).
762 Failed())
763 td.CmpContains(t, mockT.LogBuf(),
764 "Failed test 'status code should match'")
765
766 // Error followed by a success: Failed() should return true anyway
767 mockT = tdutil.NewT("test")
768 td.CmpTrue(t,
769 tdhttp.NewTestAPI(mockT, mux).
770 Get("/any").
771 CmpStatus(400). // fails
772 CmpStatus(200). // succeeds
773 Failed())
774 td.CmpContains(t, mockT.LogBuf(),
775 "Failed test 'status code should match'")
776
777 mockT = tdutil.NewT("test")
778 td.CmpTrue(t,
779 tdhttp.NewTestAPI(mockT, mux).
780 Get("/any").
781 Name("my test").
782 CmpStatus(400).
783 Failed())
784 td.CmpContains(t, mockT.LogBuf(),
785 "Failed test 'my test: status code should match'")
786 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))
787
788 // AutoDumpResponse
789 mockT = tdutil.NewT("test")
790 td.CmpTrue(t,
791 tdhttp.NewTestAPI(mockT, mux).
792 AutoDumpResponse().
793 Get("/any").
794 Name("my test").
795 CmpStatus(400).
796 Failed())
797 td.CmpContains(t, mockT.LogBuf(),
798 "Failed test 'my test: status code should match'")
799 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))
800
801 // OrDumpResponse
802 mockT = tdutil.NewT("test")
803 td.CmpTrue(t,
804 tdhttp.NewTestAPI(mockT, mux).
805 Get("/any").
806 Name("my test").
807 CmpStatus(400).
808 OrDumpResponse().
809 OrDumpResponse(). // only one log
810 Failed())
811 td.CmpContains(t, mockT.LogBuf(),
812 "Failed test 'my test: status code should match'")
813 logPos := strings.Index(mockT.LogBuf(), "Received response:\n")
814 if td.Cmp(t, logPos, td.Gte(0)) {
815 // Only one occurrence
816 td.Cmp(t,
817 strings.Index(mockT.LogBuf()[logPos+1:], "Received response:\n"),
818 -1)
819 }
820
821 mockT = tdutil.NewT("test")
822 ta := tdhttp.NewTestAPI(mockT, mux).
823 Name("my test").
824 CmpStatus(400)
825 td.CmpTrue(t, ta.Failed())
826 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")
827 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")
828 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")
829 td.CmpNot(t, mockT.LogBuf(), td.Contains("No response received yet\n"))
830
831 end := len(mockT.LogBuf())
832 ta.OrDumpResponse()
833 td.CmpContains(t, mockT.LogBuf()[end:], "No response received yet\n")
834 })
835
836 t.Run("Header error", func(t *testing.T) {
837 mockT := tdutil.NewT("test")
838 td.CmpTrue(t,
839 tdhttp.NewTestAPI(mockT, mux).
840 Get("/any").
841 CmpHeader(td.Not(containsKey)).
842 Failed())
843 td.CmpContains(t, mockT.LogBuf(),
844 "Failed test 'header should match'")
845
846 // Error followed by a success: Failed() should return true anyway
847 mockT = tdutil.NewT("test")
848 td.CmpTrue(t,
849 tdhttp.NewTestAPI(mockT, mux).
850 Get("/any").
851 CmpHeader(td.Not(containsKey)). // fails
852 CmpHeader(td.Ignore()). // succeeds
853 Failed())
854 td.CmpContains(t, mockT.LogBuf(),
855 "Failed test 'header should match'")
856
857 mockT = tdutil.NewT("test")
858 td.CmpTrue(t,
859 tdhttp.NewTestAPI(mockT, mux).
860 Get("/any").
861 Name("my test").
862 CmpHeader(td.Not(containsKey)).
863 Failed())
864 td.CmpContains(t, mockT.LogBuf(),
865 "Failed test 'my test: header should match'")
866 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))
867
868 // AutoDumpResponse
869 mockT = tdutil.NewT("test")
870 td.CmpTrue(t,
871 tdhttp.NewTestAPI(mockT, mux).
872 AutoDumpResponse().
873 Get("/any").
874 Name("my test").
875 CmpHeader(td.Not(containsKey)).
876 Failed())
877 td.CmpContains(t, mockT.LogBuf(),
878 "Failed test 'my test: header should match'")
879 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))
880
881 mockT = tdutil.NewT("test")
882 td.CmpTrue(t,
883 tdhttp.NewTestAPI(mockT, mux).
884 Name("my test").
885 CmpHeader(td.Not(containsKey)).
886 Failed())
887 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")
888 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")
889 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")
890 })
891
892 t.Run("Body error", func(t *testing.T) {
893 mockT := tdutil.NewT("test")
894 td.CmpTrue(t,
895 tdhttp.NewTestAPI(mockT, mux).
896 Get("/any").
897 CmpBody("xxx").
898 Failed())
899 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body contents is OK'")
900 td.CmpContains(t, mockT.LogBuf(), "Response.Body: values differ\n")
901 td.CmpContains(t, mockT.LogBuf(), `expected: "xxx"`)
902 td.CmpContains(t, mockT.LogBuf(), `got: "GET!"`)
903
904 // Error followed by a success: Failed() should return true anyway
905 mockT = tdutil.NewT("test")
906 td.CmpTrue(t,
907 tdhttp.NewTestAPI(mockT, mux).
908 Get("/any").
909 CmpBody("xxx"). // fails
910 CmpBody(td.Ignore()). // succeeds
911 Failed())
912
913 // Without AutoDumpResponse
914 mockT = tdutil.NewT("test")
915 td.CmpTrue(t,
916 tdhttp.NewTestAPI(mockT, mux).
917 Get("/any").
918 Name("my test").
919 CmpBody("xxx").
920 Failed())
921 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: body contents is OK'")
922 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))
923
924 // AutoDumpResponse
925 mockT = tdutil.NewT("test")
926 td.CmpTrue(t,
927 tdhttp.NewTestAPI(mockT, mux).
928 AutoDumpResponse().
929 Get("/any").
930 Name("my test").
931 CmpBody("xxx").
932 Failed())
933 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: body contents is OK'")
934 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))
935
936 mockT = tdutil.NewT("test")
937 td.CmpTrue(t,
938 tdhttp.NewTestAPI(mockT, mux).
939 Name("my test").
940 CmpBody("xxx").
941 Failed())
942 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")
943 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")
944 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")
945
946 // NoBody
947 mockT = tdutil.NewT("test")
948 td.CmpTrue(t,
949 tdhttp.NewTestAPI(mockT, mux).
950 Name("my test").
951 NoBody().
952 Failed())
953 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")
954 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")
955 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")
956 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))
957
958 // Error followed by a success: Failed() should return true anyway
959 mockT = tdutil.NewT("test")
960 td.CmpTrue(t,
961 tdhttp.NewTestAPI(mockT, mux).
962 Name("my test").
963 Head("/any").
964 CmpBody("fail"). // fails
965 NoBody(). // succeeds
966 Failed())
967
968 // No JSON body
969 mockT = tdutil.NewT("test")
970 td.CmpTrue(t,
971 tdhttp.NewTestAPI(mockT, mux).
972 Head("/any").
973 CmpStatus(200).
974 CmpHeader(containsKey).
975 CmpJSONBody(json.RawMessage(`{}`)).
976 Failed())
977 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body should not be empty'")
978 td.CmpContains(t, mockT.LogBuf(), "Response body is empty!")
979 td.CmpContains(t, mockT.LogBuf(), "Body cannot be empty when using CmpJSONBody")
980 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))
981
982 // Error followed by a success: Failed() should return true anyway
983 mockT = tdutil.NewT("test")
984 td.CmpTrue(t,
985 tdhttp.NewTestAPI(mockT, mux).
986 Get("/any/json").
987 CmpStatus(200).
988 CmpHeader(containsKey).
989 CmpJSONBody(json.RawMessage(`{}`)). // fails
990 CmpJSONBody(td.Ignore()). // succeeds
991 Failed())
992
993 // No JSON body + AutoDumpResponse
994 mockT = tdutil.NewT("test")
995 td.CmpTrue(t,
996 tdhttp.NewTestAPI(mockT, mux).
997 AutoDumpResponse().
998 Head("/any").
999 CmpStatus(200).
1000 CmpHeader(containsKey).
1001 CmpJSONBody(json.RawMessage(`{}`)).
1002 Failed())
1003 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body should not be empty'")
1004 td.CmpContains(t, mockT.LogBuf(), "Response body is empty!")
1005 td.CmpContains(t, mockT.LogBuf(), "Body cannot be empty when using CmpJSONBody")
1006 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))
1007
1008 // No XML body
1009 mockT = tdutil.NewT("test")
1010 td.CmpTrue(t,
1011 tdhttp.NewTestAPI(mockT, mux).
1012 Head("/any").
1013 CmpStatus(200).
1014 CmpHeader(containsKey).
1015 CmpXMLBody(struct{ Test string }{}).
1016 Failed())
1017 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body should not be empty'")
1018 td.CmpContains(t, mockT.LogBuf(), "Response body is empty!")
1019 td.CmpContains(t, mockT.LogBuf(), "Body cannot be empty when using CmpXMLBody")
1020 })
1021
1022 t.Run("Response error", func(t *testing.T) {
1023 mockT := tdutil.NewT("test")
1024 td.CmpTrue(t,
1025 tdhttp.NewTestAPI(mockT, mux).
1026 Get("/any").
1027 CmpResponse(nil).
1028 Failed())
1029 td.CmpContains(t, mockT.LogBuf(), "Failed test 'full response should match'")
1030 td.CmpContains(t, mockT.LogBuf(), "Response: values differ")
1031 td.CmpContains(t, mockT.LogBuf(), "got: (*http.Response)(")
1032 td.CmpContains(t, mockT.LogBuf(), "expected: nil")
1033
1034 // Error followed by a success: Failed() should return true anyway
1035 mockT = tdutil.NewT("test")
1036 td.CmpTrue(t,
1037 tdhttp.NewTestAPI(mockT, mux).
1038 Get("/any").
1039 CmpResponse(nil). // fails
1040 CmpResponse(td.Ignore()). // succeeds
1041 Failed())
1042
1043 // Without AutoDumpResponse
1044 mockT = tdutil.NewT("test")
1045 td.CmpTrue(t,
1046 tdhttp.NewTestAPI(mockT, mux).
1047 Get("/any").
1048 Name("my test").
1049 CmpResponse(nil).
1050 Failed())
1051 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: full response should match'")
1052 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))
1053
1054 // AutoDumpResponse
1055 mockT = tdutil.NewT("test")
1056 td.CmpTrue(t,
1057 tdhttp.NewTestAPI(mockT, mux).
1058 AutoDumpResponse().
1059 Get("/any").
1060 Name("my test").
1061 CmpResponse(nil).
1062 Failed())
1063 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: full response should match'")
1064 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))
1065
1066 mockT = tdutil.NewT("test")
1067 td.CmpTrue(t,
1068 tdhttp.NewTestAPI(mockT, mux).
1069 Name("my test").
1070 CmpResponse(nil).
1071 Failed())
1072 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")
1073 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")
1074 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")
1075 })
1076
1077 t.Run("Request error", func(t *testing.T) {
1078 var ta *tdhttp.TestAPI
1079 checkFatal := func(fn func()) {
1080 mockT := tdutil.NewT("test")
1081 td.CmpTrue(t, mockT.CatchFailNow(func() {
1082 ta = tdhttp.NewTestAPI(mockT, mux)
1083 fn()
1084 }))
1085 td.Cmp(t,
1086 mockT.LogBuf(),
1087 td.Contains("newRequestParams... can only contains string, http.Header, ([]*|*|)http.Cookie, url.Values, tdhttp.Q and func(*http.Request) error, not bool"),
1088 )
1089 }
1090
1091 empty := strings.NewReader("")
1092
1093 checkFatal(func() { ta.Get("/path", true) })
1094 checkFatal(func() { ta.Head("/path", true) })
1095 checkFatal(func() { ta.Options("/path", empty, true) })
1096 checkFatal(func() { ta.Post("/path", empty, true) })
1097 checkFatal(func() { ta.PostForm("/path", nil, true) })
1098 checkFatal(func() { ta.PostMultipartFormData("/path", &tdhttp.MultipartBody{}, true) })
1099 checkFatal(func() { ta.Put("/path", empty, true) })
1100 checkFatal(func() { ta.Patch("/path", empty, true) })
1101 checkFatal(func() { ta.Delete("/path", empty, true) })
1102
1103 checkFatal(func() { ta.NewJSONRequest("ZIP", "/path", nil, true) })
1104 checkFatal(func() { ta.PostJSON("/path", nil, true) })
1105 checkFatal(func() { ta.PutJSON("/path", nil, true) })
1106 checkFatal(func() { ta.PatchJSON("/path", nil, true) })
1107 checkFatal(func() { ta.DeleteJSON("/path", nil, true) })
1108
1109 checkFatal(func() { ta.NewXMLRequest("ZIP", "/path", nil, true) })
1110 checkFatal(func() { ta.PostXML("/path", nil, true) })
1111 checkFatal(func() { ta.PutXML("/path", nil, true) })
1112 checkFatal(func() { ta.PatchXML("/path", nil, true) })
1113 checkFatal(func() { ta.DeleteXML("/path", nil, true) })
1114 })
1115
1116 t.Run("Request params", func(t *testing.T) {
1117 ta := tdhttp.NewTestAPI(t, mux)
1118
1119 ta.Get("/hq/json",
1120 "X-Test", "pipo",
1121 tdhttp.Q{"a": "b"},
1122 http.Cookie{Name: "cook1", Value: "val1"}).
1123 CmpJSONBody(td.JSON(`{
1124 "header": SuperMapOf({
1125 "X-Test": ["pipo"]
1126 }),
1127 "query_params": {
1128 "a": ["b"]
1129 }
1130 }`))
1131
1132 ta.DefaultRequestParams(
1133 "X-Zip", "test",
1134 tdhttp.Q{"x": "y"},
1135 http.Cookie{Name: "cook9", Value: "val9"},
1136 func(r *http.Request) error {
1137 r.Header.Add("X-Hook", "1")
1138 return nil
1139 },
1140 func(r *http.Request) error {
1141 r.Header.Add("X-Hook", "2")
1142 return nil
1143 })
1144
1145 ta.Get("/hq/json").
1146 CmpJSONBody(td.JSON(`{
1147 "header": SuperMapOf({
1148 "X-Hook": ["1", "2"],
1149 "X-Zip": ["test"],
1150 "Cookie": ["cook9=val9"]
1151 }),
1152 "query_params": {
1153 "x": ["y"]
1154 }
1155 }`))
1156
1157 ta.Get("/hq/json",
1158 "X-Test", "pipo",
1159 tdhttp.Q{"a": "b"},
1160 http.Cookie{Name: "cook1", Value: "val1"}).
1161 CmpJSONBody(td.JSON(`{
1162 "header": SuperMapOf({
1163 "X-Hook": ["1", "2"],
1164 "X-Test": ["pipo"],
1165 "X-Zip": ["test"],
1166 "Cookie": ["cook1=val1; cook9=val9"]
1167 }),
1168 "query_params": {
1169 "x": ["y"],
1170 "a": ["b"]
1171 }
1172 }`))
1173
1174 ta.Get("/hq/json",
1175 "X-Zip", "override",
1176 tdhttp.Q{"x": "override"},
1177 http.Cookie{Name: "cook9", Value: "override"},
1178 func(r *http.Request) error {
1179 r.Header.Add("X-Hook", "3")
1180 return nil
1181 }).
1182 CmpJSONBody(td.JSON(`{
1183 "header": SuperMapOf({
1184 "X-Hook": ["3", "1", "2"],
1185 "X-Zip": ["override"],
1186 "Cookie": ["cook9=override"]
1187 }),
1188 "query_params": {
1189 "x": ["override"]
1190 }
1191 }`))
1192
1193 // Replace previously defined hooks
1194 ta.DefaultHook(func(r *http.Request) error {
1195 r.Header.Add("X-Hook", "4")
1196 return nil
1197 })
1198 ta.Get("/hq/json",
1199 func(r *http.Request) error {
1200 r.Header.Add("X-Hook", "3")
1201 return nil
1202 }).
1203 CmpJSONBody(td.JSON(`{
1204 "header": SuperMapOf({
1205 "X-Hook": ["3", "4"],
1206 "X-Zip": ["test"],
1207 "Cookie": ["cook9=val9"]
1208 }),
1209 "query_params": {
1210 "x": ["y"]
1211 }
1212 }`))
1213
1214 // Replace previously defined header values
1215 ta.DefaultHeader(http.Header{"x-zip": {"new"}, "x-test": {"yo"}})
1216 ta.Get("/hq/json").
1217 CmpJSONBody(td.JSON(`{
1218 "header": SuperMapOf({
1219 "X-Hook": ["4"],
1220 "X-Zip": ["new"],
1221 "X-Test": ["yo"],
1222 "Cookie": ["cook9=val9"]
1223 }),
1224 "query_params": {
1225 "x": ["y"]
1226 }
1227 }`))
1228
1229 t.Run("hook failures", func(t *testing.T) {
1230 tt := tdutil.NewT("test")
1231 ta := tdhttp.NewTestAPI(tt, mux)
1232
1233 hook := func(r *http.Request) error {
1234 return fmt.Errorf("hook failure")
1235 }
1236
1237 if td.CmpTrue(t, tt.CatchFailNow(func() { ta.Get("/hq/json", hook) })) {
1238 td.CmpContains(t, tt.LogBuf(), "hook failed: hook failure")
1239 }
1240
1241 ta = ta.DefaultRequestParams(hook)
1242 if td.CmpTrue(t, tt.CatchFailNow(func() { ta.Get("/hq/json") })) {
1243 td.CmpContains(t, tt.LogBuf(), "hook failed: hook failure")
1244 }
1245 })
1246 })
1247 }
1248
1249 func TestWith(t *testing.T) {
1250 mux := server()
1251
1252 ta := tdhttp.NewTestAPI(tdutil.NewT("test1"), mux)
1253
1254 td.CmpFalse(t, ta.Head("/any").CmpStatus(200).Failed())
1255
1256 nt := tdutil.NewT("test2")
1257
1258 nta := ta.With(nt)
1259
1260 td.Cmp(t, nta.T(), td.Not(td.Shallow(ta.T())))
1261
1262 td.CmpTrue(t, nta.CmpStatus(200).Failed()) // as no request sent yet
1263 td.CmpContains(t, nt.LogBuf(),
1264 "A request must be sent before testing status, header, body or full response")
1265
1266 td.CmpFalse(t, ta.CmpStatus(200).Failed()) // request already sent, so OK
1267
1268 nt = tdutil.NewT("test3")
1269 nta = ta.With(nt)
1270
1271 td.CmpTrue(t, nta.Head("/any").
1272 CmpStatus(400).
1273 OrDumpResponse().
1274 Failed())
1275 td.CmpContains(t, nt.LogBuf(), "Response.Status: values differ")
1276 td.CmpContains(t, nt.LogBuf(), "X-Testdeep-Method: HEAD") // Header dumped
1277 }
1278
1279 func TestClone(t *testing.T) {
1280 mux := server()
1281
1282 ta := tdhttp.NewTestAPI(t, mux)
1283 nta := ta.Clone().DefaultRequestParams(
1284 "X-Test", "bingo", "X-Zip", "OK",
1285 tdhttp.Q{"a": "pizza", "b": "kiss"},
1286 http.Cookie{Name: "cook1", Value: "VAL1"},
1287 )
1288
1289 td.Cmp(t, nta.T(), td.Shallow(ta.T()), "ta and nta share the same testing.TB")
1290 td.Cmp(t, nta, td.Struct(nil, td.StructFields{
1291 "defaultHeader": http.Header{"X-Test": {"bingo"}, "X-Zip": {"OK"}},
1292 "defaultQParams": url.Values{"a": {"pizza"}, "b": {"kiss"}},
1293 "defaultCookies": []*http.Cookie{
1294 {Name: "cook1", Value: "VAL1"},
1295 },
1296 }), "nta modified successfully")
1297 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1298 "defaultHeader": nil,
1299 "defaultQParams": nil,
1300 "defaultCookies": nil,
1301 }), "ta was not modified")
1302 }
1303
1304 func TestDefaultRequestParams(t *testing.T) {
1305 mux := server()
1306
1307 ta := tdhttp.NewTestAPI(tdutil.NewT("test1"), mux)
1308
1309 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1310 "defaultHeader": nil,
1311 "defaultQParams": nil,
1312 "defaultCookies": nil,
1313 }))
1314
1315 ta.DefaultRequestParams("X-Test", "pipo")
1316 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1317 "defaultHeader": http.Header{"X-Test": {"pipo"}},
1318 "defaultQParams": nil,
1319 "defaultCookies": nil,
1320 }))
1321
1322 ta.DefaultRequestParams(tdhttp.Q{"a": "zip"})
1323 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1324 "defaultHeader": nil,
1325 "defaultQParams": url.Values{"a": {"zip"}},
1326 "defaultCookies": nil,
1327 }))
1328
1329 ta.DefaultRequestParams(http.Cookie{Name: "cook1", Value: "val1"})
1330 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1331 "defaultHeader": nil,
1332 "defaultQParams": nil,
1333 "defaultCookies": []*http.Cookie{{Name: "cook1", Value: "val1"}},
1334 }))
1335
1336 ta.DefaultRequestParams()
1337 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1338 "defaultHeader": nil,
1339 "defaultQParams": nil,
1340 "defaultCookies": nil,
1341 }))
1342
1343 ta.DefaultRequestParams(
1344 "X-Test", "pipo",
1345 tdhttp.Q{"a": "zip"},
1346 http.Cookie{Name: "cook1", Value: "val1"})
1347 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1348 "defaultHeader": http.Header{"X-Test": {"pipo"}},
1349 "defaultQParams": url.Values{"a": {"zip"}},
1350 "defaultCookies": []*http.Cookie{{Name: "cook1", Value: "val1"}},
1351 }))
1352
1353 ta.AddDefaultRequestParams()
1354 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1355 "defaultHeader": http.Header{"X-Test": {"pipo"}},
1356 "defaultQParams": url.Values{"a": {"zip"}},
1357 "defaultCookies": []*http.Cookie{{Name: "cook1", Value: "val1"}},
1358 }))
1359
1360 ta.AddDefaultRequestParams(
1361 "X-Zip", "OK",
1362 tdhttp.Q{"b": "kiss"},
1363 http.Cookie{Name: "cook2", Value: "val2"})
1364 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1365 "defaultHeader": http.Header{"X-Test": {"pipo"}, "X-Zip": {"OK"}},
1366 "defaultQParams": url.Values{"a": {"zip"}, "b": {"kiss"}},
1367 "defaultCookies": []*http.Cookie{
1368 {Name: "cook2", Value: "val2"},
1369 {Name: "cook1", Value: "val1"},
1370 },
1371 }))
1372
1373 ta.AddDefaultRequestParams(
1374 "X-Test", "bingo", "X-Zip", "OK",
1375 tdhttp.Q{"a": "pizza", "b": "kiss"},
1376 http.Cookie{Name: "cook1", Value: "VAL1"},
1377 http.Cookie{Name: "cook2", Value: "val2"})
1378 td.Cmp(t, ta, td.Struct(nil, td.StructFields{
1379 "defaultHeader": http.Header{"X-Test": {"bingo"}, "X-Zip": {"OK"}},
1380 "defaultQParams": url.Values{"a": {"pizza"}, "b": {"kiss"}},
1381 "defaultCookies": []*http.Cookie{
1382 {Name: "cook1", Value: "VAL1"},
1383 {Name: "cook2", Value: "val2"},
1384 },
1385 }))
1386
1387 t.Run("DefaultRequestParams fatal", func(t *testing.T) {
1388 mockT := tdutil.NewT("test")
1389 td.CmpTrue(t, mockT.CatchFailNow(func() {
1390 ta = tdhttp.NewTestAPI(mockT, mux)
1391 ta.DefaultRequestParams(123)
1392 }))
1393 td.Cmp(t,
1394 mockT.LogBuf(),
1395 td.Contains("newRequestParams... can only contains"))
1396 })
1397
1398 t.Run("AddDefaultRequestParams fatal", func(t *testing.T) {
1399 mockT := tdutil.NewT("test")
1400 td.CmpTrue(t, mockT.CatchFailNow(func() {
1401 ta = tdhttp.NewTestAPI(mockT, mux)
1402 ta.AddDefaultRequestParams(123)
1403 }))
1404 td.Cmp(t,
1405 mockT.LogBuf(),
1406 td.Contains("newRequestParams... can only contains"))
1407 })
1408 }
1409
1410 func TestOr(t *testing.T) {
1411 mux := server()
1412
1413 t.Run("Success", func(t *testing.T) {
1414 var orCalled bool
1415 for i, fn := range []any{
1416 func(body string) { orCalled = true },
1417 func(t *td.T, body string) { orCalled = true },
1418 func(body []byte) { orCalled = true },
1419 func(t *td.T, body []byte) { orCalled = true },
1420 func(t *td.T, r *httptest.ResponseRecorder) { orCalled = true },
1421 } {
1422 orCalled = false
1423 // As CmpStatus succeeds, Or function is not called
1424 td.CmpFalse(t,
1425 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).
1426 Head("/any").
1427 CmpStatus(200).
1428 Or(fn).
1429 Failed(),
1430 "Not failed #%d", i)
1431 td.CmpFalse(t, orCalled, "called #%d", i)
1432 }
1433 })
1434
1435 t.Run("No request sent", func(t *testing.T) {
1436 var ok, orCalled bool
1437 for i, fn := range []any{
1438 func(body string) { orCalled = true; ok = body == "" },
1439 func(t *td.T, body string) { orCalled = true; ok = t != nil && body == "" },
1440 func(body []byte) { orCalled = true; ok = body == nil },
1441 func(t *td.T, body []byte) { orCalled = true; ok = t != nil && body == nil },
1442 func(t *td.T, r *httptest.ResponseRecorder) { orCalled = true; ok = t != nil && r == nil },
1443 } {
1444 orCalled, ok = false, false
1445 // Check status without sending a request → fail
1446 td.CmpTrue(t,
1447 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).
1448 CmpStatus(123).
1449 Or(fn).
1450 Failed(),
1451 "Failed #%d", i)
1452 td.CmpTrue(t, orCalled, "called #%d", i)
1453 td.CmpTrue(t, ok, "OK #%d", i)
1454 }
1455 })
1456
1457 t.Run("Empty bodies", func(t *testing.T) {
1458 var ok, orCalled bool
1459 for i, fn := range []any{
1460 func(body string) { orCalled = true; ok = body == "" },
1461 func(t *td.T, body string) { orCalled = true; ok = t != nil && body == "" },
1462 func(body []byte) { orCalled = true; ok = body == nil },
1463 func(t *td.T, body []byte) { orCalled = true; ok = t != nil && body == nil },
1464 func(t *td.T, r *httptest.ResponseRecorder) {
1465 orCalled = true
1466 ok = t != nil && r != nil && r.Body.Len() == 0
1467 },
1468 } {
1469 orCalled, ok = false, false
1470 // HEAD /any = no body + CmpStatus fails
1471 td.CmpTrue(t,
1472 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).
1473 Head("/any").
1474 CmpStatus(123).
1475 Or(fn).
1476 Failed(),
1477 "Failed #%d", i)
1478 td.CmpTrue(t, orCalled, "called #%d", i)
1479 td.CmpTrue(t, ok, "OK #%d", i)
1480 }
1481 })
1482
1483 t.Run("Body", func(t *testing.T) {
1484 var ok, orCalled bool
1485 for i, fn := range []any{
1486 func(body string) { orCalled = true; ok = body == "GET!" },
1487 func(t *td.T, body string) { orCalled = true; ok = t != nil && body == "GET!" },
1488 func(body []byte) { orCalled = true; ok = string(body) == "GET!" },
1489 func(t *td.T, body []byte) { orCalled = true; ok = t != nil && string(body) == "GET!" },
1490 func(t *td.T, r *httptest.ResponseRecorder) {
1491 orCalled = true
1492 ok = t != nil && r != nil && r.Body.String() == "GET!"
1493 },
1494 } {
1495 orCalled, ok = false, false
1496 // GET /any = "GET!" body + CmpStatus fails
1497 td.CmpTrue(t,
1498 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).
1499 Get("/any").
1500 CmpStatus(123).
1501 Or(fn).
1502 Failed(),
1503 "Failed #%d", i)
1504 td.CmpTrue(t, orCalled, "called #%d", i)
1505 td.CmpTrue(t, ok, "OK #%d", i)
1506 }
1507 })
1508
1509 tt := tdutil.NewT("test")
1510 ta := tdhttp.NewTestAPI(tt, mux)
1511 if td.CmpTrue(t, tt.CatchFailNow(func() { ta.Or(123) })) {
1512 td.CmpContains(t, tt.LogBuf(),
1513 "usage: Or(func([*td.T,]string) | func([*td.T,][]byte) | func(*td.T,*httptest.ResponseRecorder)), but received int as 1st parameter")
1514 }
1515 }
1516
1517 func TestRun(t *testing.T) {
1518 mux := server()
1519
1520 ta := tdhttp.NewTestAPI(tdutil.NewT("test"), mux)
1521
1522 ok := ta.Run("Test", func(ta *tdhttp.TestAPI) {
1523 td.CmpFalse(t, ta.Get("/any").CmpStatus(200).Failed())
1524 })
1525 td.CmpTrue(t, ok)
1526
1527 ok = ta.Run("Test", func(ta *tdhttp.TestAPI) {
1528 td.CmpTrue(t, ta.Get("/any").CmpStatus(123).Failed())
1529 })
1530 td.CmpFalse(t, ok)
1531 }