Best Go-testdeep code snippet using tdhttp.CmpXMLResponse
http_test.go
Source:http_test.go
...378 Status: 242,379 Body: JResp{Name: op},380 }))381}382func TestCmpXMLResponse(tt *testing.T) {383 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {384 w.Header().Add("X-TestDeep", "foobar")385 w.WriteHeader(242)386 fmt.Fprintln(w, `<XResp><name>Bob</name></XResp>`)387 })388 type XResp struct {389 Name string `xml:"name"`390 }391 t := td.NewT(tt)392 for _, curTest := range []CmpResponseTest{393 // Success394 {395 Name: "XML OK",396 Handler: handler,397 Success: true,398 ExpectedResp: tdhttp.Response{399 Status: 242,400 Header: http.Header{"X-Testdeep": []string{"foobar"}},401 Body: XResp{Name: "Bob"},402 },403 },404 {405 Name: "XML ptr OK",406 Handler: handler,407 Success: true,408 ExpectedResp: tdhttp.Response{409 Status: 242,410 Header: http.Header{"X-Testdeep": []string{"foobar"}},411 Body: &XResp{Name: "Bob"},412 },413 },414 // Failure415 {416 Name: "XML failure",417 Handler: handler,418 Success: false,419 ExpectedResp: tdhttp.Response{420 // xml.Unmarshal does not raise an error when trying to421 // unmarshal in an int, as json does...422 Body: func() {},423 },424 ExpectedLogs: []string{425 `~ Failed test 'body unmarshaling'426\s+unmarshal\(Response\.Body\): should NOT be an error427\s+got: .*unknown type func\(\).*428\s+expected: nil`,429 `~ Received response:430\s+\x60(?s:.+?)431\s+432\s+<XResp><name>Bob</name></XResp>433\s+\x60434`, // check the complete body is shown435 },436 },437 } {438 t.Run(curTest.Name,439 func(t *td.T) {440 testCmpResponse(t, tdhttp.CmpXMLResponse, "CmpXMLResponse", curTest)441 })442 t.Run(curTest.Name+" TestAPI",443 func(t *td.T) {444 testTestAPI(t, (*tdhttp.TestAPI).CmpXMLBody, "CmpXMLBody", curTest)445 })446 }447}448var logsViz = strings.NewReplacer(449 " ", "·",450 "\t", "â",451 "\r", "<cr>",452)453func testLogs(t *td.T, mockT *tdutil.T, curTest CmpResponseTest) {454 t.Helper()455 dumpLogs := !t.Cmp(mockT.Failed(), !curTest.Success, "test failure")456 for _, expectedLog := range curTest.ExpectedLogs {457 if strings.HasPrefix(expectedLog, "~") {458 re := regexp.MustCompile(expectedLog[1:])459 if !re.MatchString(mockT.LogBuf()) {460 t.Errorf(`logs do not match "%s" regexp`, re)461 dumpLogs = true462 }463 } else if !strings.Contains(mockT.LogBuf(), expectedLog) {464 t.Errorf(`"%s" not found in test logs`, expectedLog)465 dumpLogs = true466 }467 }468 if dumpLogs {469 t.Errorf(`Test logs: "%s"`, logsViz.Replace(mockT.LogBuf()))470 }471}472func testCmpResponse(t *td.T,473 cmp func(testing.TB, *http.Request, func(http.ResponseWriter, *http.Request), tdhttp.Response, ...any) bool,474 cmpName string,475 curTest CmpResponseTest,476) {477 t.Helper()478 mockT := tdutil.NewT(cmpName)479 t.Cmp(cmp(mockT,480 httptest.NewRequest("GET", "/path", nil),481 curTest.Handler,482 curTest.ExpectedResp),483 curTest.Success)484 testLogs(t, mockT, curTest)485}486func testTestAPI(t *td.T,487 cmpBody func(*tdhttp.TestAPI, any) *tdhttp.TestAPI,488 cmpName string,489 curTest CmpResponseTest,490) {491 t.Helper()492 mockT := tdutil.NewT(cmpName)493 ta := tdhttp.NewTestAPI(mockT, http.HandlerFunc(curTest.Handler)).494 Get("/path")495 if curTest.ExpectedResp.Status != nil {496 ta.CmpStatus(curTest.ExpectedResp.Status)497 }498 if curTest.ExpectedResp.Header != nil {499 ta.CmpHeader(curTest.ExpectedResp.Header)500 }501 if curTest.ExpectedResp.Cookies != nil {502 ta.CmpCookies(curTest.ExpectedResp.Cookies)503 }504 cmpBody(ta, curTest.ExpectedResp.Body)505 t.Cmp(ta.Failed(), !curTest.Success)506 testLogs(t, mockT, curTest)507}508func TestMux(t *testing.T) {509 mux := http.NewServeMux()510 // GET /text511 mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) {512 if req.Method != "GET" {513 http.NotFound(w, req)514 return515 }516 w.Header().Set("Content-Type", "text/plain")517 w.WriteHeader(http.StatusOK)518 fmt.Fprintf(w, "Text result!")519 })520 // GET /json521 mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {522 w.Header().Set("Content-Type", "application/json")523 w.WriteHeader(http.StatusOK)524 if req.Method != "GET" {525 fmt.Fprintf(w, `{"code":404,"message":"Not found"}`)526 return527 }528 fmt.Fprintf(w, `{"comment":"JSON result!"}`)529 })530 // GET /xml531 mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) {532 if req.Method != "GET" {533 http.NotFound(w, req)534 return535 }536 w.Header().Set("Content-Type", "application/xml")537 w.WriteHeader(http.StatusOK)538 fmt.Fprintf(w, `<XResp><comment>XML result!</comment></XResp>`)539 })540 //541 // Check GET /text route542 t.Run("/text route", func(t *testing.T) {543 tdhttp.CmpResponse(t, tdhttp.NewRequest("GET", "/text", nil),544 mux.ServeHTTP,545 tdhttp.Response{546 Status: http.StatusOK,547 Header: td.SuperMapOf(http.Header{548 "Content-Type": []string{"text/plain"},549 }, nil),550 Body: "Text result!",551 },552 "GET /text should return 200 + text/plain + Text result!")553 tdhttp.CmpResponse(t, tdhttp.NewRequest("PATCH", "/text", nil),554 mux.ServeHTTP,555 tdhttp.Response{556 Status: http.StatusNotFound,557 Body: td.Ignore(),558 },559 "PATCH /text should return Not Found")560 t.Run("/text route via CmpResponseFunc", tdhttp.CmpResponseFunc(561 tdhttp.NewRequest("GET", "/text", nil),562 mux.ServeHTTP,563 tdhttp.Response{564 Status: http.StatusOK,565 Header: td.SuperMapOf(http.Header{566 "Content-Type": []string{"text/plain"},567 }, nil),568 Body: "Text result!",569 }))570 t.Run("/text route via CmpMarshaledResponseFunc", tdhttp.CmpMarshaledResponseFunc(571 tdhttp.NewRequest("GET", "/text", nil),572 mux.ServeHTTP,573 func(body []byte, target any) error {574 *target.(*string) = string(body)575 return nil576 },577 tdhttp.Response{578 Status: http.StatusOK,579 Header: td.SuperMapOf(http.Header{580 "Content-Type": []string{"text/plain"},581 }, nil),582 Body: "Text result!",583 }))584 })585 //586 // Check GET /json587 t.Run("/json route", func(t *testing.T) {588 type JResp struct {589 Comment string `json:"comment"`590 }591 tdhttp.CmpJSONResponse(t, tdhttp.NewRequest("GET", "/json", nil),592 mux.ServeHTTP,593 tdhttp.Response{594 Status: http.StatusOK,595 Header: td.SuperMapOf(http.Header{596 "Content-Type": []string{"application/json"},597 }, nil),598 Body: JResp{Comment: "JSON result!"},599 },600 "GET /json should return 200 + application/json + comment=JSON result!")601 tdhttp.CmpJSONResponse(t, tdhttp.NewRequest("GET", "/json", nil),602 mux.ServeHTTP,603 tdhttp.Response{604 Status: http.StatusOK,605 Header: td.SuperMapOf(http.Header{606 "Content-Type": []string{"application/json"},607 }, nil),608 Body: td.Struct(JResp{}, td.StructFields{609 "Comment": td.Contains("result!"),610 }),611 },612 "GET /json should return 200 + application/json + comment=~result!")613 t.Run("/json route via CmpJSONResponseFunc", tdhttp.CmpJSONResponseFunc(614 tdhttp.NewRequest("GET", "/json", nil),615 mux.ServeHTTP,616 tdhttp.Response{617 Status: http.StatusOK,618 Header: td.SuperMapOf(http.Header{619 "Content-Type": []string{"application/json"},620 }, nil),621 Body: JResp{Comment: "JSON result!"},622 }))623 // We expect to receive a specific message, but a complete624 // different one is received (here a Not Found, as PUT is used).625 // In this case, a log message tell us that nothing has been set626 // during unmarshaling AND the received body should be dumped627 t.Run("zeroed body", func(tt *testing.T) {628 t := td.NewT(tt)629 mockT := tdutil.NewT("zeroed_body")630 ok := tdhttp.CmpJSONResponse(mockT,631 tdhttp.NewRequest("PUT", "/json", nil),632 mux.ServeHTTP,633 tdhttp.Response{634 Status: http.StatusOK,635 Header: td.SuperMapOf(http.Header{636 "Content-Type": []string{"application/json"},637 }, nil),638 Body: JResp{Comment: "JSON result!"},639 })640 t.False(ok)641 t.True(mockT.Failed())642 t.Contains(mockT.LogBuf(), "nothing has been set during unmarshaling")643 t.Contains(mockT.LogBuf(), "Received response:")644 })645 })646 //647 // Check GET /xml648 t.Run("/xml route", func(t *testing.T) {649 type XResp struct {650 Comment string `xml:"comment"`651 }652 tdhttp.CmpXMLResponse(t, tdhttp.NewRequest("GET", "/xml", nil),653 mux.ServeHTTP,654 tdhttp.Response{655 Status: http.StatusOK,656 Header: td.SuperMapOf(http.Header{657 "Content-Type": []string{"application/xml"},658 }, nil),659 Body: XResp{Comment: "XML result!"},660 },661 "GET /xml should return 200 + application/xml + comment=XML result!")662 tdhttp.CmpXMLResponse(t, tdhttp.NewRequest("GET", "/xml", nil),663 mux.ServeHTTP,664 tdhttp.Response{665 Status: http.StatusOK,666 Header: td.SuperMapOf(http.Header{667 "Content-Type": []string{"application/xml"},668 }, nil),669 Body: td.Struct(XResp{}, td.StructFields{670 "Comment": td.Contains("result!"),671 }),672 },673 "GET /xml should return 200 + application/xml + comment=~result!")674 t.Run("/xml route via CmpXMLResponseFunc", tdhttp.CmpXMLResponseFunc(675 tdhttp.NewRequest("GET", "/xml", nil),676 mux.ServeHTTP,677 tdhttp.Response{678 Status: http.StatusOK,679 Header: td.SuperMapOf(http.Header{680 "Content-Type": []string{"application/xml"},681 }, nil),682 Body: td.Struct(XResp{}, td.StructFields{683 "Comment": td.Contains("result!"),684 }),685 }))686 // We expect to receive a specific message into a not specific687 // type (behind the TestDeep operator). The XML unmarshaling688 // fails, so a log message should tell us to be more clear689 // concerning the expected body type (in case it is the origin of690 // the problem).691 t.Run("Unmarshal is failing", func(tt *testing.T) {692 t := td.NewT(tt)693 mockT := tdutil.NewT("Unmarshal_is_failing")694 ok := tdhttp.CmpXMLResponse(mockT,695 tdhttp.NewRequest("PUT", "/xml", nil),696 mux.ServeHTTP,697 tdhttp.Response{698 Status: http.StatusOK,699 Header: td.SuperMapOf(http.Header{700 "Content-Type": []string{"application/xml"},701 }, nil),702 // This TestDeep operators combination is absurd. It is only703 // intended to avoid CmpXMLResponse detects the expected body704 // type705 Body: td.Any(XResp{Comment: "XML result!"}, 12),706 })707 t.False(ok)708 t.True(mockT.Failed())709 t.Contains(mockT.LogBuf(),710 "Cannot guess the body expected type as Any TestDeep")711 t.Contains(mockT.LogBuf(),712 "You can try All(Isa(EXPECTED_TYPE), Any(â¦)) to disambiguateâ¦")713 t.Contains(mockT.LogBuf(), "Received response:")714 })715 })716}...
http.go
Source:http.go
...196 json.Unmarshal,197 expectedResp,198 args...)199}200// CmpXMLResponse is used to match an XML response body. req201// is launched against handler. If expectedResp.Body is202// non-nil, the response body is [xml.Unmarshal]'ed. The response is203// then tested against expectedResp.204//205// args... are optional and allow to name the test, a t.Log() done206// before starting any test. If len(args) > 1 and the first item of207// args is a string and contains a '%' rune then [fmt.Fprintf] is used208// to compose the name, else args are passed to [fmt.Fprint].209//210// It returns true if the tests succeed, false otherwise.211//212// ok := tdhttp.CmpXMLResponse(t,213// tdhttp.Get("/person/42"),214// myAPI.ServeHTTP,215// Response{216// Status: http.StatusOK,217// Header: td.ContainsKey("X-Custom-Header"),218// Body: Person{219// ID: 42,220// Name: "Bob",221// Age: 26,222// },223// },224// "/person/{id} route")225//226// Response.Status, Response.Header and Response.Body fields can all227// be [td.TestDeep] operators as it is for Response.Header field228// here. Otherwise, Response.Status should be an int, Response.Header229// a [http.Header] and Response.Body any type one can [xml.Unmarshal]230// into.231//232// If Response.Status and Response.Header are omitted (or nil), they233// are not tested.234//235// If Response.Body is omitted (or nil), it means the body response236// has to be empty. If you want to ignore the body response, use237// [td.Ignore] explicitly.238//239// See [TestAPI] type and its methods for more flexible tests.240func CmpXMLResponse(t testing.TB,241 req *http.Request,242 handler func(w http.ResponseWriter, r *http.Request),243 expectedResp Response,244 args ...any,245) bool {246 t.Helper()247 return CmpMarshaledResponse(t,248 req,249 handler,250 xml.Unmarshal,251 expectedResp,252 args...)253}254// CmpMarshaledResponseFunc returns a function ready to be used with255// [testing.T.Run], calling [CmpMarshaledResponse] behind the scene. As it256// is intended to be used in conjunction with [testing.T.Run] which257// names the sub-test, the test name part (args...) is voluntary258// omitted.259//260// t.Run("Subtest name", tdhttp.CmpMarshaledResponseFunc(261// tdhttp.Get("/text"),262// mux.ServeHTTP,263// tdhttp.Response{264// Status: http.StatusOK,265// }))266//267// See [CmpMarshaledResponse] for details.268//269// See [TestAPI] type and its methods for more flexible tests.270func CmpMarshaledResponseFunc(req *http.Request,271 handler func(w http.ResponseWriter, r *http.Request),272 unmarshal func([]byte, any) error,273 expectedResp Response) func(t *testing.T) {274 return func(t *testing.T) {275 t.Helper()276 CmpMarshaledResponse(t, req, handler, unmarshal, expectedResp)277 }278}279// CmpResponseFunc returns a function ready to be used with280// [testing.T.Run], calling [CmpResponse] behind the scene. As it is281// intended to be used in conjunction with [testing.T.Run] which names282// the sub-test, the test name part (args...) is voluntary omitted.283//284// t.Run("Subtest name", tdhttp.CmpResponseFunc(285// tdhttp.Get("/text"),286// mux.ServeHTTP,287// tdhttp.Response{288// Status: http.StatusOK,289// }))290//291// See [CmpResponse] documentation for details.292//293// See [TestAPI] type and its methods for more flexible tests.294func CmpResponseFunc(req *http.Request,295 handler func(w http.ResponseWriter, r *http.Request),296 expectedResp Response) func(t *testing.T) {297 return func(t *testing.T) {298 t.Helper()299 CmpResponse(t, req, handler, expectedResp)300 }301}302// CmpJSONResponseFunc returns a function ready to be used with303// [testing.T.Run], calling [CmpJSONResponse] behind the scene. As it is304// intended to be used in conjunction with [testing.T.Run] which names305// the sub-test, the test name part (args...) is voluntary omitted.306//307// t.Run("Subtest name", tdhttp.CmpJSONResponseFunc(308// tdhttp.Get("/json"),309// mux.ServeHTTP,310// tdhttp.Response{311// Status: http.StatusOK,312// Body: JResp{Comment: "expected comment!"},313// }))314//315// See [CmpJSONResponse] documentation for details.316//317// See [TestAPI] type and its methods for more flexible tests.318func CmpJSONResponseFunc(req *http.Request,319 handler func(w http.ResponseWriter, r *http.Request),320 expectedResp Response) func(t *testing.T) {321 return func(t *testing.T) {322 t.Helper()323 CmpJSONResponse(t, req, handler, expectedResp)324 }325}326// CmpXMLResponseFunc returns a function ready to be used with327// [testing.T.Run], calling [CmpXMLResponse] behind the scene. As it is328// intended to be used in conjunction with [testing.T.Run] which names329// the sub-test, the test name part (args...) is voluntary omitted.330//331// t.Run("Subtest name", tdhttp.CmpXMLResponseFunc(332// tdhttp.Get("/xml"),333// mux.ServeHTTP,334// tdhttp.Response{335// Status: http.StatusOK,336// Body: JResp{Comment: "expected comment!"},337// }))338//339// See [CmpXMLResponse] documentation for details.340//341// See [TestAPI] type and its methods for more flexible tests.342func CmpXMLResponseFunc(req *http.Request,343 handler func(w http.ResponseWriter, r *http.Request),344 expectedResp Response) func(t *testing.T) {345 return func(t *testing.T) {346 t.Helper()347 CmpXMLResponse(t, req, handler, expectedResp)348 }349}...
CmpXMLResponse
Using AI Code Generation
1import (2func TestCompareXMLResponse(t *testing.T) {3 resp := &http.Response{4 Body: ioutil.NopCloser([]byte(`<?xml version="1.0" encoding="UTF-8"?><response><status>success</status></response>`)),5 }6 actualResp := &http.Response{7 Body: ioutil.NopCloser([]byte(`<?xml version="1.0" encoding="UTF-8"?><response><status>success</status></response>`)),8 }9 if tdhttp.CmpXMLResponse(resp, actualResp) {10 fmt.Println("XML response comparison successful")11 } else {12 fmt.Println("XML response comparison failed")13 }14 if tdhttp.CmpXMLResponse(resp, actualResp) {15 fmt.Println("XML response comparison successful")16 } else {17 fmt.Println("XML response comparison failed")18 }19}20import (21func TestCompareXMLResponse(t *testing.T) {22 resp := &http.Response{23 Body: ioutil.NopCloser([]byte(`<?xml version="1.0" encoding="UTF-8"?><response><status>success</status></response>`)),24 }25 actualResp := &http.Response{
CmpXMLResponse
Using AI Code Generation
1import (2func main() {3 tdhttpObj := tdhttp.New()4 fmt.Println(tdhttpObj.CmpXMLResponse(`<root><child1>1</child1><child2>2</child2></root>`, `<root><child1>1</child1><child2>2</child2></root>`, false, true))5 fmt.Println(tdhttpObj.CmpXMLResponse(`<root><child1>1</child1><child2>2</child2></root>`, `<root><child2>2</child2><child1>1</child1></root>`, true, true))6 fmt.Println(tdhttpObj.CmpXMLResponse(`<root><child1>1</child1><child2>2</child2></root>`, `<root><child1>1</child1><child2>2</child2></root>`, true, false))7 fmt.Println(tdhttpObj.CmpXMLResponse(`<root><child1>1</child1><child2>2</child2></root>`, `<root><child2>2</child2><child1>1</child1></root>`, true, false))8}
CmpXMLResponse
Using AI Code Generation
1import (2func Test_CmpXMLResponse(t *testing.T) {3 result, err = tdhttp.CmpXMLResponse(url, xml)4 if err != nil {5 fmt.Println("Error: ", err)6 } else {7 fmt.Println("Result: ", result)8 }9}
CmpXMLResponse
Using AI Code Generation
1import (2func main() {3 var httpobj tdhttp.NewHTTPObject()4 httpobj.SetHTTPMethod("GET")5 httpobj.SetRequestHeader("Accept", "text/html")6 httpobj.SetRequestBody("Hello World")7 httpobj.SendRequest()8 fmt.Println(httpobj.GetResponseBody())9 fmt.Println(httpobj.GetResponseHeader())10 fmt.Println(httpobj.GetResponseStatus())11 fmt.Println(httpobj.GetResponseStatusCode())12 fmt.Println(httpobj.GetResponseTime())13 fmt.Println(httpobj.CmpXMLResponse("response.xml"))14}15import (16func main() {17 var httpobj tdhttp.NewHTTPObject()18 httpobj.SetHTTPMethod("GET")19 httpobj.SetRequestHeader("Accept", "text/html")20 httpobj.SetRequestBody("Hello World")21 httpobj.SendRequest()22 fmt.Println(httpobj.GetResponseBody())23 fmt.Println(httpobj.GetResponseHeader())24 fmt.Println(httpobj.GetResponseStatus())25 fmt.Println(httpobj.GetResponseStatusCode())26 fmt.Println(httpobj.GetResponseTime())27 fmt.Println(httpobj.CmpJSONResponse("response.json"))28}29import (30func main() {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!