How to use cmp method of tdutil Package

Best Go-testdeep code snippet using tdutil.cmp

test_api_test.go

Source:test_api_test.go Github

copy

Full Screen

1// Copyright (c) 2020, Maxime Soulé2// All rights reserved.3//4// This source code is licensed under the BSD-style license found in the5// LICENSE file in the root directory of this source tree.6package tdhttp_test7import (8 "encoding/json"9 "fmt"10 "io"11 "net/http"12 "net/http/httptest"13 "net/url"14 "strings"15 "testing"16 "time"17 "github.com/maxatome/go-testdeep/helpers/tdhttp"18 "github.com/maxatome/go-testdeep/helpers/tdutil"19 "github.com/maxatome/go-testdeep/td"20)21func server() *http.ServeMux {22 mux := http.NewServeMux()23 mux.HandleFunc("/any", func(w http.ResponseWriter, req *http.Request) {24 w.Header().Set("X-TestDeep-Method", req.Method)25 if req.Method == "HEAD" {26 w.WriteHeader(http.StatusOK)27 return28 }29 w.Header().Set("Content-Type", "text/plain")30 w.WriteHeader(http.StatusOK)31 fmt.Fprintf(w, "%s!", req.Method)32 if req.ContentLength != 0 {33 w.Write([]byte("\n---\n")) //nolint: errcheck34 io.Copy(w, req.Body) //nolint: errcheck35 }36 })37 mux.HandleFunc("/any/json", func(w http.ResponseWriter, req *http.Request) {38 w.Header().Set("X-TestDeep-Method", req.Method)39 if req.Method == "HEAD" {40 w.WriteHeader(http.StatusOK)41 return42 }43 w.Header().Set("Content-Type", "application/json")44 w.WriteHeader(http.StatusOK)45 m := map[string]any{46 "method": req.Method,47 }48 if req.ContentLength != 0 {49 var body any50 if err := json.NewDecoder(req.Body).Decode(&body); err != nil {51 http.Error(w, err.Error(), http.StatusInternalServerError)52 return53 }54 m["body"] = body55 }56 json.NewEncoder(w).Encode(m) //nolint: errcheck57 })58 mux.HandleFunc("/mirror/json", func(w http.ResponseWriter, req *http.Request) {59 w.Header().Set("X-TestDeep-Method", req.Method)60 if req.Method == "HEAD" {61 w.WriteHeader(http.StatusOK)62 return63 }64 w.Header().Set("Content-Type", "application/json")65 w.WriteHeader(http.StatusOK)66 io.Copy(w, req.Body) //nolint: errcheck67 })68 mux.HandleFunc("/any/xml", func(w http.ResponseWriter, req *http.Request) {69 w.Header().Set("X-TestDeep-Method", req.Method)70 if req.Method == "HEAD" {71 w.WriteHeader(http.StatusOK)72 return73 }74 w.Header().Set("Content-Type", "application/xml")75 w.WriteHeader(http.StatusOK)76 fmt.Fprintf(w, `<XResp><method>%s</method>`, req.Method)77 if req.ContentLength != 0 {78 io.Copy(w, req.Body) //nolint: errcheck79 }80 w.Write([]byte(`</XResp>`)) //nolint: errcheck81 })82 mux.HandleFunc("/any/cookies", func(w http.ResponseWriter, req *http.Request) {83 w.Header().Set("X-TestDeep-Method", req.Method)84 if req.Method == "HEAD" {85 w.WriteHeader(http.StatusOK)86 return87 }88 w.Header().Set("Content-Type", "text/plain")89 http.SetCookie(w, &http.Cookie{90 Name: "first",91 Value: "cookie1",92 MaxAge: 123456,93 Expires: time.Date(2021, time.August, 12, 11, 22, 33, 0, time.UTC),94 })95 http.SetCookie(w, &http.Cookie{96 Name: "second",97 Value: "cookie2",98 MaxAge: 654321,99 })100 w.WriteHeader(http.StatusOK)101 fmt.Fprintf(w, "%s!", req.Method)102 if req.ContentLength != 0 {103 w.Write([]byte("\n---\n")) //nolint: errcheck104 io.Copy(w, req.Body) //nolint: errcheck105 }106 })107 mux.HandleFunc("/any/trailer", func(w http.ResponseWriter, req *http.Request) {108 w.Header().Set("Trailer", "X-TestDeep-Method")109 w.Header().Add("Trailer", "X-TestDeep-Foo")110 io.WriteString(w, "Hey!") //nolint: errcheck111 w.Header().Set("X-TestDeep-Method", req.Method)112 w.Header().Set("X-TestDeep-Foo", "bar")113 })114 return mux115}116func TestNewTestAPI(t *testing.T) {117 mux := server()118 containsKey := td.ContainsKey("X-Testdeep-Method")119 t.Run("No error", func(t *testing.T) {120 mockT := tdutil.NewT("test")121 td.CmpFalse(t,122 tdhttp.NewTestAPI(mockT, mux).123 Head("/any").124 CmpStatus(200).125 CmpHeader(containsKey).126 CmpHeader(td.SuperMapOf(http.Header{}, td.MapEntries{127 "X-Testdeep-Method": td.Bag(td.Re(`(?i)^head\z`)),128 })).129 NoBody().130 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {131 assert.Cmp(resp.StatusCode, 200)132 assert.Cmp(resp.Header, containsKey)133 assert.Smuggle(resp.Body, io.ReadAll, td.Empty())134 })).135 Failed())136 td.CmpEmpty(t, mockT.LogBuf())137 mockT = tdutil.NewT("test")138 td.CmpFalse(t,139 tdhttp.NewTestAPI(mockT, mux).140 Head("/any").141 CmpStatus(200).142 CmpHeader(containsKey).143 CmpBody(td.Empty()).144 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {145 assert.Cmp(resp.StatusCode, 200)146 assert.Cmp(resp.Header, containsKey)147 assert.Smuggle(resp.Body, io.ReadAll, td.Empty())148 })).149 Failed())150 td.CmpEmpty(t, mockT.LogBuf())151 mockT = tdutil.NewT("test")152 td.CmpFalse(t,153 tdhttp.NewTestAPI(mockT, mux).154 Get("/any").155 CmpStatus(200).156 CmpHeader(containsKey).157 CmpBody("GET!").158 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {159 assert.Cmp(resp.StatusCode, 200)160 assert.Cmp(resp.Header, containsKey)161 assert.Smuggle(resp.Body, io.ReadAll, td.String("GET!"))162 })).163 Failed())164 td.CmpEmpty(t, mockT.LogBuf())165 mockT = tdutil.NewT("test")166 td.CmpFalse(t,167 tdhttp.NewTestAPI(mockT, mux).168 Get("/any").169 CmpStatus(200).170 CmpHeader(containsKey).171 CmpBody(td.Contains("GET")).172 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {173 assert.Cmp(resp.StatusCode, 200)174 assert.Cmp(resp.Header, containsKey)175 assert.Smuggle(resp.Body, io.ReadAll, td.Contains("GET"))176 })).177 Failed())178 td.CmpEmpty(t, mockT.LogBuf())179 mockT = tdutil.NewT("test")180 td.CmpFalse(t,181 tdhttp.NewTestAPI(mockT, mux).182 Options("/any", strings.NewReader("OPTIONS body")).183 CmpStatus(200).184 CmpHeader(containsKey).185 CmpBody("OPTIONS!\n---\nOPTIONS body").186 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {187 assert.Cmp(resp.StatusCode, 200)188 assert.Cmp(resp.Header, containsKey)189 assert.Smuggle(resp.Body, io.ReadAll, td.String("OPTIONS!\n---\nOPTIONS body"))190 })).191 Failed())192 td.CmpEmpty(t, mockT.LogBuf())193 mockT = tdutil.NewT("test")194 td.CmpFalse(t,195 tdhttp.NewTestAPI(mockT, mux).196 Post("/any", strings.NewReader("POST body")).197 CmpStatus(200).198 CmpHeader(containsKey).199 CmpBody("POST!\n---\nPOST body").200 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {201 assert.Cmp(resp.StatusCode, 200)202 assert.Cmp(resp.Header, containsKey)203 assert.Smuggle(resp.Body, io.ReadAll, td.String("POST!\n---\nPOST body"))204 })).205 Failed())206 td.CmpEmpty(t, mockT.LogBuf())207 mockT = tdutil.NewT("test")208 td.CmpFalse(t,209 tdhttp.NewTestAPI(mockT, mux).210 PostForm("/any", url.Values{"p1": []string{"v1"}, "p2": []string{"v2"}}).211 CmpStatus(200).212 CmpHeader(containsKey).213 CmpBody("POST!\n---\np1=v1&p2=v2").214 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {215 assert.Cmp(resp.StatusCode, 200)216 assert.Cmp(resp.Header, containsKey)217 assert.Smuggle(resp.Body, io.ReadAll, td.String("POST!\n---\np1=v1&p2=v2"))218 })).219 Failed())220 td.CmpEmpty(t, mockT.LogBuf())221 mockT = tdutil.NewT("test")222 td.CmpFalse(t,223 tdhttp.NewTestAPI(mockT, mux).224 PostForm("/any", tdhttp.Q{"p1": "v1", "p2": "v2"}).225 CmpStatus(200).226 CmpHeader(containsKey).227 CmpBody("POST!\n---\np1=v1&p2=v2").228 CmpResponse(td.Code(func(assert *td.T, resp *http.Response) {229 assert.Cmp(resp.StatusCode, 200)230 assert.Cmp(resp.Header, containsKey)231 assert.Smuggle(resp.Body, io.ReadAll, td.String("POST!\n---\np1=v1&p2=v2"))232 })).233 Failed())234 td.CmpEmpty(t, mockT.LogBuf())235 mockT = tdutil.NewT("test")236 td.CmpFalse(t,237 tdhttp.NewTestAPI(mockT, mux).238 PostMultipartFormData("/any", &tdhttp.MultipartBody{239 Boundary: "BoUnDaRy",240 Parts: []*tdhttp.MultipartPart{241 tdhttp.NewMultipartPartString("pipo", "bingo"),242 },243 }).244 CmpStatus(200).245 CmpHeader(containsKey).246 CmpBody(strings.ReplaceAll(247 `POST!248---249--BoUnDaRy%CR250Content-Disposition: form-data; name="pipo"%CR251Content-Type: text/plain; charset=utf-8%CR252%CR253bingo%CR254--BoUnDaRy--%CR255`,256 "%CR", "\r")).257 Failed())258 td.CmpEmpty(t, mockT.LogBuf())259 mockT = tdutil.NewT("test")260 td.CmpFalse(t,261 tdhttp.NewTestAPI(mockT, mux).262 Put("/any", strings.NewReader("PUT body")).263 CmpStatus(200).264 CmpHeader(containsKey).265 CmpBody("PUT!\n---\nPUT body").266 Failed())267 td.CmpEmpty(t, mockT.LogBuf())268 mockT = tdutil.NewT("test")269 td.CmpFalse(t,270 tdhttp.NewTestAPI(mockT, mux).271 Patch("/any", strings.NewReader("PATCH body")).272 CmpStatus(200).273 CmpHeader(containsKey).274 CmpBody("PATCH!\n---\nPATCH body").275 Failed())276 td.CmpEmpty(t, mockT.LogBuf())277 mockT = tdutil.NewT("test")278 td.CmpFalse(t,279 tdhttp.NewTestAPI(mockT, mux).280 Delete("/any", strings.NewReader("DELETE body")).281 CmpStatus(200).282 CmpHeader(containsKey).283 CmpBody("DELETE!\n---\nDELETE body").284 Failed())285 td.CmpEmpty(t, mockT.LogBuf())286 })287 t.Run("No JSON error", func(t *testing.T) {288 requestBody := map[string]any{"hey": 123}289 expectedBody := func(m string) td.TestDeep {290 return td.JSON(`{"method": $1, "body": {"hey": 123}}`, m)291 }292 mockT := tdutil.NewT("test")293 td.CmpFalse(t,294 tdhttp.NewTestAPI(mockT, mux).295 NewJSONRequest("GET", "/mirror/json", json.RawMessage(`null`)).296 CmpStatus(200).297 CmpHeader(containsKey).298 CmpJSONBody(nil).299 Failed())300 td.CmpEmpty(t, mockT.LogBuf())301 mockT = tdutil.NewT("test")302 td.CmpFalse(t,303 tdhttp.NewTestAPI(mockT, mux).304 NewJSONRequest("ZIP", "/any/json", requestBody).305 CmpStatus(200).306 CmpHeader(containsKey).307 CmpJSONBody(expectedBody("ZIP")).308 Failed())309 td.CmpEmpty(t, mockT.LogBuf())310 mockT = tdutil.NewT("test")311 td.CmpFalse(t,312 tdhttp.NewTestAPI(mockT, mux).313 NewJSONRequest("ZIP", "/any/json", requestBody).314 CmpStatus(200).315 CmpHeader(containsKey).316 CmpJSONBody(td.JSONPointer("/body/hey", 123)).317 Failed())318 td.CmpEmpty(t, mockT.LogBuf())319 mockT = tdutil.NewT("test")320 td.CmpFalse(t,321 tdhttp.NewTestAPI(mockT, mux).322 PostJSON("/any/json", requestBody).323 CmpStatus(200).324 CmpHeader(containsKey).325 CmpJSONBody(expectedBody("POST")).326 Failed())327 td.CmpEmpty(t, mockT.LogBuf())328 mockT = tdutil.NewT("test")329 td.CmpFalse(t,330 tdhttp.NewTestAPI(mockT, mux).331 PutJSON("/any/json", requestBody).332 CmpStatus(200).333 CmpHeader(containsKey).334 CmpJSONBody(expectedBody("PUT")).335 Failed())336 td.CmpEmpty(t, mockT.LogBuf())337 mockT = tdutil.NewT("test")338 td.CmpFalse(t,339 tdhttp.NewTestAPI(mockT, mux).340 PatchJSON("/any/json", requestBody).341 CmpStatus(200).342 CmpHeader(containsKey).343 CmpJSONBody(expectedBody("PATCH")).344 Failed())345 td.CmpEmpty(t, mockT.LogBuf())346 mockT = tdutil.NewT("test")347 td.CmpFalse(t,348 tdhttp.NewTestAPI(mockT, mux).349 DeleteJSON("/any/json", requestBody).350 CmpStatus(200).351 CmpHeader(containsKey).352 CmpJSONBody(expectedBody("DELETE")).353 Failed())354 td.CmpEmpty(t, mockT.LogBuf())355 // With anchors356 type ReqBody struct {357 Hey int `json:"hey"`358 }359 type Resp struct {360 Method string `json:"method"`361 ReqBody ReqBody `json:"body"`362 }363 mockT = tdutil.NewT("test")364 tt := td.NewT(mockT)365 td.CmpFalse(t,366 tdhttp.NewTestAPI(mockT, mux).367 DeleteJSON("/any/json", requestBody).368 CmpStatus(200).369 CmpHeader(containsKey).370 CmpJSONBody(Resp{371 Method: tt.A(td.Re(`^(?i)delete\z`), "").(string),372 ReqBody: ReqBody{373 Hey: tt.A(td.Between(120, 130)).(int),374 },375 }).376 Failed())377 td.CmpEmpty(t, mockT.LogBuf())378 // JSON and root operator (here SuperMapOf)379 mockT = tdutil.NewT("test")380 td.CmpFalse(t,381 tdhttp.NewTestAPI(mockT, mux).382 PostJSON("/any/json", true).383 CmpStatus(200).384 CmpJSONBody(td.JSON(`SuperMapOf({"body":Ignore()})`)).385 Failed())386 td.CmpEmpty(t, mockT.LogBuf())387 // td.Bag+td.JSON388 mockT = tdutil.NewT("test")389 td.CmpFalse(t,390 tdhttp.NewTestAPI(mockT, mux).391 PostJSON("/mirror/json",392 json.RawMessage(`[{"name":"Bob"},{"name":"Alice"}]`)).393 CmpStatus(200).394 CmpJSONBody(td.Bag(395 td.JSON(`{"name":"Alice"}`),396 td.JSON(`{"name":"Bob"}`),397 )).398 Failed())399 td.CmpEmpty(t, mockT.LogBuf())400 // td.Bag+literal401 type People struct {402 Name string `json:"name"`403 }404 mockT = tdutil.NewT("test")405 td.CmpFalse(t,406 tdhttp.NewTestAPI(mockT, mux).407 PostJSON("/mirror/json",408 json.RawMessage(`[{"name":"Bob"},{"name":"Alice"}]`)).409 CmpStatus(200).410 CmpJSONBody(td.Bag(People{"Alice"}, People{"Bob"})).411 Failed())412 td.CmpEmpty(t, mockT.LogBuf())413 })414 t.Run("No XML error", func(t *testing.T) {415 type XBody struct {416 Hey int `xml:"hey"`417 }418 type XResp struct {419 Method string `xml:"method"`420 ReqBody *XBody `xml:"XBody"`421 }422 requestBody := XBody{Hey: 123}423 expectedBody := func(m string) XResp {424 return XResp{425 Method: m,426 ReqBody: &requestBody,427 }428 }429 mockT := tdutil.NewT("test")430 td.CmpFalse(t,431 tdhttp.NewTestAPI(mockT, mux).432 NewXMLRequest("ZIP", "/any/xml", requestBody).433 CmpStatus(200).434 CmpHeader(containsKey).435 CmpXMLBody(expectedBody("ZIP")).436 Failed())437 td.CmpEmpty(t, mockT.LogBuf())438 mockT = tdutil.NewT("test")439 td.CmpFalse(t,440 tdhttp.NewTestAPI(mockT, mux).441 PostXML("/any/xml", requestBody).442 CmpStatus(200).443 CmpHeader(containsKey).444 CmpXMLBody(expectedBody("POST")).445 Failed())446 td.CmpEmpty(t, mockT.LogBuf())447 mockT = tdutil.NewT("test")448 td.CmpFalse(t,449 tdhttp.NewTestAPI(mockT, mux).450 PutXML("/any/xml", requestBody).451 CmpStatus(200).452 CmpHeader(containsKey).453 CmpXMLBody(expectedBody("PUT")).454 Failed())455 td.CmpEmpty(t, mockT.LogBuf())456 mockT = tdutil.NewT("test")457 td.CmpFalse(t,458 tdhttp.NewTestAPI(mockT, mux).459 PatchXML("/any/xml", requestBody).460 CmpStatus(200).461 CmpHeader(containsKey).462 CmpXMLBody(expectedBody("PATCH")).463 Failed())464 td.CmpEmpty(t, mockT.LogBuf())465 mockT = tdutil.NewT("test")466 td.CmpFalse(t,467 tdhttp.NewTestAPI(mockT, mux).468 DeleteXML("/any/xml", requestBody).469 CmpStatus(200).470 CmpHeader(containsKey).471 CmpXMLBody(expectedBody("DELETE")).472 Failed())473 td.CmpEmpty(t, mockT.LogBuf())474 // With anchors475 mockT = tdutil.NewT("test")476 tt := td.NewT(mockT)477 td.CmpFalse(tt,478 tdhttp.NewTestAPI(mockT, mux).479 DeleteXML("/any/xml", requestBody).480 CmpStatus(200).481 CmpHeader(containsKey).482 CmpXMLBody(XResp{483 Method: tt.A(td.Re(`^(?i)delete\z`), "").(string),484 ReqBody: &XBody{485 Hey: tt.A(td.Between(120, 130)).(int),486 },487 }).488 Failed())489 td.CmpEmpty(t, mockT.LogBuf())490 })491 t.Run("Cookies", func(t *testing.T) {492 mockT := tdutil.NewT("test")493 td.CmpFalse(t,494 tdhttp.NewTestAPI(mockT, mux).495 Get("/any/cookies").496 CmpCookies([]*http.Cookie{497 {498 Name: "first",499 Value: "cookie1",500 MaxAge: 123456,501 Expires: time.Date(2021, time.August, 12, 11, 22, 33, 0, time.UTC),502 },503 {504 Name: "second",505 Value: "cookie2",506 MaxAge: 654321,507 },508 }).509 Failed())510 td.CmpEmpty(t, mockT.LogBuf())511 mockT = tdutil.NewT("test")512 td.CmpTrue(t,513 tdhttp.NewTestAPI(mockT, mux).514 Get("/any/cookies").515 CmpCookies([]*http.Cookie{516 {517 Name: "first",518 Value: "cookie1",519 MaxAge: 123456,520 Expires: time.Date(2021, time.August, 12, 11, 22, 33, 0, time.UTC),521 },522 }).523 Failed())524 td.CmpContains(t, mockT.LogBuf(),525 "Failed test 'cookies should match'")526 td.CmpContains(t, mockT.LogBuf(),527 "Response.Cookie: comparing slices, from index #1")528 // 2 cookies are here whatever their order is using Bag529 mockT = tdutil.NewT("test")530 td.CmpFalse(t,531 tdhttp.NewTestAPI(mockT, mux).532 Get("/any/cookies").533 CmpCookies(td.Bag(534 td.Smuggle("Name", "second"),535 td.Smuggle("Name", "first"),536 )).537 Failed())538 td.CmpEmpty(t, mockT.LogBuf())539 // Testing only Name & Value whatever their order is using Bag540 mockT = tdutil.NewT("test")541 td.CmpFalse(t,542 tdhttp.NewTestAPI(mockT, mux).543 Get("/any/cookies").544 CmpCookies(td.Bag(545 td.Struct(&http.Cookie{Name: "first", Value: "cookie1"}, nil),546 td.Struct(&http.Cookie{Name: "second", Value: "cookie2"}, nil),547 )).548 Failed())549 td.CmpEmpty(t, mockT.LogBuf())550 // Testing the presence of only one using SuperBagOf551 mockT = tdutil.NewT("test")552 td.CmpFalse(t,553 tdhttp.NewTestAPI(mockT, mux).554 Get("/any/cookies").555 CmpCookies(td.SuperBagOf(556 td.Struct(&http.Cookie{Name: "first", Value: "cookie1"}, nil),557 )).558 Failed())559 td.CmpEmpty(t, mockT.LogBuf())560 // Testing only the number of cookies561 mockT = tdutil.NewT("test")562 td.CmpFalse(t,563 tdhttp.NewTestAPI(mockT, mux).564 Get("/any/cookies").565 CmpCookies(td.Len(2)).566 Failed())567 td.CmpEmpty(t, mockT.LogBuf())568 // Error followed by a success: Failed() should return true anyway569 mockT = tdutil.NewT("test")570 td.CmpTrue(t,571 tdhttp.NewTestAPI(mockT, mux).572 Get("/any").573 CmpCookies(td.Len(100)). // fails574 CmpCookies(td.Len(2)). // succeeds575 Failed())576 td.CmpContains(t, mockT.LogBuf(),577 "Failed test 'cookies should match'")578 // AutoDumpResponse579 mockT = tdutil.NewT("test")580 td.CmpTrue(t,581 tdhttp.NewTestAPI(mockT, mux).582 AutoDumpResponse().583 Get("/any/cookies").584 Name("my test").585 CmpCookies(td.Len(100)).586 Failed())587 td.CmpContains(t, mockT.LogBuf(),588 "Failed test 'my test: cookies should match'")589 td.CmpContains(t, mockT.LogBuf(), "Response.Cookie: bad length")590 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))591 // Request not sent592 mockT = tdutil.NewT("test")593 ta := tdhttp.NewTestAPI(mockT, mux).594 Name("my test").595 CmpCookies(td.Len(2))596 td.CmpTrue(t, ta.Failed())597 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")598 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")599 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")600 td.CmpNot(t, mockT.LogBuf(), td.Contains("No response received yet\n"))601 })602 t.Run("Trailer", func(t *testing.T) {603 mockT := tdutil.NewT("test")604 td.CmpFalse(t,605 tdhttp.NewTestAPI(mockT, mux).606 Get("/any").607 CmpStatus(200).608 CmpTrailer(nil). // No trailer at all609 Failed())610 mockT = tdutil.NewT("test")611 td.CmpFalse(t,612 tdhttp.NewTestAPI(mockT, mux).613 Get("/any/trailer").614 CmpStatus(200).615 CmpTrailer(containsKey).616 Failed())617 mockT = tdutil.NewT("test")618 td.CmpFalse(t,619 tdhttp.NewTestAPI(mockT, mux).620 Get("/any/trailer").621 CmpStatus(200).622 CmpTrailer(http.Header{623 "X-Testdeep-Method": {"GET"},624 "X-Testdeep-Foo": {"bar"},625 }).626 Failed())627 // AutoDumpResponse628 mockT = tdutil.NewT("test")629 td.CmpTrue(t,630 tdhttp.NewTestAPI(mockT, mux).631 AutoDumpResponse().632 Get("/any/trailer").633 Name("my test").634 CmpTrailer(http.Header{}).635 Failed())636 td.CmpContains(t, mockT.LogBuf(),637 "Failed test 'my test: trailer should match'")638 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))639 // OrDumpResponse640 mockT = tdutil.NewT("test")641 td.CmpTrue(t,642 tdhttp.NewTestAPI(mockT, mux).643 Get("/any/trailer").644 Name("my test").645 CmpTrailer(http.Header{}).646 OrDumpResponse().647 OrDumpResponse(). // only one log648 Failed())649 td.CmpContains(t, mockT.LogBuf(),650 "Failed test 'my test: trailer should match'")651 logPos := strings.Index(mockT.LogBuf(), "Received response:\n")652 if td.Cmp(t, logPos, td.Gte(0)) {653 // Only one occurrence654 td.Cmp(t,655 strings.Index(mockT.LogBuf()[logPos+1:], "Received response:\n"),656 -1)657 }658 mockT = tdutil.NewT("test")659 ta := tdhttp.NewTestAPI(mockT, mux).660 Name("my test").661 CmpTrailer(http.Header{})662 td.CmpTrue(t, ta.Failed())663 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")664 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")665 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")666 td.CmpNot(t, mockT.LogBuf(), td.Contains("No response received yet\n"))667 end := len(mockT.LogBuf())668 ta.OrDumpResponse()669 td.CmpContains(t, mockT.LogBuf()[end:], "No response received yet\n")670 })671 t.Run("Status error", func(t *testing.T) {672 mockT := tdutil.NewT("test")673 td.CmpTrue(t,674 tdhttp.NewTestAPI(mockT, mux).675 Get("/any").676 CmpStatus(400).677 Failed())678 td.CmpContains(t, mockT.LogBuf(),679 "Failed test 'status code should match'")680 // Error followed by a success: Failed() should return true anyway681 mockT = tdutil.NewT("test")682 td.CmpTrue(t,683 tdhttp.NewTestAPI(mockT, mux).684 Get("/any").685 CmpStatus(400). // fails686 CmpStatus(200). // succeeds687 Failed())688 td.CmpContains(t, mockT.LogBuf(),689 "Failed test 'status code should match'")690 mockT = tdutil.NewT("test")691 td.CmpTrue(t,692 tdhttp.NewTestAPI(mockT, mux).693 Get("/any").694 Name("my test").695 CmpStatus(400).696 Failed())697 td.CmpContains(t, mockT.LogBuf(),698 "Failed test 'my test: status code should match'")699 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))700 // AutoDumpResponse701 mockT = tdutil.NewT("test")702 td.CmpTrue(t,703 tdhttp.NewTestAPI(mockT, mux).704 AutoDumpResponse().705 Get("/any").706 Name("my test").707 CmpStatus(400).708 Failed())709 td.CmpContains(t, mockT.LogBuf(),710 "Failed test 'my test: status code should match'")711 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))712 // OrDumpResponse713 mockT = tdutil.NewT("test")714 td.CmpTrue(t,715 tdhttp.NewTestAPI(mockT, mux).716 Get("/any").717 Name("my test").718 CmpStatus(400).719 OrDumpResponse().720 OrDumpResponse(). // only one log721 Failed())722 td.CmpContains(t, mockT.LogBuf(),723 "Failed test 'my test: status code should match'")724 logPos := strings.Index(mockT.LogBuf(), "Received response:\n")725 if td.Cmp(t, logPos, td.Gte(0)) {726 // Only one occurrence727 td.Cmp(t,728 strings.Index(mockT.LogBuf()[logPos+1:], "Received response:\n"),729 -1)730 }731 mockT = tdutil.NewT("test")732 ta := tdhttp.NewTestAPI(mockT, mux).733 Name("my test").734 CmpStatus(400)735 td.CmpTrue(t, ta.Failed())736 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")737 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")738 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")739 td.CmpNot(t, mockT.LogBuf(), td.Contains("No response received yet\n"))740 end := len(mockT.LogBuf())741 ta.OrDumpResponse()742 td.CmpContains(t, mockT.LogBuf()[end:], "No response received yet\n")743 })744 t.Run("Header error", func(t *testing.T) {745 mockT := tdutil.NewT("test")746 td.CmpTrue(t,747 tdhttp.NewTestAPI(mockT, mux).748 Get("/any").749 CmpHeader(td.Not(containsKey)).750 Failed())751 td.CmpContains(t, mockT.LogBuf(),752 "Failed test 'header should match'")753 // Error followed by a success: Failed() should return true anyway754 mockT = tdutil.NewT("test")755 td.CmpTrue(t,756 tdhttp.NewTestAPI(mockT, mux).757 Get("/any").758 CmpHeader(td.Not(containsKey)). // fails759 CmpHeader(td.Ignore()). // succeeds760 Failed())761 td.CmpContains(t, mockT.LogBuf(),762 "Failed test 'header should match'")763 mockT = tdutil.NewT("test")764 td.CmpTrue(t,765 tdhttp.NewTestAPI(mockT, mux).766 Get("/any").767 Name("my test").768 CmpHeader(td.Not(containsKey)).769 Failed())770 td.CmpContains(t, mockT.LogBuf(),771 "Failed test 'my test: header should match'")772 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))773 // AutoDumpResponse774 mockT = tdutil.NewT("test")775 td.CmpTrue(t,776 tdhttp.NewTestAPI(mockT, mux).777 AutoDumpResponse().778 Get("/any").779 Name("my test").780 CmpHeader(td.Not(containsKey)).781 Failed())782 td.CmpContains(t, mockT.LogBuf(),783 "Failed test 'my test: header should match'")784 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))785 mockT = tdutil.NewT("test")786 td.CmpTrue(t,787 tdhttp.NewTestAPI(mockT, mux).788 Name("my test").789 CmpHeader(td.Not(containsKey)).790 Failed())791 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")792 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")793 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")794 })795 t.Run("Body error", func(t *testing.T) {796 mockT := tdutil.NewT("test")797 td.CmpTrue(t,798 tdhttp.NewTestAPI(mockT, mux).799 Get("/any").800 CmpBody("xxx").801 Failed())802 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body contents is OK'")803 td.CmpContains(t, mockT.LogBuf(), "Response.Body: values differ\n")804 td.CmpContains(t, mockT.LogBuf(), `expected: "xxx"`)805 td.CmpContains(t, mockT.LogBuf(), `got: "GET!"`)806 // Error followed by a success: Failed() should return true anyway807 mockT = tdutil.NewT("test")808 td.CmpTrue(t,809 tdhttp.NewTestAPI(mockT, mux).810 Get("/any").811 CmpBody("xxx"). // fails812 CmpBody(td.Ignore()). // succeeds813 Failed())814 // Without AutoDumpResponse815 mockT = tdutil.NewT("test")816 td.CmpTrue(t,817 tdhttp.NewTestAPI(mockT, mux).818 Get("/any").819 Name("my test").820 CmpBody("xxx").821 Failed())822 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: body contents is OK'")823 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))824 // AutoDumpResponse825 mockT = tdutil.NewT("test")826 td.CmpTrue(t,827 tdhttp.NewTestAPI(mockT, mux).828 AutoDumpResponse().829 Get("/any").830 Name("my test").831 CmpBody("xxx").832 Failed())833 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: body contents is OK'")834 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))835 mockT = tdutil.NewT("test")836 td.CmpTrue(t,837 tdhttp.NewTestAPI(mockT, mux).838 Name("my test").839 CmpBody("xxx").840 Failed())841 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")842 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")843 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")844 // NoBody845 mockT = tdutil.NewT("test")846 td.CmpTrue(t,847 tdhttp.NewTestAPI(mockT, mux).848 Name("my test").849 NoBody().850 Failed())851 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")852 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")853 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")854 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))855 // Error followed by a success: Failed() should return true anyway856 mockT = tdutil.NewT("test")857 td.CmpTrue(t,858 tdhttp.NewTestAPI(mockT, mux).859 Name("my test").860 Head("/any").861 CmpBody("fail"). // fails862 NoBody(). // succeeds863 Failed())864 // No JSON body865 mockT = tdutil.NewT("test")866 td.CmpTrue(t,867 tdhttp.NewTestAPI(mockT, mux).868 Head("/any").869 CmpStatus(200).870 CmpHeader(containsKey).871 CmpJSONBody(json.RawMessage(`{}`)).872 Failed())873 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body should not be empty'")874 td.CmpContains(t, mockT.LogBuf(), "Response body is empty!")875 td.CmpContains(t, mockT.LogBuf(), "Body cannot be empty when using CmpJSONBody")876 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))877 // Error followed by a success: Failed() should return true anyway878 mockT = tdutil.NewT("test")879 td.CmpTrue(t,880 tdhttp.NewTestAPI(mockT, mux).881 Get("/any/json").882 CmpStatus(200).883 CmpHeader(containsKey).884 CmpJSONBody(json.RawMessage(`{}`)). // fails885 CmpJSONBody(td.Ignore()). // succeeds886 Failed())887 // No JSON body + AutoDumpResponse888 mockT = tdutil.NewT("test")889 td.CmpTrue(t,890 tdhttp.NewTestAPI(mockT, mux).891 AutoDumpResponse().892 Head("/any").893 CmpStatus(200).894 CmpHeader(containsKey).895 CmpJSONBody(json.RawMessage(`{}`)).896 Failed())897 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body should not be empty'")898 td.CmpContains(t, mockT.LogBuf(), "Response body is empty!")899 td.CmpContains(t, mockT.LogBuf(), "Body cannot be empty when using CmpJSONBody")900 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))901 // No XML body902 mockT = tdutil.NewT("test")903 td.CmpTrue(t,904 tdhttp.NewTestAPI(mockT, mux).905 Head("/any").906 CmpStatus(200).907 CmpHeader(containsKey).908 CmpXMLBody(struct{ Test string }{}).909 Failed())910 td.CmpContains(t, mockT.LogBuf(), "Failed test 'body should not be empty'")911 td.CmpContains(t, mockT.LogBuf(), "Response body is empty!")912 td.CmpContains(t, mockT.LogBuf(), "Body cannot be empty when using CmpXMLBody")913 })914 t.Run("Response error", func(t *testing.T) {915 mockT := tdutil.NewT("test")916 td.CmpTrue(t,917 tdhttp.NewTestAPI(mockT, mux).918 Get("/any").919 CmpResponse(nil).920 Failed())921 td.CmpContains(t, mockT.LogBuf(), "Failed test 'full response should match'")922 td.CmpContains(t, mockT.LogBuf(), "Response: values differ")923 td.CmpContains(t, mockT.LogBuf(), "got: (*http.Response)(")924 td.CmpContains(t, mockT.LogBuf(), "expected: nil")925 // Error followed by a success: Failed() should return true anyway926 mockT = tdutil.NewT("test")927 td.CmpTrue(t,928 tdhttp.NewTestAPI(mockT, mux).929 Get("/any").930 CmpResponse(nil). // fails931 CmpResponse(td.Ignore()). // succeeds932 Failed())933 // Without AutoDumpResponse934 mockT = tdutil.NewT("test")935 td.CmpTrue(t,936 tdhttp.NewTestAPI(mockT, mux).937 Get("/any").938 Name("my test").939 CmpResponse(nil).940 Failed())941 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: full response should match'")942 td.CmpNot(t, mockT.LogBuf(), td.Contains("Received response:\n"))943 // AutoDumpResponse944 mockT = tdutil.NewT("test")945 td.CmpTrue(t,946 tdhttp.NewTestAPI(mockT, mux).947 AutoDumpResponse().948 Get("/any").949 Name("my test").950 CmpResponse(nil).951 Failed())952 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: full response should match'")953 td.Cmp(t, mockT.LogBuf(), td.Contains("Received response:\n"))954 mockT = tdutil.NewT("test")955 td.CmpTrue(t,956 tdhttp.NewTestAPI(mockT, mux).957 Name("my test").958 CmpResponse(nil).959 Failed())960 td.CmpContains(t, mockT.LogBuf(), "Failed test 'my test: request is sent'\n")961 td.CmpContains(t, mockT.LogBuf(), "Request not sent!\n")962 td.CmpContains(t, mockT.LogBuf(), "A request must be sent before testing status, header, body or full response\n")963 })964 t.Run("Request error", func(t *testing.T) {965 var ta *tdhttp.TestAPI966 checkFatal := func(fn func()) {967 mockT := tdutil.NewT("test")968 td.CmpTrue(t, mockT.CatchFailNow(func() {969 ta = tdhttp.NewTestAPI(mockT, mux)970 fn()971 }))972 td.Cmp(t,973 mockT.LogBuf(),974 td.Contains("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool"),975 )976 }977 empty := strings.NewReader("")978 checkFatal(func() { ta.Get("/path", true) })979 checkFatal(func() { ta.Head("/path", true) })980 checkFatal(func() { ta.Options("/path", empty, true) })981 checkFatal(func() { ta.Post("/path", empty, true) })982 checkFatal(func() { ta.PostForm("/path", nil, true) })983 checkFatal(func() { ta.PostMultipartFormData("/path", &tdhttp.MultipartBody{}, true) })984 checkFatal(func() { ta.Put("/path", empty, true) })985 checkFatal(func() { ta.Patch("/path", empty, true) })986 checkFatal(func() { ta.Delete("/path", empty, true) })987 checkFatal(func() { ta.NewJSONRequest("ZIP", "/path", nil, true) })988 checkFatal(func() { ta.PostJSON("/path", nil, true) })989 checkFatal(func() { ta.PutJSON("/path", nil, true) })990 checkFatal(func() { ta.PatchJSON("/path", nil, true) })991 checkFatal(func() { ta.DeleteJSON("/path", nil, true) })992 checkFatal(func() { ta.NewXMLRequest("ZIP", "/path", nil, true) })993 checkFatal(func() { ta.PostXML("/path", nil, true) })994 checkFatal(func() { ta.PutXML("/path", nil, true) })995 checkFatal(func() { ta.PatchXML("/path", nil, true) })996 checkFatal(func() { ta.DeleteXML("/path", nil, true) })997 })998}999func TestWith(t *testing.T) {1000 mux := server()1001 ta := tdhttp.NewTestAPI(tdutil.NewT("test1"), mux)1002 td.CmpFalse(t, ta.Head("/any").CmpStatus(200).Failed())1003 nt := tdutil.NewT("test2")1004 nta := ta.With(nt)1005 td.Cmp(t, nta.T(), td.Not(td.Shallow(ta.T())))1006 td.CmpTrue(t, nta.CmpStatus(200).Failed()) // as no request sent yet1007 td.CmpContains(t, nt.LogBuf(),1008 "A request must be sent before testing status, header, body or full response")1009 td.CmpFalse(t, ta.CmpStatus(200).Failed()) // request already sent, so OK1010 nt = tdutil.NewT("test3")1011 nta = ta.With(nt)1012 td.CmpTrue(t, nta.Head("/any").1013 CmpStatus(400).1014 OrDumpResponse().1015 Failed())1016 td.CmpContains(t, nt.LogBuf(), "Response.Status: values differ")1017 td.CmpContains(t, nt.LogBuf(), "X-Testdeep-Method: HEAD") // Header dumped1018}1019func TestOr(t *testing.T) {1020 mux := server()1021 t.Run("Success", func(t *testing.T) {1022 var orCalled bool1023 for i, fn := range []any{1024 func(body string) { orCalled = true },1025 func(t *td.T, body string) { orCalled = true },1026 func(body []byte) { orCalled = true },1027 func(t *td.T, body []byte) { orCalled = true },1028 func(t *td.T, r *httptest.ResponseRecorder) { orCalled = true },1029 } {1030 orCalled = false1031 // As CmpStatus succeeds, Or function is not called1032 td.CmpFalse(t,1033 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).1034 Head("/any").1035 CmpStatus(200).1036 Or(fn).1037 Failed(),1038 "Not failed #%d", i)1039 td.CmpFalse(t, orCalled, "called #%d", i)1040 }1041 })1042 t.Run("No request sent", func(t *testing.T) {1043 var ok, orCalled bool1044 for i, fn := range []any{1045 func(body string) { orCalled = true; ok = body == "" },1046 func(t *td.T, body string) { orCalled = true; ok = t != nil && body == "" },1047 func(body []byte) { orCalled = true; ok = body == nil },1048 func(t *td.T, body []byte) { orCalled = true; ok = t != nil && body == nil },1049 func(t *td.T, r *httptest.ResponseRecorder) { orCalled = true; ok = t != nil && r == nil },1050 } {1051 orCalled, ok = false, false1052 // Check status without sending a request → fail1053 td.CmpTrue(t,1054 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).1055 CmpStatus(123).1056 Or(fn).1057 Failed(),1058 "Failed #%d", i)1059 td.CmpTrue(t, orCalled, "called #%d", i)1060 td.CmpTrue(t, ok, "OK #%d", i)1061 }1062 })1063 t.Run("Empty bodies", func(t *testing.T) {1064 var ok, orCalled bool1065 for i, fn := range []any{1066 func(body string) { orCalled = true; ok = body == "" },1067 func(t *td.T, body string) { orCalled = true; ok = t != nil && body == "" },1068 func(body []byte) { orCalled = true; ok = body == nil },1069 func(t *td.T, body []byte) { orCalled = true; ok = t != nil && body == nil },1070 func(t *td.T, r *httptest.ResponseRecorder) {1071 orCalled = true1072 ok = t != nil && r != nil && r.Body.Len() == 01073 },1074 } {1075 orCalled, ok = false, false1076 // HEAD /any = no body + CmpStatus fails1077 td.CmpTrue(t,1078 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).1079 Head("/any").1080 CmpStatus(123).1081 Or(fn).1082 Failed(),1083 "Failed #%d", i)1084 td.CmpTrue(t, orCalled, "called #%d", i)1085 td.CmpTrue(t, ok, "OK #%d", i)1086 }1087 })1088 t.Run("Body", func(t *testing.T) {1089 var ok, orCalled bool1090 for i, fn := range []any{1091 func(body string) { orCalled = true; ok = body == "GET!" },1092 func(t *td.T, body string) { orCalled = true; ok = t != nil && body == "GET!" },1093 func(body []byte) { orCalled = true; ok = string(body) == "GET!" },1094 func(t *td.T, body []byte) { orCalled = true; ok = t != nil && string(body) == "GET!" },1095 func(t *td.T, r *httptest.ResponseRecorder) {1096 orCalled = true1097 ok = t != nil && r != nil && r.Body.String() == "GET!"1098 },1099 } {1100 orCalled, ok = false, false1101 // GET /any = "GET!" body + CmpStatus fails1102 td.CmpTrue(t,1103 tdhttp.NewTestAPI(tdutil.NewT("test"), mux).1104 Get("/any").1105 CmpStatus(123).1106 Or(fn).1107 Failed(),1108 "Failed #%d", i)1109 td.CmpTrue(t, orCalled, "called #%d", i)1110 td.CmpTrue(t, ok, "OK #%d", i)1111 }1112 })1113 tt := tdutil.NewT("test")1114 ta := tdhttp.NewTestAPI(tt, mux)1115 if td.CmpTrue(t, tt.CatchFailNow(func() { ta.Or(123) })) {1116 td.CmpContains(t, tt.LogBuf(),1117 "usage: Or(func([*td.T,]string) | func([*td.T,][]byte) | func(*td.T,*httptest.ResponseRecorder)), but received int as 1st parameter")1118 }1119}1120func TestRun(t *testing.T) {1121 mux := server()1122 ta := tdhttp.NewTestAPI(tdutil.NewT("test"), mux)1123 ok := ta.Run("Test", func(ta *tdhttp.TestAPI) {1124 td.CmpFalse(t, ta.Get("/any").CmpStatus(200).Failed())1125 })1126 td.CmpTrue(t, ok)1127 ok = ta.Run("Test", func(ta *tdhttp.TestAPI) {1128 td.CmpTrue(t, ta.Get("/any").CmpStatus(123).Failed())1129 })1130 td.CmpFalse(t, ok)1131}...

Full Screen

Full Screen

check_test.go

Source:check_test.go Github

copy

Full Screen

...67}68func indent(str string, numSpc int) string {69 return strings.ReplaceAll(str, "\n", "\n\t"+strings.Repeat(" ", numSpc))70}71func cmpErrorStr(t *testing.T, err *ctxerr.Error,72 got string, expected expectedErrorMatch, fieldName string,73 args ...any,74) bool {75 t.Helper()76 if expected.Exact != "" && got != expected.Exact {77 t.Errorf(`%sError.%s mismatch78 got: %s79 expected: %s80 Full error:81 > %s`,82 tdutil.BuildTestName(args...),83 fieldName, indent(got, 10), indent(expected.Exact, 10),84 strings.ReplaceAll(err.Error(), "\n\t", "\n\t> "))85 return false86 }87 if expected.Contain != "" && !strings.Contains(got, expected.Contain) {88 t.Errorf(`%sError.%s mismatch89 got: %s90 should contain: %s91 Full error:92 > %s`,93 tdutil.BuildTestName(args...),94 fieldName,95 indent(got, 16), indent(expected.Contain, 16),96 strings.ReplaceAll(err.Error(), "\n\t", "\n\t> "))97 return false98 }99 if expected.Match != nil && !expected.Match.MatchString(got) {100 t.Errorf(`%sError.%s mismatch101 got: %s102 should match: %s103 Full error:104 > %s`,105 tdutil.BuildTestName(args...),106 fieldName,107 indent(got, 14), indent(expected.Match.String(), 14),108 strings.ReplaceAll(err.Error(), "\n\t", "\n\t> "))109 return false110 }111 return true112}113func matchError(t *testing.T, err *ctxerr.Error, expectedError expectedError,114 expectedIsTestDeep bool, args ...any,115) bool {116 t.Helper()117 if !cmpErrorStr(t, err, err.Message, expectedError.Message,118 "Message", args...) {119 return false120 }121 if !cmpErrorStr(t, err, err.Context.Path.String(), expectedError.Path,122 "Context.Path", args...) {123 return false124 }125 if !cmpErrorStr(t, err, err.GotString(), expectedError.Got, "Got", args...) {126 return false127 }128 if !cmpErrorStr(t, err,129 err.ExpectedString(), expectedError.Expected, "Expected", args...) {130 return false131 }132 if !cmpErrorStr(t, err,133 err.SummaryString(), expectedError.Summary, "Summary", args...) {134 return false135 }136 // If expected is a TestDeep, the Location should be set137 if expectedIsTestDeep {138 expectedError.Located = true139 }140 if expectedError.Located != err.Location.IsInitialized() {141 t.Errorf(`%sLocation of the origin of the error142 got: %v143 expected: %v`,144 tdutil.BuildTestName(args...), err.Location.IsInitialized(), expectedError.Located)145 return false146 }147 if expectedError.Located &&148 !strings.HasSuffix(err.Location.File, "_test.go") {149 t.Errorf(`%sFile of the origin of the error150 got: line %d of %s151 expected: *_test.go`,152 tdutil.BuildTestName(args...), err.Location.Line, err.Location.File)153 return false154 }155 if expectedError.Origin != nil {156 if err.Origin == nil {157 t.Errorf(`%sError should originate from another Error`,158 tdutil.BuildTestName(args...))159 return false160 }161 return matchError(t, err.Origin, *expectedError.Origin,162 expectedIsTestDeep, args...)163 }164 if err.Origin != nil {165 t.Errorf(`%sError should NOT originate from another Error`,166 tdutil.BuildTestName(args...))167 return false168 }169 return true170}171func _checkError(t *testing.T, got, expected any,172 expectedError expectedError, args ...any,173) bool {174 t.Helper()175 err := td.EqDeeplyError(got, expected)176 if err == nil {177 t.Errorf("%sAn Error should have occurred", tdutil.BuildTestName(args...))178 return false179 }180 _, expectedIsTestDeep := expected.(td.TestDeep)181 if !matchError(t, err.(*ctxerr.Error), expectedError, expectedIsTestDeep, args...) {182 return false183 }184 if td.EqDeeply(got, expected) {185 t.Errorf(`%sBoolean context failed186 got: true187 expected: false`, tdutil.BuildTestName(args...))188 return false189 }190 return true191}192func ifaceExpectedError(t *testing.T, expectedError expectedError) expectedError {193 t.Helper()194 if !strings.Contains(expectedError.Path.Exact, "DATA") {195 return expectedError196 }197 newExpectedError := expectedError198 newExpectedError.Path.Exact = strings.Replace(expectedError.Path.Exact,199 "DATA", "DATA.Iface", 1)200 if newExpectedError.Origin != nil {201 newOrigin := ifaceExpectedError(t, *newExpectedError.Origin)202 newExpectedError.Origin = &newOrigin203 }204 return newExpectedError205}206// checkError calls _checkError twice. The first time with the same207// parameters, the second time in an any context.208func checkError(t *testing.T, got, expected any,209 expectedError expectedError, args ...any,210) bool {211 t.Helper()212 if ok := _checkError(t, got, expected, expectedError, args...); !ok {213 return false214 }215 type tmpStruct struct {216 Iface any217 }218 return _checkError(t, tmpStruct{Iface: got},219 td.Struct(220 tmpStruct{},221 td.StructFields{222 "Iface": expected,223 }),224 ifaceExpectedError(t, expectedError),225 args...)226}227func checkErrorForEach(t *testing.T,228 gotList []any, expected any,229 expectedError expectedError, args ...any,230) (ret bool) {231 t.Helper()232 globalTestName := tdutil.BuildTestName(args...)233 ret = true234 for idx, got := range gotList {235 testName := fmt.Sprintf("Got #%d", idx)236 if globalTestName != "" {237 testName += ", " + globalTestName238 }239 ret = checkError(t, got, expected, expectedError, testName) && ret240 }241 return242}243// customCheckOK calls chk twice. The first time with the same244// parameters, the second time in an any context.245func customCheckOK(t *testing.T,246 chk func(t *testing.T, got, expected any, args ...any) bool,247 got, expected any,248 args ...any,249) bool {250 t.Helper()251 if ok := chk(t, got, expected, args...); !ok {252 return false253 }254 type tmpStruct struct {255 Iface any256 }257 // Dirty hack to force got be passed as an interface kind258 return chk(t, tmpStruct{Iface: got},259 td.Struct(260 tmpStruct{},261 td.StructFields{262 "Iface": expected,263 }),264 args...)265}266func _checkOK(t *testing.T, got, expected any,267 args ...any,268) bool {269 t.Helper()270 if !td.Cmp(t, got, expected, args...) {271 return false272 }273 if !td.EqDeeply(got, expected) {274 t.Errorf(`%sBoolean context failed275 got: false276 expected: true`, tdutil.BuildTestName(args...))277 return false278 }279 if err := td.EqDeeplyError(got, expected); err != nil {280 t.Errorf(`%sEqDeeplyError returned an error: %s`,281 tdutil.BuildTestName(args...), err)282 return false283 }284 return true285}286// checkOK calls _checkOK twice. The first time with the same287// parameters, the second time in an any context.288func checkOK(t *testing.T, got, expected any,289 args ...any,290) bool {291 t.Helper()292 return customCheckOK(t, _checkOK, got, expected, args...)293}294func checkOKOrPanicIfUnsafeDisabled(t *testing.T, got, expected any,295 args ...any,296) bool {297 t.Helper()298 var ret bool299 cmp := func() {300 t.Helper()301 ret = _checkOK(t, got, expected, args...)302 }303 // Should panic if unsafe package is not available304 if dark.UnsafeDisabled {305 return test.CheckPanic(t, cmp,306 "dark.GetInterface() does not handle private ")307 }308 cmp()309 return ret310}311func checkOKForEach(t *testing.T, gotList []any, expected any,312 args ...any,313) (ret bool) {314 t.Helper()315 globalTestName := tdutil.BuildTestName(args...)316 ret = true317 for idx, got := range gotList {318 testName := fmt.Sprintf("Got #%d", idx)319 if globalTestName != "" {320 testName += ", " + globalTestName321 }322 ret = checkOK(t, got, expected, testName) && ret...

Full Screen

Full Screen

types_test.go

Source:types_test.go Github

copy

Full Screen

1// Copyright (c) 2019-2021, Maxime Soulé2// All rights reserved.3//4// This source code is licensed under the BSD-style license found in the5// LICENSE file in the root directory of this source tree.6package td_test7import (8 "encoding/json"9 "strings"10 "testing"11 "github.com/maxatome/go-testdeep/helpers/tdutil"12 "github.com/maxatome/go-testdeep/internal/test"13 "github.com/maxatome/go-testdeep/td"14)15func TestSetlocation(t *testing.T) {16 //nolint: gocritic17//line types_test.go:1018 tt := &tdutil.T{}19 ok := td.Cmp(tt, 12, 13)20 if !ok {21 test.EqualStr(t, tt.LogBuf(), ` types_test.go:11: Failed test22 DATA: values differ23 got: 1224 expected: 1325`)26 } else {27 t.Error("Cmp returned true!")28 }29 //nolint: gocritic30//line types_test.go:2031 tt = &tdutil.T{}32 ok = td.Cmp(tt,33 12,34 td.Any(13, 14, 15))35 if !ok {36 test.EqualStr(t, tt.LogBuf(), ` types_test.go:21: Failed test37 DATA: comparing with Any38 got: 1239 expected: Any(13,40 14,41 15)42 [under operator Any at types_test.go:23]43`)44 } else {45 t.Error("Cmp returned true!")46 }47 //nolint: gocritic48//line types_test.go:3049 tt = &tdutil.T{}50 ok = td.CmpAny(tt,51 12,52 []any{13, 14, 15})53 if !ok {54 test.EqualStr(t, tt.LogBuf(), ` types_test.go:31: Failed test55 DATA: comparing with Any56 got: 1257 expected: Any(13,58 14,59 15)60`)61 } else {62 t.Error("CmpAny returned true!")63 }64 //nolint: gocritic65//line types_test.go:4066 tt = &tdutil.T{}67 ttt := td.NewT(tt)68 ok = ttt.Cmp(69 12,70 td.Any(13, 14, 15))71 if !ok {72 test.EqualStr(t, tt.LogBuf(), ` types_test.go:42: Failed test73 DATA: comparing with Any74 got: 1275 expected: Any(13,76 14,77 15)78 [under operator Any at types_test.go:44]79`)80 } else {81 t.Error("Cmp returned true!")82 }83 //nolint: gocritic84//line types_test.go:5085 tt = &tdutil.T{}86 ttt = td.NewT(tt)87 ok = ttt.Any(88 12,89 []any{13, 14, 15})90 if !ok {91 test.EqualStr(t, tt.LogBuf(), ` types_test.go:52: Failed test92 DATA: comparing with Any93 got: 1294 expected: Any(13,95 14,96 15)97`)98 } else {99 t.Error("Cmp returned true!")100 }101//line /a/full/path/types_test.go:50102 tt = &tdutil.T{}103 ttt = td.NewT(tt)104 ok = ttt.Any(105 12,106 []any{13, 14, 15})107 if !ok {108 test.EqualStr(t, tt.LogBuf(), ` types_test.go:52: Failed test109 DATA: comparing with Any110 got: 12111 expected: Any(13,112 14,113 15)114 This is how we got here:115 TestSetlocation() /a/full/path/types_test.go:52116`) // at least one '/' in file name → "This is how we got here"117 } else {118 t.Error("Cmp returned true!")119 }120}121func TestError(t *testing.T) {122 test.NoError(t, td.Re(`x`).Error())123 test.Error(t, td.Re(123).Error())124}125func TestMarshalJSON(t *testing.T) {126 op := td.String("foo")127 _, err := json.Marshal(op)128 if test.Error(t, err) {129 test.IsTrue(t, strings.HasSuffix(err.Error(), "String TestDeep operator cannot be json.Marshal'led"))130 }131}...

Full Screen

Full Screen

cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter two numbers")4 fmt.Scan(&a, &b)5 if tdutil.Cmp(a, b) == 0 {6 fmt.Println("Equal")7 } else if tdutil.Cmp(a, b) == 1 {8 fmt.Println("a is greater")9 } else {10 fmt.Println("b is greater")11 }12}13import (14func main() {15 fmt.Println("Enter a number")16 fmt.Scan(&a)17 if tdutil.IsPrime(a) {18 fmt.Println("Prime")19 } else {20 fmt.Println("Not Prime")21 }22}23import (24func main() {25 fmt.Println("Enter a number")26 fmt.Scan(&a)27 if tdutil.IsEven(a) {28 fmt.Println("Even")29 } else {30 fmt.Println("Odd")31 }32}33import (34func main() {35 fmt.Println("Enter a year")36 fmt.Scan(&a)37 if tdutil.IsLeap(a) {38 fmt.Println("Leap")39 } else {40 fmt.Println("Not Leap")41 }42}43import (44func main() {45 fmt.Println("Enter a number")46 fmt.Scan(&a)47 if tdutil.IsPowerOfTwo(a) {48 fmt.Println("Power of 2")49 } else {50 fmt.Println("Not Power of 2")51 }52}53import (54func main() {55 fmt.Println("Enter a number")56 fmt.Scan(&a)57 if tdutil.IsArmstrong(a) {58 fmt.Println("Arm

Full Screen

Full Screen

cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter two numbers")4 fmt.Scanln(&a, &b)5 fmt.Println(tdutil.Cmp(a, b))6}

Full Screen

Full Screen

cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter 3 numbers")4 fmt.Scanln(&a)5 fmt.Scanln(&b)6 fmt.Scanln(&c)7 fmt.Println(tdutil.Cmp(a, b, c))8}

Full Screen

Full Screen

cmp

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "tdutil"3func main() {4 a := tdutil.Tdutil{ 1 }5 b := tdutil.Tdutil{ 2 }6 fmt.Println(a.cmp(b))7}8type Tdutil struct {9}10func (t *Tdutil) cmp(t2 *Tdutil) int {11 if t.X < t2.X {12 } else if t.X == t2.X {13 } else {14 }15}

Full Screen

Full Screen

cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter three numbers:")4 fmt.Scanln(&a, &b, &c)5 fmt.Println("Max:", tdutil.Cmp(a, b, c))6}7import (8func main() {9 fmt.Println("Enter three numbers:")10 fmt.Scanln(&a, &b, &c)11 fmt.Println("Max:", tdutil.Cmp(a, b, c))12}13/usr/local/Cellar/go/1.13.5/libexec/src/github.com/tdutil (from $GOROOT)14/Users/username/go/src/github.com/tdutil (from $GOPATH)

Full Screen

Full Screen

cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("enter two numbers")4 fmt.Scan(&i, &j)5 fmt.Println(tdutil.Cmp(i, j))6}7import (8func main() {9 fmt.Println("enter two numbers")10 fmt.Scan(&i, &j)11 fmt.Println(tdutil.Cmp(i, j))12}13import (14func main() {15 fmt.Println("enter two numbers")16 fmt.Scan(&i, &j)17 fmt.Println(tdutil.Cmp(i, j))18}19import (20func main() {21 fmt.Println("enter two numbers")22 fmt.Scan(&i, &j)23 fmt.Println(tdutil.Cmp(i, j))24}25import (26func main() {27 fmt.Println("enter two numbers")28 fmt.Scan(&i, &j)29 fmt.Println(tdutil.Cmp(i, j))30}31import (32func main() {33 fmt.Println("enter two numbers")34 fmt.Scan(&i, &j)35 fmt.Println(tdutil.Cmp(i, j))36}37import (38func main() {39 fmt.Println("enter two numbers")40 fmt.Scan(&i, &j)41 fmt.Println(tdutil.Cmp(i, j))42}

Full Screen

Full Screen

cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(tdutil.Cmp(1, 2))4}5import (6func Cmp(a, b int) int {7 if a > b {8 } else if a < b {9 } else {10 }11}12import (13func main() {14 fmt.Println(mypkg.Cmp(1, 2))15}16import (17func Cmp(a, b int) int {18 if a > b {19 } else if a < b {20 } else {21 }22}23import (24func main() {25 fmt.Println(mypkg.Cmp(1, 2))26}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful