How to use Or method of tdhttp Package

Best Go-testdeep code snippet using tdhttp.Or

test_api_test.go

Source:test_api_test.go Github

copy

Full Screen

...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

request.go

Source:request.go Github

copy

Full Screen

...203// "X-Foo": "bar",204// }205// req := tdhttp.NewRequest("POST", "/pdf", body, td.Flatten(strHeaders))206//207// Or combined with forms seen above:208//209// req := tdhttp.NewRequest("POST", "/pdf", body,210// "Content-type", "application/pdf",211// http.Header{"X-Test": []string{"value1"}},212// td.Flatten(strHeaders),213// "X-Test", "value2",214// http.Cookie{Name: "cook1", Value: "val1"},215// tdhttp.BasicAuthHeader("max", "5ecr3T"),216// &http.Cookie{Name: "cook2", Value: "val2"},217// )218//219// Header keys are always canonicalized using [http.CanonicalHeaderKey].220//221// Query parameters can be added using [url.Values] or more flexible...

Full Screen

Full Screen

http.go

Source:http.go Github

copy

Full Screen

1// Copyright (c) 2019, 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 tdhttp7import (8 "encoding/json"9 "encoding/xml"10 "fmt"11 "net/http"12 "reflect"13 "testing"14 "github.com/maxatome/go-testdeep/helpers/tdutil"15 "github.com/maxatome/go-testdeep/internal/trace"16 "github.com/maxatome/go-testdeep/td"17)18func init() {19 trace.IgnorePackage()20}21// Response is used by Cmp*Response functions to make the HTTP22// response match easier. Each field, can be a [td.TestDeep] operator23// as well as the exact expected value.24type Response struct {25 Status any // is the expected status (ignored if nil)26 Header any // is the expected header (ignored if nil)27 Cookies any // is the expected cookies (ignored if nil)28 Body any // is the expected body (expected to be empty if nil)29}30func cmpMarshaledResponse(tb testing.TB,31 req *http.Request,32 handler func(w http.ResponseWriter, r *http.Request),33 acceptEmptyBody bool,34 unmarshal func([]byte, any) error,35 expectedResp Response,36 args ...any,37) bool {38 tb.Helper()39 if testName := tdutil.BuildTestName(args...); testName != "" {40 tb.Log(testName)41 }42 t := td.NewT(tb)43 defer t.AnchorsPersistTemporarily()()44 ta := NewTestAPI(t, http.HandlerFunc(handler)).Request(req)45 // Check status, nil = ignore46 if expectedResp.Status != nil {47 ta.CmpStatus(expectedResp.Status)48 }49 // Check header, nil = ignore50 if expectedResp.Header != nil {51 ta.CmpHeader(expectedResp.Header)52 }53 // Check cookie, nil = ignore54 if expectedResp.Cookies != nil {55 ta.CmpCookies(expectedResp.Cookies)56 }57 if expectedResp.Body == nil {58 ta.NoBody()59 } else {60 ta.cmpMarshaledBody(acceptEmptyBody, unmarshal, expectedResp.Body)61 }62 return !ta.Failed()63}64// CmpMarshaledResponse is the base function used by some others in65// tdhttp package. req is launched against handler. The response body66// is unmarshaled using unmarshal. The response is then tested against67// expectedResp.68//69// args... are optional and allow to name the test, a t.Log() done70// before starting any test. If len(args) > 1 and the first item of71// args is a string and contains a '%' rune then [fmt.Fprintf] is used72// to compose the name, else args are passed to [fmt.Fprint].73//74// It returns true if the tests succeed, false otherwise.75//76// See [TestAPI] type and its methods for more flexible tests.77func CmpMarshaledResponse(t testing.TB,78 req *http.Request,79 handler func(w http.ResponseWriter, r *http.Request),80 unmarshal func([]byte, any) error,81 expectedResp Response,82 args ...any,83) bool {84 t.Helper()85 return cmpMarshaledResponse(t, req, handler, false, unmarshal, expectedResp, args...)86}87// CmpResponse is used to match a []byte or string response body. req88// is launched against handler. If expectedResp.Body is non-nil, the89// response body is converted to []byte or string, depending on the90// expectedResp.Body type. The response is then tested against91// expectedResp.92//93// args... are optional and allow to name the test, a t.Log() done94// before starting any test. If len(args) > 1 and the first item of95// args is a string and contains a '%' rune then [fmt.Fprintf] is used96// to compose the name, else args are passed to [fmt.Fprint].97//98// It returns true if the tests succeed, false otherwise.99//100// ok := tdhttp.CmpResponse(t,101// tdhttp.Get("/test"),102// myAPI.ServeHTTP,103// Response{104// Status: http.StatusOK,105// Header: td.ContainsKey("X-Custom-Header"),106// Body: "OK!\n",107// },108// "/test route")109//110// Response.Status, Response.Header and Response.Body fields can all111// be [td.TestDeep] operators as it is for Response.Header field112// here. Otherwise, Response.Status should be an int, Response.Header113// a [http.Header] and Response.Body a []byte or a string.114//115// See [TestAPI] type and its methods for more flexible tests.116func CmpResponse(t testing.TB,117 req *http.Request,118 handler func(w http.ResponseWriter, r *http.Request),119 expectedResp Response,120 args ...any) bool {121 t.Helper()122 return cmpMarshaledResponse(t,123 req,124 handler,125 true,126 func(body []byte, target any) error {127 switch t := target.(type) {128 case *string:129 *t = string(body)130 case *[]byte:131 *t = body132 case *any:133 *t = body134 default:135 // cmpMarshaledBody (behind cmpMarshaledResponse) always calls136 // us with target as a pointer137 return fmt.Errorf(138 "CmpResponse only accepts expectedResp.Body be a []byte, a string or a TestDeep operator allowing to match these types, but not type %s",139 reflect.TypeOf(target).Elem())140 }141 return nil142 },143 expectedResp,144 args...)145}146// CmpJSONResponse is used to match a JSON response body. req is147// launched against handler. If expectedResp.Body is non-nil, the148// response body is [json.Unmarshal]'ed. The response is then tested149// against expectedResp.150//151// args... are optional and allow to name the test, a t.Log() done152// before starting any test. If len(args) > 1 and the first item of153// args is a string and contains a '%' rune then [fmt.Fprintf] is used154// to compose the name, else args are passed to [fmt.Fprint].155//156// It returns true if the tests succeed, false otherwise.157//158// ok := tdhttp.CmpJSONResponse(t,159// tdhttp.Get("/person/42"),160// myAPI.ServeHTTP,161// Response{162// Status: http.StatusOK,163// Header: td.ContainsKey("X-Custom-Header"),164// Body: Person{165// ID: 42,166// Name: "Bob",167// Age: 26,168// },169// },170// "/person/{id} route")171//172// Response.Status, Response.Header and Response.Body fields can all173// be [td.TestDeep] operators as it is for Response.Header field174// here. Otherwise, Response.Status should be an int, Response.Header175// a [http.Header] and Response.Body any type one can176// [json.Unmarshal] into.177//178// If Response.Status and Response.Header are omitted (or nil), they179// are not tested.180//181// If Response.Body is omitted (or nil), it means the body response has to be182// empty. If you want to ignore the body response, use [td.Ignore]183// explicitly.184//185// See [TestAPI] type and its methods for more flexible tests.186func CmpJSONResponse(t testing.TB,187 req *http.Request,188 handler func(w http.ResponseWriter, r *http.Request),189 expectedResp Response,190 args ...any,191) bool {192 t.Helper()193 return CmpMarshaledResponse(t,194 req,195 handler,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}...

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) > 1 {4 }5 if len(os.Args) > 2 {6 }7 if resp, err = tdhttp.New(urlStr).Or(method).Send(); err == nil {8 if respBody, err = ioutil.ReadAll(resp.Body); err == nil {9 fmt.Println(string(respBody))10 }11 }12}13import (14func main() {15 if len(os.Args) > 1 {16 }17 if len(os.Args) > 2 {18 }

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 b := buffer.New([]byte(`a b c`))4 l := lex.NewLexer(b)5 p := html.NewParser(l)6 _, err := p.Parse()7 if err != nil {8 fmt.Println(err)9 }10}

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := minify.New()4 m.AddFunc("text/css", css.Minify)5 m.AddFunc("text/html", html.Minify)6 m.AddFunc("text/javascript", js.Minify)7 m.AddFunc("image/svg+xml", svg.Minify)8 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)9 m.Add("text/html", &html.Minifier{10 })11 m.Add("text/css", &css.Minifier{12 })13 m.Add("text/javascript", &js.Minifier{14 })15 m.Add("image/svg

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import "github.com/tdewolff/minify"2import "github.com/tdewolff/minify/js"3import "github.com/tdewolff/minify/css"4import "github.com/tdewolff/minify/html"5import "github.com/tdewolff/minify/svg"6import "github.com/tdewolff/minify/json"7import "github.com/tdewolff/minify/xml"8func main() {9m := minify.New()10m.AddFunc("text/javascript", js.Minify)11m.AddFunc("text/css", css.Minify)12m.AddFunc("text/html", html.Minify)13m.AddFunc("image/svg+xml", svg.Minify)14m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)15m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)16m.Add("text/html", &html.Minifier{17})18m.Add("text/html", &html.Minifier{19})20m.Add("text/html", &html.Minifier{21})22m.Add("text/html", &html.Minifier{23})24m.Add("text/html", &html.Minifier{25})26m.Add("text/html", &html.Minifier{27})28m.Add("text/html", &html.Minifier{29})30m.Add("text/html", &html.Minifier{31})32m.Add("text/html", &html.Minifier{33})34m.Add("text/html", &html.Minifier{35})36m.Add("text/html", &html.Minifier{37})38m.Add("text/html", &html.Minifier{39})40m.Add("text/html", &html.Minifier{41})42m.Add("text/html", &html.Minifier{43})44m.Add("text/html", &html.Minifier{45})46m.Add("text/html", &html.Minifier{47})48m.Add("text/html", &html.Minifier{49})

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 m = minify.New()5 m.AddFunc("image/svg+xml", svg.Minify)6 m.AddFunc("text/xml", xml.Minify)7 m.AddFunc("text/css", css.Minify)8 m.AddFunc("application/json", js.Minify)9 m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), js.Minify)10 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)11 m.Add("text/html", &html.Minifier{12 })13 cookie := &http.Cookie{14 }15 req.AddCookie(cookie)16 req.Header.Add("User-Agent", "my-user-agent")17 client := &http.Client{}18 resp, err := client.Do(req)19 body, err := ioutil.ReadAll(resp.Body)20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(string(body))24 resp.Body.Close()25 f, err := os.Create("response.html")26 if err != nil {27 log.Fatal(err)28 }29 _, err = f.Write(body)30 if err != nil {31 log.Fatal(err)32 }33 err = f.Close()34 if err != nil {35 log.Fatal(err)36 }37}

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http := tdhttp.New(tdhttp.DefaultOptions)4 fmt.Println("url:", url)5 fmt.Println("url path:", url.Path)6 fmt.Println("url query:", url.Query)7 fmt.Println("url fragment:", url.Fragment)8 fmt.Println("url scheme:", url.Scheme)9 fmt.Println("url host:", url.Host)10 fmt.Println("url port:", url.Port)11}

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 req.SetTimeout(10)5 resp := req.Do()6 fmt.Println(resp.Body)7 fmt.Println(resp.StatusCode)8}9import (10func main() {11 fmt.Println("Hello, playground")12 req.SetTimeout(10)13 resp := req.Do()14 fmt.Println(resp.Body)15 fmt.Println(resp.StatusCode)16}17import (18func main() {19 fmt.Println("Hello, playground")20 req.SetTimeout(10)21 resp := req.Do()22 fmt.Println(resp.Body)23 fmt.Println(resp.StatusCode)24}25import (26func main() {27 fmt.Println("Hello, playground")28 req.SetTimeout(10)29 resp := req.Do()30 fmt.Println(resp.Body)31 fmt.Println(resp.StatusCode)32}33import (34func main() {35 fmt.Println("Hello, playground")36 req.SetTimeout(10)37 resp := req.Do()38 fmt.Println(resp.Body)39 fmt.Println(resp.StatusCode)40}41import (42func main() {43 fmt.Println("Hello, playground")44 req.SetTimeout(10)45 resp := req.Do()46 fmt.Println(resp.Body)47 fmt.Println(resp.StatusCode)48}

Full Screen

Full Screen

Or

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var tdhttp = tdhttp.New()4 var headers = map[string]string{5 }6 var params = map[string]string{7 }8 var response = tdhttp.Or(url, headers, params)9 fmt.Println(response)10}11import (12func main() {13 var tdhttp = tdhttp.New()14 var headers = map[string]string{15 }16 var params = map[string]string{17 }18 var response = tdhttp.Post(url, headers, params)19 fmt.Println(response)20}21import (22func main() {23 var tdhttp = tdhttp.New()24 var headers = map[string]string{25 }26 var params = map[string]string{27 }28 var response = tdhttp.Patch(url, headers, params)29 fmt.Println(response)30}31import (32func main() {33 var tdhttp = tdhttp.New()34 var headers = map[string]string{35 }36 var params = map[string]string{37 }38 var response = tdhttp.Put(url, headers, params)39 fmt.Println(response)40}41import (

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