Debian Codegraph @

helpers/tdhttp/http_test.go

raw
1 // Copyright (c) 2019, 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 "fmt"
11 "net/http"
12 "net/http/httptest"
13 "os"
14 "regexp"
15 "strings"
16 "testing"
17
18 "github.com/maxatome/go-testdeep/helpers/tdhttp"
19 "github.com/maxatome/go-testdeep/helpers/tdutil"
20 "github.com/maxatome/go-testdeep/internal/color"
21 "github.com/maxatome/go-testdeep/td"
22 )
23
24 func TestMain(m *testing.M) {
25 color.SaveState()
26 os.Exit(m.Run())
27 }
28
29 type CmpResponseTest struct {
30 Name string
31 Handler func(w http.ResponseWriter, r *http.Request)
32 Success bool
33 ExpectedResp tdhttp.Response
34 ExpectedLogs []string
35 }
36
37 func TestCmpResponse(tt *testing.T) {
38 handlerNonEmpty := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
39 w.Header().Add("X-TestDeep", "foobar")
40 w.WriteHeader(242)
41 fmt.Fprintln(w, "text response") //nolint: errcheck
42 })
43
44 cookie := http.Cookie{Name: "Cookies-Testdeep", Value: "foobar"}
45 handlerWithCokies := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
46 w.Header().Add("X-TestDeep", "cookies")
47 http.SetCookie(w, &cookie)
48 w.WriteHeader(242)
49 })
50
51 handlerEmpty := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
52 w.Header().Add("X-TestDeep", "zip")
53 w.WriteHeader(424)
54 })
55
56 t := td.NewT(tt)
57
58 for _, curTest := range []CmpResponseTest{
59 // Non-empty success
60 {
61 Name: "string body only",
62 Handler: handlerNonEmpty,
63 Success: true,
64 ExpectedResp: tdhttp.Response{Body: "text response\n"},
65 },
66 {
67 Name: "[]byte status + body",
68 Handler: handlerNonEmpty,
69 Success: true,
70 ExpectedResp: tdhttp.Response{
71 Status: 242,
72 Body: []byte("text response\n"),
73 },
74 },
75 {
76 Name: "[]byte status + header + body",
77 Handler: handlerNonEmpty,
78 Success: true,
79 ExpectedResp: tdhttp.Response{
80 Status: 242,
81 Header: http.Header{"X-Testdeep": []string{"foobar"}},
82 Body: []byte("text response\n"),
83 },
84 },
85 {
86 Name: "with TestDeep operators",
87 Handler: handlerNonEmpty,
88 Success: true,
89 ExpectedResp: tdhttp.Response{
90 Status: td.Between(200, 300),
91 Header: td.ContainsKey("X-Testdeep"),
92 Body: td.All(
93 td.Isa(""), // enforces TypeBehind → string
94 td.Contains("response"),
95 ),
96 },
97 },
98 {
99 Name: "ignore body explicitly",
100 Handler: handlerNonEmpty,
101 Success: true,
102 ExpectedResp: tdhttp.Response{
103 Status: 242,
104 Header: http.Header{"X-Testdeep": []string{"foobar"}},
105 Body: td.Ignore(),
106 },
107 },
108 {
109 Name: "body just not empty",
110 Handler: handlerNonEmpty,
111 Success: true,
112 ExpectedResp: tdhttp.Response{
113 Status: 242,
114 Header: http.Header{"X-Testdeep": []string{"foobar"}},
115 Body: td.NotEmpty(),
116 },
117 },
118 // Non-empty failures
119 {
120 Name: "bad status",
121 Handler: handlerNonEmpty,
122 Success: false,
123 ExpectedResp: tdhttp.Response{Status: 243, Body: td.NotEmpty()},
124 ExpectedLogs: []string{
125 `~ Failed test 'status code should match'
126 \s+Response.Status: values differ
127 \s+got: 242
128 \s+expected: 243`,
129 `~ Received response:
130 \s+\x60(?s:.+?)
131 \s+
132 \s+text response
133 \s+\x60
134 `, // check the complete body is shown
135 },
136 },
137 {
138 Name: "bad body",
139 Handler: handlerNonEmpty,
140 Success: false,
141 ExpectedResp: tdhttp.Response{Body: "BAD!"},
142 ExpectedLogs: []string{
143 `~ Failed test 'body contents is OK'
144 \s+Response.Body: values differ
145 \s+got: \x60text response
146 \s+\x60
147 \s+expected: "BAD!"`,
148 },
149 },
150 {
151 Name: "bad body, as non-empty",
152 Handler: handlerNonEmpty,
153 Success: false,
154 ExpectedResp: tdhttp.Response{},
155 ExpectedLogs: []string{
156 `~ Failed test 'body should be empty'
157 \s+Response.Body is not empty
158 \s+got: not empty
159 \s+expected: empty`,
160 `~ Received response:
161 \s+\x60(?s:.+?)
162 \s+
163 \s+text response
164 \s+\x60
165 `, // check the complete body is shown
166 },
167 },
168 {
169 Name: "bad header",
170 Handler: handlerNonEmpty,
171 Success: false,
172 ExpectedResp: tdhttp.Response{
173 Header: http.Header{"X-Testdeep": []string{"zzz"}},
174 Body: td.NotEmpty(),
175 },
176 ExpectedLogs: []string{
177 `~ Failed test 'header should match'
178 \s+Response.Header\["X-Testdeep"\]\[0\]: values differ
179 \s+got: "foobar"
180 \s+expected: "zzz"`,
181 },
182 },
183 {
184 Name: "bad cookies",
185 Handler: handlerWithCokies,
186 Success: false,
187 ExpectedResp: tdhttp.Response{
188 Cookies: []*http.Cookie{{Name: "Cookies-Testdeep", Value: "squalala"}},
189 Body: td.Empty(),
190 },
191 ExpectedLogs: []string{
192 `~ Failed test 'cookies should match'
193 \s+Response.Cookie\[0\]\.Value: values differ
194 \s+got: "foobar"
195 \s+expected: "squalala"`,
196 },
197 },
198 {
199 Name: "good cookies",
200 Handler: handlerWithCokies,
201 Success: true,
202 ExpectedResp: tdhttp.Response{
203 Header: http.Header{
204 "X-Testdeep": []string{"cookies"},
205 "Set-Cookie": []string{cookie.String()},
206 },
207 Cookies: []*http.Cookie{&cookie},
208 Body: td.Empty(),
209 },
210 },
211 {
212 Name: "cannot unmarshal",
213 Handler: handlerNonEmpty,
214 Success: false,
215 ExpectedResp: tdhttp.Response{Body: 123},
216 ExpectedLogs: []string{
217 `~ Failed test 'body unmarshaling'
218 \s+unmarshal\(Response\.Body\): should NOT be an error
219 \s+got: .*Cmp(Response|Body) only accepts expected(Resp\.)?Body be a \[\]byte, a string or a TestDeep operator allowing to match these types, but not type int.*
220 \s+expected: nil`,
221 `~ Received response:
222 \s+\x60(?s:.+?)
223 \s+
224 \s+text response
225 \s+\x60
226 `, // check the complete body is shown
227 },
228 },
229 // Empty success
230 {
231 Name: "empty body",
232 Handler: handlerEmpty,
233 Success: true,
234 ExpectedResp: tdhttp.Response{
235 Status: 424,
236 Header: http.Header{"X-Testdeep": []string{"zip"}},
237 Body: nil,
238 },
239 },
240 // Empty failures
241 {
242 Name: "should not be empty",
243 Handler: handlerEmpty,
244 Success: false,
245 ExpectedResp: tdhttp.Response{Body: "NOT EMPTY!"},
246 ExpectedLogs: []string{
247 `~ Failed test 'body contents is OK'
248 \s+Response.Body: values differ
249 \s+got: ""
250 \s+expected: "NOT EMPTY!"`,
251 },
252 },
253 } {
254 t.Run(curTest.Name,
255 func(t *td.T) {
256 testCmpResponse(t, tdhttp.CmpResponse, "CmpResponse", curTest)
257 })
258
259 t.Run(curTest.Name+" TestAPI",
260 func(t *td.T) {
261 testTestAPI(t, (*tdhttp.TestAPI).CmpBody, "CmpBody", curTest)
262 })
263 }
264 }
265
266 func TestCmpJSONResponse(tt *testing.T) {
267 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
268 w.Header().Add("X-TestDeep", "foobar")
269 w.WriteHeader(242)
270 fmt.Fprintln(w, `{"name":"Bob"}`) //nolint: errcheck
271 })
272
273 type JResp struct {
274 Name string `json:"name"`
275 }
276
277 t := td.NewT(tt)
278
279 for _, curTest := range []CmpResponseTest{
280 // Success
281 {
282 Name: "JSON OK",
283 Handler: handler,
284 Success: true,
285 ExpectedResp: tdhttp.Response{
286 Status: 242,
287 Header: http.Header{"X-Testdeep": []string{"foobar"}},
288 Body: JResp{Name: "Bob"},
289 },
290 },
291 {
292 Name: "JSON ptr OK",
293 Handler: handler,
294 Success: true,
295 ExpectedResp: tdhttp.Response{
296 Status: 242,
297 Header: http.Header{"X-Testdeep": []string{"foobar"}},
298 Body: &JResp{Name: "Bob"},
299 },
300 },
301 // Failure
302 {
303 Name: "JSON failure",
304 Handler: handler,
305 Success: false,
306 ExpectedResp: tdhttp.Response{
307 Body: 123,
308 },
309 ExpectedLogs: []string{
310 `~ Failed test 'body unmarshaling'
311 \s+unmarshal\(Response\.Body\): should NOT be an error
312 \s+got: .*cannot unmarshal object into Go value of type int.*
313 \s+expected: nil`,
314 `~ Received response:
315 \s+\x60(?s:.+?)
316 \s+
317 \s+\{"name":"Bob"\}
318 \s+\x60
319 `, // check the complete body is shown
320 },
321 },
322 } {
323 t.Run(curTest.Name,
324 func(t *td.T) {
325 testCmpResponse(t, tdhttp.CmpJSONResponse, "CmpJSONResponse", curTest)
326 })
327
328 t.Run(curTest.Name+" TestAPI",
329 func(t *td.T) {
330 testTestAPI(t, (*tdhttp.TestAPI).CmpJSONBody, "CmpJSONBody", curTest)
331 })
332 }
333 }
334
335 func TestCmpJSONResponseAnchor(tt *testing.T) {
336 t := td.NewT(tt)
337
338 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
339 w.WriteHeader(242)
340 fmt.Fprintln(w, `{"name":"Bob"}`) //nolint: errcheck
341 })
342 req := httptest.NewRequest("GET", "/path", nil)
343
344 type JResp struct {
345 Name string `json:"name"`
346 }
347
348 // With *td.T
349 tdhttp.CmpJSONResponse(t, req, handler,
350 tdhttp.Response{
351 Status: 242,
352 Body: JResp{
353 Name: t.A(td.Re("(?i)bob"), "").(string),
354 },
355 })
356
357 // With *testing.T
358 tdhttp.CmpJSONResponse(tt, req, handler,
359 tdhttp.Response{
360 Status: 242,
361 Body: JResp{
362 Name: t.A(td.Re("(?i)bob"), "").(string),
363 },
364 })
365
366 func() {
367 defer t.AnchorsPersistTemporarily()()
368
369 op := t.A(td.Re("(?i)bob"), "").(string)
370
371 // All calls should succeed, as op persists
372 tdhttp.CmpJSONResponse(t, req, handler,
373 tdhttp.Response{
374 Status: 242,
375 Body: JResp{Name: op},
376 })
377
378 tdhttp.CmpJSONResponse(t, req, handler,
379 tdhttp.Response{
380 Status: 242,
381 Body: JResp{Name: op},
382 })
383
384 // Even with the original *testing.T instance (here tt)
385 tdhttp.CmpJSONResponse(tt, req, handler,
386 tdhttp.Response{
387 Status: 242,
388 Body: JResp{Name: op},
389 })
390 }()
391
392 // Failures
393 t.FailureIsFatal().False(t.DoAnchorsPersist()) // just to be sure
394
395 mt := td.NewT(tdutil.NewT("tdhttp_persistence_test"))
396 op := mt.A(td.Re("(?i)bob"), "").(string)
397
398 // First call should succeed
399 t.True(tdhttp.CmpJSONResponse(mt, req, handler,
400 tdhttp.Response{
401 Status: 242,
402 Body: JResp{Name: op},
403 }))
404
405 // Second one should fail, as previously anchored operator has been reset
406 t.False(tdhttp.CmpJSONResponse(mt, req, handler,
407 tdhttp.Response{
408 Status: 242,
409 Body: JResp{Name: op},
410 }))
411 }
412
413 func TestCmpXMLResponse(tt *testing.T) {
414 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
415 w.Header().Add("X-TestDeep", "foobar")
416 w.WriteHeader(242)
417 fmt.Fprintln(w, `<XResp><name>Bob</name></XResp>`) //nolint: errcheck
418 })
419
420 type XResp struct {
421 Name string `xml:"name"`
422 }
423
424 t := td.NewT(tt)
425
426 for _, curTest := range []CmpResponseTest{
427 // Success
428 {
429 Name: "XML OK",
430 Handler: handler,
431 Success: true,
432 ExpectedResp: tdhttp.Response{
433 Status: 242,
434 Header: http.Header{"X-Testdeep": []string{"foobar"}},
435 Body: XResp{Name: "Bob"},
436 },
437 },
438 {
439 Name: "XML ptr OK",
440 Handler: handler,
441 Success: true,
442 ExpectedResp: tdhttp.Response{
443 Status: 242,
444 Header: http.Header{"X-Testdeep": []string{"foobar"}},
445 Body: &XResp{Name: "Bob"},
446 },
447 },
448 // Failure
449 {
450 Name: "XML failure",
451 Handler: handler,
452 Success: false,
453 ExpectedResp: tdhttp.Response{
454 // xml.Unmarshal does not raise an error when trying to
455 // unmarshal in an int, as json does...
456 Body: func() {},
457 },
458 ExpectedLogs: []string{
459 `~ Failed test 'body unmarshaling'
460 \s+unmarshal\(Response\.Body\): should NOT be an error
461 \s+got: .*unknown type func\(\).*
462 \s+expected: nil`,
463 `~ Received response:
464 \s+\x60(?s:.+?)
465 \s+
466 \s+<XResp><name>Bob</name></XResp>
467 \s+\x60
468 `, // check the complete body is shown
469 },
470 },
471 } {
472 t.Run(curTest.Name,
473 func(t *td.T) {
474 testCmpResponse(t, tdhttp.CmpXMLResponse, "CmpXMLResponse", curTest)
475 })
476
477 t.Run(curTest.Name+" TestAPI",
478 func(t *td.T) {
479 testTestAPI(t, (*tdhttp.TestAPI).CmpXMLBody, "CmpXMLBody", curTest)
480 })
481 }
482 }
483
484 var logsViz = strings.NewReplacer(
485 " ", "·",
486 "\t", "→",
487 "\r", "<cr>",
488 )
489
490 func testLogs(t *td.T, mockT *tdutil.T, curTest CmpResponseTest) {
491 t.Helper()
492
493 dumpLogs := !t.Cmp(mockT.Failed(), !curTest.Success, "test failure")
494
495 for _, expectedLog := range curTest.ExpectedLogs {
496 if strings.HasPrefix(expectedLog, "~") {
497 re := regexp.MustCompile(expectedLog[1:])
498 if !re.MatchString(mockT.LogBuf()) {
499 t.Errorf(`logs do not match "%s" regexp`, re)
500 dumpLogs = true
501 }
502 } else if !strings.Contains(mockT.LogBuf(), expectedLog) {
503 t.Errorf(`"%s" not found in test logs`, expectedLog)
504 dumpLogs = true
505 }
506 }
507
508 if dumpLogs {
509 t.Errorf(`Test logs: "%s"`, logsViz.Replace(mockT.LogBuf()))
510 }
511 }
512
513 func testCmpResponse(t *td.T,
514 cmp func(testing.TB, *http.Request, func(http.ResponseWriter, *http.Request), tdhttp.Response, ...any) bool,
515 cmpName string,
516 curTest CmpResponseTest,
517 ) {
518 t.Helper()
519
520 mockT := tdutil.NewT(cmpName)
521
522 t.Cmp(cmp(mockT,
523 httptest.NewRequest("GET", "/path", nil),
524 curTest.Handler,
525 curTest.ExpectedResp),
526 curTest.Success)
527
528 testLogs(t, mockT, curTest)
529 }
530
531 func testTestAPI(t *td.T,
532 cmpBody func(*tdhttp.TestAPI, any) *tdhttp.TestAPI,
533 cmpName string,
534 curTest CmpResponseTest,
535 ) {
536 t.Helper()
537
538 mockT := tdutil.NewT(cmpName)
539
540 ta := tdhttp.NewTestAPI(mockT, http.HandlerFunc(curTest.Handler)).
541 Get("/path")
542
543 if curTest.ExpectedResp.Status != nil {
544 ta.CmpStatus(curTest.ExpectedResp.Status)
545 }
546
547 if curTest.ExpectedResp.Header != nil {
548 ta.CmpHeader(curTest.ExpectedResp.Header)
549 }
550
551 if curTest.ExpectedResp.Cookies != nil {
552 ta.CmpCookies(curTest.ExpectedResp.Cookies)
553 }
554
555 cmpBody(ta, curTest.ExpectedResp.Body)
556
557 t.Cmp(ta.Failed(), !curTest.Success)
558
559 testLogs(t, mockT, curTest)
560 }
561
562 func TestMux(t *testing.T) {
563 mux := http.NewServeMux()
564
565 // GET /text
566 mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) {
567 if req.Method != "GET" {
568 http.NotFound(w, req)
569 return
570 }
571 w.Header().Set("Content-Type", "text/plain")
572 w.WriteHeader(http.StatusOK)
573 fmt.Fprintf(w, "Text result!") //nolint: errcheck
574 })
575
576 // GET /json
577 mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
578 w.Header().Set("Content-Type", "application/json")
579 w.WriteHeader(http.StatusOK)
580 if req.Method != "GET" {
581 fmt.Fprintf(w, `{"code":404,"message":"Not found"}`) //nolint: errcheck
582 return
583 }
584 fmt.Fprintf(w, `{"comment":"JSON result!"}`) //nolint: errcheck
585 })
586
587 // GET /xml
588 mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) {
589 if req.Method != "GET" {
590 http.NotFound(w, req)
591 return
592 }
593 w.Header().Set("Content-Type", "application/xml")
594 w.WriteHeader(http.StatusOK)
595 fmt.Fprintf(w, `<XResp><comment>XML result!</comment></XResp>`) //nolint: errcheck
596 })
597
598 //
599 // Check GET /text route
600 t.Run("/text route", func(t *testing.T) {
601 tdhttp.CmpResponse(t, tdhttp.NewRequest("GET", "/text", nil),
602 mux.ServeHTTP,
603 tdhttp.Response{
604 Status: http.StatusOK,
605 Header: td.SuperMapOf(http.Header{
606 "Content-Type": []string{"text/plain"},
607 }, nil),
608 Body: "Text result!",
609 },
610 "GET /text should return 200 + text/plain + Text result!")
611
612 tdhttp.CmpResponse(t, tdhttp.NewRequest("PATCH", "/text", nil),
613 mux.ServeHTTP,
614 tdhttp.Response{
615 Status: http.StatusNotFound,
616 Body: td.Ignore(),
617 },
618 "PATCH /text should return Not Found")
619
620 t.Run("/text route via CmpResponseFunc", tdhttp.CmpResponseFunc(
621 tdhttp.NewRequest("GET", "/text", nil),
622 mux.ServeHTTP,
623 tdhttp.Response{
624 Status: http.StatusOK,
625 Header: td.SuperMapOf(http.Header{
626 "Content-Type": []string{"text/plain"},
627 }, nil),
628 Body: "Text result!",
629 }))
630
631 t.Run("/text route via CmpMarshaledResponseFunc", tdhttp.CmpMarshaledResponseFunc(
632 tdhttp.NewRequest("GET", "/text", nil),
633 mux.ServeHTTP,
634 func(body []byte, target any) error {
635 *target.(*string) = string(body)
636 return nil
637 },
638 tdhttp.Response{
639 Status: http.StatusOK,
640 Header: td.SuperMapOf(http.Header{
641 "Content-Type": []string{"text/plain"},
642 }, nil),
643 Body: "Text result!",
644 }))
645 })
646
647 //
648 // Check GET /json
649 t.Run("/json route", func(t *testing.T) {
650 type JResp struct {
651 Comment string `json:"comment"`
652 }
653 tdhttp.CmpJSONResponse(t, tdhttp.NewRequest("GET", "/json", nil),
654 mux.ServeHTTP,
655 tdhttp.Response{
656 Status: http.StatusOK,
657 Header: td.SuperMapOf(http.Header{
658 "Content-Type": []string{"application/json"},
659 }, nil),
660 Body: JResp{Comment: "JSON result!"},
661 },
662 "GET /json should return 200 + application/json + comment=JSON result!")
663
664 tdhttp.CmpJSONResponse(t, tdhttp.NewRequest("GET", "/json", nil),
665 mux.ServeHTTP,
666 tdhttp.Response{
667 Status: http.StatusOK,
668 Header: td.SuperMapOf(http.Header{
669 "Content-Type": []string{"application/json"},
670 }, nil),
671 Body: td.Struct(JResp{}, td.StructFields{
672 "Comment": td.Contains("result!"),
673 }),
674 },
675 "GET /json should return 200 + application/json + comment=~result!")
676
677 t.Run("/json route via CmpJSONResponseFunc", tdhttp.CmpJSONResponseFunc(
678 tdhttp.NewRequest("GET", "/json", nil),
679 mux.ServeHTTP,
680 tdhttp.Response{
681 Status: http.StatusOK,
682 Header: td.SuperMapOf(http.Header{
683 "Content-Type": []string{"application/json"},
684 }, nil),
685 Body: JResp{Comment: "JSON result!"},
686 }))
687
688 // We expect to receive a specific message, but a complete
689 // different one is received (here a Not Found, as PUT is used).
690 // In this case, a log message tell us that nothing has been set
691 // during unmarshaling AND the received body should be dumped
692 t.Run("zeroed body", func(tt *testing.T) {
693 t := td.NewT(tt)
694
695 mockT := tdutil.NewT("zeroed_body")
696 ok := tdhttp.CmpJSONResponse(mockT,
697 tdhttp.NewRequest("PUT", "/json", nil),
698 mux.ServeHTTP,
699 tdhttp.Response{
700 Status: http.StatusOK,
701 Header: td.SuperMapOf(http.Header{
702 "Content-Type": []string{"application/json"},
703 }, nil),
704 Body: JResp{Comment: "JSON result!"},
705 })
706
707 t.False(ok)
708 t.True(mockT.Failed())
709 t.Contains(mockT.LogBuf(), "nothing has been set during unmarshaling")
710 t.Contains(mockT.LogBuf(), "Received response:")
711 })
712 })
713
714 //
715 // Check GET /xml
716 t.Run("/xml route", func(t *testing.T) {
717 type XResp struct {
718 Comment string `xml:"comment"`
719 }
720 tdhttp.CmpXMLResponse(t, tdhttp.NewRequest("GET", "/xml", nil),
721 mux.ServeHTTP,
722 tdhttp.Response{
723 Status: http.StatusOK,
724 Header: td.SuperMapOf(http.Header{
725 "Content-Type": []string{"application/xml"},
726 }, nil),
727 Body: XResp{Comment: "XML result!"},
728 },
729 "GET /xml should return 200 + application/xml + comment=XML result!")
730
731 tdhttp.CmpXMLResponse(t, tdhttp.NewRequest("GET", "/xml", nil),
732 mux.ServeHTTP,
733 tdhttp.Response{
734 Status: http.StatusOK,
735 Header: td.SuperMapOf(http.Header{
736 "Content-Type": []string{"application/xml"},
737 }, nil),
738 Body: td.Struct(XResp{}, td.StructFields{
739 "Comment": td.Contains("result!"),
740 }),
741 },
742 "GET /xml should return 200 + application/xml + comment=~result!")
743
744 t.Run("/xml route via CmpXMLResponseFunc", tdhttp.CmpXMLResponseFunc(
745 tdhttp.NewRequest("GET", "/xml", nil),
746 mux.ServeHTTP,
747 tdhttp.Response{
748 Status: http.StatusOK,
749 Header: td.SuperMapOf(http.Header{
750 "Content-Type": []string{"application/xml"},
751 }, nil),
752 Body: td.Struct(XResp{}, td.StructFields{
753 "Comment": td.Contains("result!"),
754 }),
755 }))
756
757 // We expect to receive a specific message into a not specific
758 // type (behind the TestDeep operator). The XML unmarshaling
759 // fails, so a log message should tell us to be more clear
760 // concerning the expected body type (in case it is the origin of
761 // the problem).
762 t.Run("Unmarshal is failing", func(tt *testing.T) {
763 t := td.NewT(tt)
764
765 mockT := tdutil.NewT("Unmarshal_is_failing")
766 ok := tdhttp.CmpXMLResponse(mockT,
767 tdhttp.NewRequest("PUT", "/xml", nil),
768 mux.ServeHTTP,
769 tdhttp.Response{
770 Status: http.StatusOK,
771 Header: td.SuperMapOf(http.Header{
772 "Content-Type": []string{"application/xml"},
773 }, nil),
774 // This TestDeep operators combination is absurd. It is only
775 // intended to avoid CmpXMLResponse detects the expected body
776 // type
777 Body: td.Any(XResp{Comment: "XML result!"}, 12),
778 })
779
780 t.False(ok)
781 t.True(mockT.Failed())
782 t.Contains(mockT.LogBuf(),
783 "Cannot guess the body expected type as Any TestDeep")
784 t.Contains(mockT.LogBuf(),
785 "You can try All(Isa(EXPECTED_TYPE), Any(…)) to disambiguate…")
786 t.Contains(mockT.LogBuf(), "Received response:")
787 })
788 })
789 }