How to use NewRequest method of tdhttp Package

Best Go-testdeep code snippet using tdhttp.NewRequest

request.go

Source:request.go Github

copy

Full Screen

...76 }77 u.RawQuery += qp.Encode()78 target = u.String()79 }80 req := httptest.NewRequest(method, target, body)81 for k, v := range header {82 req.Header[k] = append(req.Header[k], v...)83 }84 for _, c := range cookies {85 req.AddCookie(c)86 }87 return req, nil88}89// BasicAuthHeader returns a new [http.Header] with only Authorization90// key set, compliant with HTTP Basic Authentication using user and91// password. It is provided as a facility to build request in one92// line:93//94// ta.Get("/path", tdhttp.BasicAuthHeader("max", "5ecr3T"))95//96// instead of:97//98// req := tdhttp.Get("/path")99// req.SetBasicAuth("max", "5ecr3T")100// ta.Request(req)101//102// See [http.Request.SetBasicAuth] for details.103func BasicAuthHeader(user, password string) http.Header {104 return http.Header{105 "Authorization": []string{106 "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+password)),107 },108 }109}110func get(target string, headersQueryParams ...any) (*http.Request, error) {111 return newRequest(http.MethodGet, target, nil, headersQueryParams)112}113func head(target string, headersQueryParams ...any) (*http.Request, error) {114 return newRequest(http.MethodHead, target, nil, headersQueryParams)115}116func options(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {117 return newRequest(http.MethodOptions, target, body, headersQueryParams)118}119func post(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {120 return newRequest(http.MethodPost, target, body, headersQueryParams)121}122func postForm(target string, data URLValuesEncoder, headersQueryParams ...any) (*http.Request, error) {123 var body string124 if data != nil {125 body = data.Encode()126 }127 return newRequest(128 http.MethodPost, target, strings.NewReader(body),129 append(headersQueryParams, "Content-Type", "application/x-www-form-urlencoded"),130 )131}132func postMultipartFormData(target string, data *MultipartBody, headersQueryParams ...any) (*http.Request, error) {133 return newRequest(134 http.MethodPost, target, data,135 append(headersQueryParams, "Content-Type", data.ContentType()),136 )137}138func put(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {139 return newRequest(http.MethodPut, target, body, headersQueryParams)140}141func patch(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {142 return newRequest(http.MethodPatch, target, body, headersQueryParams)143}144func del(target string, body io.Reader, headersQueryParams ...any) (*http.Request, error) {145 return newRequest(http.MethodDelete, target, body, headersQueryParams)146}147// NewRequest creates a new HTTP request as [httptest.NewRequest]148// does, with the ability to immediately add some headers and/or some149// query parameters.150//151// Headers can be added using string pairs as in:152//153// req := tdhttp.NewRequest("POST", "/pdf", body,154// "Content-type", "application/pdf",155// "X-Test", "value",156// )157//158// or using [http.Header] as in:159//160// req := tdhttp.NewRequest("POST", "/pdf", body,161// http.Header{"Content-type": []string{"application/pdf"}},162// )163//164// or using [BasicAuthHeader] as in:165//166// req := tdhttp.NewRequest("POST", "/pdf", body,167// tdhttp.BasicAuthHeader("max", "5ecr3T"),168// )169//170// or using [http.Cookie] (pointer or not, behind the scene,171// [http.Request.AddCookie] is used) as in:172//173// req := tdhttp.NewRequest("POST", "/pdf", body,174// http.Cookie{Name: "cook1", Value: "val1"},175// &http.Cookie{Name: "cook2", Value: "val2"},176// )177//178// Several header sources are combined:179//180// req := tdhttp.NewRequest("POST", "/pdf", body,181// "Content-type", "application/pdf",182// http.Header{"X-Test": []string{"value1"}},183// "X-Test", "value2",184// http.Cookie{Name: "cook1", Value: "val1"},185// tdhttp.BasicAuthHeader("max", "5ecr3T"),186// &http.Cookie{Name: "cook2", Value: "val2"},187// )188//189// Produces the following [http.Header]:190//191// http.Header{192// "Authorization": []string{"Basic bWF4OjVlY3IzVA=="},193// "Content-type": []string{"application/pdf"},194// "Cookie": []string{"cook1=val1; cook2=val2"},195// "X-Test": []string{"value1", "value2"},196// }197//198// A string slice or a map can be flatened as well. As [NewRequest] expects199// ...any, [td.Flatten] can help here too:200//201// strHeaders := map[string]string{202// "X-Length": "666",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 flexible222// [Q], as in:223//224// req := tdhttp.NewRequest("GET", "/pdf",225// url.Values{226// "param": {"val"},227// "names": {"bob", "alice"},228// },229// "X-Test": "a header in the middle",230// tdhttp.Q{231// "limit": 20,232// "ids": []int64{456, 789},233// "details": true,234// },235// )236//237// All [url.Values] and [Q] instances are combined to produce the238// final query string to use. The previous example produces the239// following target:240//241// /pdf?details=true&ids=456&ids=789&limit=20&names=bob&names=alice&param=val242//243// If target already contains a query string, it is reused:244//245// req := tdhttp.NewRequest("GET", "/pdf?limit=10", tdhttp.Q{"details": true})246//247// produces the following target:248//249// /path?details=true&limit=10250//251// Behind the scene, [url.Values.Encode] is used, so the parameters252// are always sorted by key. If you want a specific order, then do not253// use [url.Values] nor [Q] instances, but compose target by yourself.254//255// See [Q] documentation to learn how values are stringified.256func NewRequest(method, target string, body io.Reader, headersQueryParams ...any) *http.Request {257 req, err := newRequest(method, target, body, headersQueryParams)258 if err != nil {259 panic(err)260 }261 return req262}263// Get creates a new HTTP GET. It is a shortcut for:264//265// tdhttp.NewRequest(http.MethodGet, target, nil, headersQueryParams...)266//267// See [NewRequest] for all possible formats accepted in headersQueryParams.268func Get(target string, headersQueryParams ...any) *http.Request {269 req, err := get(target, headersQueryParams...)270 if err != nil {271 panic(err)272 }273 return req274}275// Head creates a new HTTP HEAD. It is a shortcut for:276//277// tdhttp.NewRequest(http.MethodHead, target, nil, headersQueryParams...)278//279// See [NewRequest] for all possible formats accepted in headersQueryParams.280func Head(target string, headersQueryParams ...any) *http.Request {281 req, err := head(target, headersQueryParams...)282 if err != nil {283 panic(err)284 }285 return req286}287// Options creates a HTTP OPTIONS. It is a shortcut for:288//289// tdhttp.NewRequest(http.MethodOptions, target, body, headersQueryParams...)290//291// See [NewRequest] for all possible formats accepted in headersQueryParams.292func Options(target string, body io.Reader, headersQueryParams ...any) *http.Request {293 req, err := options(target, body, headersQueryParams...)294 if err != nil {295 panic(err)296 }297 return req298}299// Post creates a HTTP POST. It is a shortcut for:300//301// tdhttp.NewRequest(http.MethodPost, target, body, headersQueryParams...)302//303// See [NewRequest] for all possible formats accepted in headersQueryParams.304func Post(target string, body io.Reader, headersQueryParams ...any) *http.Request {305 req, err := post(target, body, headersQueryParams...)306 if err != nil {307 panic(err)308 }309 return req310}311// URLValuesEncoder is an interface [PostForm] and [TestAPI.PostForm] data312// must implement.313// Encode can be called to generate a "URL encoded" form such as314// ("bar=baz&foo=quux") sorted by key.315//316// [url.Values] and [Q] implement this interface.317type URLValuesEncoder interface {318 Encode() string319}320// PostForm creates a HTTP POST with data's keys and values321// URL-encoded as the request body. "Content-Type" header is322// automatically set to "application/x-www-form-urlencoded". Other323// headers can be added via headersQueryParams, as in:324//325// req := tdhttp.PostForm("/data",326// url.Values{327// "param1": []string{"val1", "val2"},328// "param2": []string{"zip"},329// },330// "X-Foo", "Foo-value",331// "X-Zip", "Zip-value",332// )333//334// See [NewRequest] for all possible formats accepted in headersQueryParams.335func PostForm(target string, data URLValuesEncoder, headersQueryParams ...any) *http.Request {336 req, err := postForm(target, data, headersQueryParams...)337 if err != nil {338 panic(err)339 }340 return req341}342// PostMultipartFormData creates a HTTP POST multipart request, like343// multipart/form-data one for example. See [MultipartBody] type for344// details. "Content-Type" header is automatically set depending on345// data.MediaType (defaults to "multipart/form-data") and data.Boundary346// (defaults to "go-testdeep-42"). Other headers can be added via347// headersQueryParams, as in:348//349// req := tdhttp.PostMultipartFormData("/data",350// &tdhttp.MultipartBody{351// // "multipart/form-data" by default352// Parts: []*tdhttp.MultipartPart{353// tdhttp.NewMultipartPartString("type", "Sales"),354// tdhttp.NewMultipartPartFile("report", "report.json", "application/json"),355// },356// },357// "X-Foo", "Foo-value",358// "X-Zip", "Zip-value",359// )360//361// and with a different media type:362//363// req := tdhttp.PostMultipartFormData("/data",364// &tdhttp.MultipartBody{365// MediaType: "multipart/mixed",366// Parts: []*tdhttp.MultipartPart{367// tdhttp.NewMultipartPartString("type", "Sales"),368// tdhttp.NewMultipartPartFile("report", "report.json", "application/json"),369// },370// },371// "X-Foo", "Foo-value",372// "X-Zip", "Zip-value",373// )374//375// See [NewRequest] for all possible formats accepted in headersQueryParams.376func PostMultipartFormData(target string, data *MultipartBody, headersQueryParams ...any) *http.Request {377 req, err := postMultipartFormData(target, data, headersQueryParams...)378 if err != nil {379 panic(err)380 }381 return req382}383// Put creates a HTTP PUT. It is a shortcut for:384//385// tdhttp.NewRequest(http.MethodPut, target, body, headersQueryParams...)386//387// See [NewRequest] for all possible formats accepted in headersQueryParams.388func Put(target string, body io.Reader, headersQueryParams ...any) *http.Request {389 req, err := put(target, body, headersQueryParams...)390 if err != nil {391 panic(err)392 }393 return req394}395// Patch creates a HTTP PATCH. It is a shortcut for:396//397// tdhttp.NewRequest(http.MethodPatch, target, body, headersQueryParams...)398//399// See [NewRequest] for all possible formats accepted in headersQueryParams.400func Patch(target string, body io.Reader, headersQueryParams ...any) *http.Request {401 req, err := patch(target, body, headersQueryParams...)402 if err != nil {403 panic(err)404 }405 return req406}407// Delete creates a HTTP DELETE. It is a shortcut for:408//409// tdhttp.NewRequest(http.MethodDelete, target, body, headersQueryParams...)410//411// See [NewRequest] for all possible formats accepted in headersQueryParams.412func Delete(target string, body io.Reader, headersQueryParams ...any) *http.Request {413 req, err := del(target, body, headersQueryParams...)414 if err != nil {415 panic(err)416 }417 return req418}419func newJSONRequest(method, target string, body any, headersQueryParams ...any) (*http.Request, error) {420 b, err := json.Marshal(body)421 if err != nil {422 if opErr, ok := types.AsOperatorNotJSONMarshallableError(err); ok {423 var plus string424 switch op := opErr.Operator(); op {425 case "JSON", "SubJSONOf", "SuperJSONOf":426 plus = ", use json.RawMessage() instead"427 }428 return nil, errors.New(color.Bad("JSON encoding failed: %s%s", err, plus))429 }430 return nil, errors.New(color.Bad("%s", err))431 }432 return newRequest(433 method, target, bytes.NewReader(b),434 append(headersQueryParams, "Content-Type", "application/json"),435 )436}437// NewJSONRequest creates a new HTTP request with body marshaled to438// JSON. "Content-Type" header is automatically set to439// "application/json". Other headers can be added via headersQueryParams, as in:440//441// req := tdhttp.NewJSONRequest("POST", "/data", body,442// "X-Foo", "Foo-value",443// "X-Zip", "Zip-value",444// )445//446// See [NewRequest] for all possible formats accepted in headersQueryParams.447func NewJSONRequest(method, target string, body any, headersQueryParams ...any) *http.Request {448 req, err := newJSONRequest(method, target, body, headersQueryParams...)449 if err != nil {450 panic(err)451 }452 return req453}454// PostJSON creates a HTTP POST with body marshaled to455// JSON. "Content-Type" header is automatically set to456// "application/json". It is a shortcut for:457//458// tdhttp.NewJSONRequest(http.MethodPost, target, body, headersQueryParams...)459//460// See [NewRequest] for all possible formats accepted in headersQueryParams.461func PostJSON(target string, body any, headersQueryParams ...any) *http.Request {462 req, err := newJSONRequest(http.MethodPost, target, body, headersQueryParams...)463 if err != nil {464 panic(err)465 }466 return req467}468// PutJSON creates a HTTP PUT with body marshaled to469// JSON. "Content-Type" header is automatically set to470// "application/json". It is a shortcut for:471//472// tdhttp.NewJSONRequest(http.MethodPut, target, body, headersQueryParams...)473//474// See [NewRequest] for all possible formats accepted in headersQueryParams.475func PutJSON(target string, body any, headersQueryParams ...any) *http.Request {476 req, err := newJSONRequest(http.MethodPut, target, body, headersQueryParams...)477 if err != nil {478 panic(err)479 }480 return req481}482// PatchJSON creates a HTTP PATCH with body marshaled to483// JSON. "Content-Type" header is automatically set to484// "application/json". It is a shortcut for:485//486// tdhttp.NewJSONRequest(http.MethodPatch, target, body, headersQueryParams...)487//488// See [NewRequest] for all possible formats accepted in headersQueryParams.489func PatchJSON(target string, body any, headersQueryParams ...any) *http.Request {490 req, err := newJSONRequest(http.MethodPatch, target, body, headersQueryParams...)491 if err != nil {492 panic(err)493 }494 return req495}496// DeleteJSON creates a HTTP DELETE with body marshaled to497// JSON. "Content-Type" header is automatically set to498// "application/json". It is a shortcut for:499//500// tdhttp.NewJSONRequest(http.MethodDelete, target, body, headersQueryParams...)501//502// See [NewRequest] for all possible formats accepted in headersQueryParams.503func DeleteJSON(target string, body any, headersQueryParams ...any) *http.Request {504 req, err := newJSONRequest(http.MethodDelete, target, body, headersQueryParams...)505 if err != nil {506 panic(err)507 }508 return req509}510func newXMLRequest(method, target string, body any, headersQueryParams ...any) (*http.Request, error) {511 b, err := xml.Marshal(body)512 if err != nil {513 return nil, errors.New(color.Bad("XML encoding failed: %s", err))514 }515 return newRequest(516 method, target, bytes.NewReader(b),517 append(headersQueryParams, "Content-Type", "application/xml"),518 )519}520// NewXMLRequest creates a new HTTP request with body marshaled to521// XML. "Content-Type" header is automatically set to522// "application/xml". Other headers can be added via headersQueryParams, as in:523//524// req := tdhttp.NewXMLRequest("POST", "/data", body,525// "X-Foo", "Foo-value",526// "X-Zip", "Zip-value",527// )528//529// See [NewRequest] for all possible formats accepted in headersQueryParams.530func NewXMLRequest(method, target string, body any, headersQueryParams ...any) *http.Request {531 req, err := newXMLRequest(method, target, body, headersQueryParams...)532 if err != nil {533 panic(err)534 }535 return req536}537// PostXML creates a HTTP POST with body marshaled to538// XML. "Content-Type" header is automatically set to539// "application/xml". It is a shortcut for:540//541// tdhttp.NewXMLRequest(http.MethodPost, target, body, headersQueryParams...)542//543// See [NewRequest] for all possible formats accepted in headersQueryParams.544func PostXML(target string, body any, headersQueryParams ...any) *http.Request {545 req, err := newXMLRequest(http.MethodPost, target, body, headersQueryParams...)546 if err != nil {547 panic(err)548 }549 return req550}551// PutXML creates a HTTP PUT with body marshaled to552// XML. "Content-Type" header is automatically set to553// "application/xml". It is a shortcut for:554//555// tdhttp.NewXMLRequest(http.MethodPut, target, body, headersQueryParams...)556//557// See [NewRequest] for all possible formats accepted in headersQueryParams.558func PutXML(target string, body any, headersQueryParams ...any) *http.Request {559 req, err := newXMLRequest(http.MethodPut, target, body, headersQueryParams...)560 if err != nil {561 panic(err)562 }563 return req564}565// PatchXML creates a HTTP PATCH with body marshaled to566// XML. "Content-Type" header is automatically set to567// "application/xml". It is a shortcut for:568//569// tdhttp.NewXMLRequest(http.MethodPatch, target, body, headersQueryParams...)570//571// See [NewRequest] for all possible formats accepted in headersQueryParams.572func PatchXML(target string, body any, headersQueryParams ...any) *http.Request {573 req, err := newXMLRequest(http.MethodPatch, target, body, headersQueryParams...)574 if err != nil {575 panic(err)576 }577 return req578}579// DeleteXML creates a HTTP DELETE with body marshaled to580// XML. "Content-Type" header is automatically set to581// "application/xml". It is a shortcut for:582//583// tdhttp.NewXMLRequest(http.MethodDelete, target, body, headersQueryParams...)584//585// See [NewRequest] for all possible formats accepted in headersQueryParams.586func DeleteXML(target string, body any, headersQueryParams ...any) *http.Request {587 req, err := newXMLRequest(http.MethodDelete, target, body, headersQueryParams...)588 if err != nil {589 panic(err)590 }591 return req592}...

Full Screen

Full Screen

request_test.go

Source:request_test.go Github

copy

Full Screen

...16 td.Cmp(t,17 tdhttp.BasicAuthHeader("max", "5ecr3T"),18 http.Header{"Authorization": []string{"Basic bWF4OjVlY3IzVA=="}})19}20func TestNewRequest(tt *testing.T) {21 t := td.NewT(tt)22 t.Run("NewRequest", func(t *td.T) {23 req := tdhttp.NewRequest("GET", "/path", nil,24 "Foo", "Bar",25 "Zip", "Test")26 t.Cmp(req.Header, http.Header{27 "Foo": []string{"Bar"},28 "Zip": []string{"Test"},29 })30 })31 t.Run("NewRequest last header value less", func(t *td.T) {32 req := tdhttp.NewRequest("GET", "/path", nil,33 "Foo", "Bar",34 "Zip")35 t.Cmp(req.Header, http.Header{36 "Foo": []string{"Bar"},37 "Zip": []string{""},38 })39 })40 t.Run("NewRequest header http.Header", func(t *td.T) {41 req := tdhttp.NewRequest("GET", "/path", nil,42 http.Header{43 "Foo": []string{"Bar"},44 "Zip": []string{"Test"},45 })46 t.Cmp(req.Header, http.Header{47 "Foo": []string{"Bar"},48 "Zip": []string{"Test"},49 })50 })51 t.Run("NewRequest header http.Cookie", func(t *td.T) {52 req := tdhttp.NewRequest("GET", "/path", nil,53 &http.Cookie{Name: "cook1", Value: "val1"},54 http.Cookie{Name: "cook2", Value: "val2"},55 )56 t.Cmp(req.Header, http.Header{"Cookie": []string{"cook1=val1; cook2=val2"}})57 })58 t.Run("NewRequest header flattened", func(t *td.T) {59 req := tdhttp.NewRequest("GET", "/path", nil,60 td.Flatten([]string{61 "Foo", "Bar",62 "Zip", "Test",63 }),64 td.Flatten(map[string]string{65 "Pipo": "Bingo",66 "Hey": "Yo",67 }),68 )69 t.Cmp(req.Header, http.Header{70 "Foo": []string{"Bar"},71 "Zip": []string{"Test"},72 "Pipo": []string{"Bingo"},73 "Hey": []string{"Yo"},74 })75 })76 t.Run("NewRequest header combined", func(t *td.T) {77 req := tdhttp.NewRequest("GET", "/path", nil,78 "H1", "V1",79 http.Header{80 "H1": []string{"V2"},81 "H2": []string{"V1", "V2"},82 },83 "H2", "V3",84 td.Flatten([]string{85 "H2", "V4",86 "H3", "V1",87 "H3", "V2",88 }),89 td.Flatten(map[string]string{90 "H2": "V5",91 "H3": "V3",92 }),93 )94 t.Cmp(req.Header, http.Header{95 "H1": []string{"V1", "V2"},96 "H2": []string{"V1", "V2", "V3", "V4", "V5"},97 "H3": []string{"V1", "V2", "V3"},98 })99 })100 t.Run("NewRequest and query params", func(t *td.T) {101 req := tdhttp.NewRequest("GET", "/path", nil,102 url.Values{"p1": []string{"a", "b"}},103 url.Values{"p2": []string{"a", "b"}},104 tdhttp.Q{"p1": "c", "p2": []string{"c", "d"}},105 tdhttp.Q{"p1": 123, "p3": true},106 )107 t.Cmp(req.URL.String(), "/path?p1=a&p1=b&p1=c&p1=123&p2=a&p2=b&p2=c&p2=d&p3=true")108 // Query param already set in path109 req = tdhttp.NewRequest("GET", "/path?already=true", nil,110 tdhttp.Q{"p1": 123, "p3": true},111 )112 t.Cmp(req.URL.String(), "/path?already=true&p1=123&p3=true")113 })114 t.Run("NewRequest panics", func(t *td.T) {115 t.CmpPanic(116 func() { tdhttp.NewRequest("GET", "/path", nil, "H", "V", true) },117 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[2])"))118 t.CmpPanic(119 func() { tdhttp.NewRequest("GET", "/path", nil, "H1", true) },120 td.HasPrefix(`header "H1" should have a string value, not a bool (@ headersQueryParams[1])`))121 t.CmpPanic(122 func() { tdhttp.Get("/path", true) },123 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))124 t.CmpPanic(125 func() { tdhttp.Head("/path", true) },126 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))127 t.CmpPanic(128 func() { tdhttp.Options("/path", nil, true) },129 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))130 t.CmpPanic(131 func() { tdhttp.Post("/path", nil, true) },132 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))133 t.CmpPanic(134 func() { tdhttp.PostForm("/path", nil, true) },135 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))136 t.CmpPanic(137 func() { tdhttp.PostMultipartFormData("/path", &tdhttp.MultipartBody{}, true) },138 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))139 t.CmpPanic(140 func() { tdhttp.Patch("/path", nil, true) },141 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))142 t.CmpPanic(143 func() { tdhttp.Put("/path", nil, true) },144 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))145 t.CmpPanic(146 func() { tdhttp.Delete("/path", nil, true) },147 td.HasPrefix("headersQueryParams... can only contains string, http.Header, http.Cookie, url.Values and tdhttp.Q, not bool (@ headersQueryParams[0])"))148 // Bad target149 t.CmpPanic(150 func() { tdhttp.NewRequest("GET", ":/badpath", nil) },151 td.HasPrefix(`target is not a valid path: `))152 // Q error153 t.CmpPanic(154 func() { tdhttp.Get("/", tdhttp.Q{"bad": map[string]bool{}}) },155 td.HasPrefix(`headersQueryParams... tdhttp.Q bad parameter: don't know how to add type map[string]bool (map) to param "bad" (@ headersQueryParams[0])`))156 })157 // Get158 t.Cmp(tdhttp.Get("/path", "Foo", "Bar"),159 td.Struct(160 &http.Request{161 Method: "GET",162 Header: http.Header{"Foo": []string{"Bar"}},163 },164 td.StructFields{...

Full Screen

Full Screen

router_test.go

Source:router_test.go Github

copy

Full Screen

...33 },34 fakeFileFS: defaultFakeFileFS,35 },36 args: args{37 req: tdhttp.NewRequest(http.MethodGet, "https://google.com/index.html", nil),38 },39 want: defaultHTMLContent,40 wantStatus: td.Between(200, 299),41 },42 {43 name: "GET /profile.htm",44 fields: fields{45 rules: []string{46 `PathPattern("\\.(?i)(htm|html)$") => File("default.html")`,47 },48 fakeFileFS: defaultFakeFileFS,49 },50 args: args{51 req: tdhttp.NewRequest(http.MethodGet, "https://gitlab.com/profile.htm", nil),52 },53 want: defaultHTMLContent,54 wantStatus: td.Between(200, 299),55 },56 {57 name: "GET with Accept: text/html",58 fields: fields{59 rules: []string{60 `PathPattern("\\.(?i)(htm|html)$") => File("default.html")`,61 `Header("Accept", "text/html") => File("default.html")`,62 },63 fakeFileFS: defaultFakeFileFS,64 },65 args: args{66 req: tdhttp.NewRequest(67 http.MethodGet,68 "https://gitlab.com/profile",69 nil,70 http.Header{71 "Accept": []string{"text/html"},72 },73 ),74 },75 want: defaultHTMLContent,76 wantStatus: td.Between(200, 299),77 },78 {79 name: "POST",80 fields: fields{81 rules: []string{82 `METHOD("POST") => Status(204)`,83 },84 },85 args: args{86 req: tdhttp.NewRequest(87 http.MethodPost,88 "https://gitlab.com/profile",89 nil,90 http.Header{91 "Accept": []string{"text/html"},92 },93 ),94 },95 want: "",96 wantStatus: 204,97 },98 }99 for _, tc := range tests {100 tt := tc...

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error:", err)5 }6 fmt.Println("Request:", req)7}8import (9func main() {10 if err != nil {11 fmt.Println("Error:", err)12 }13 client := &http.Client{}14 resp, err := client.Do(req)15 if err != nil {16 fmt.Println("Error:", err)17 }18 defer resp.Body.Close()19 fmt.Println("Status:", resp.Status)20}21import (22func main() {23 if err != nil {24 fmt.Println("Error:", err)25 }26 defer resp.Body.Close()27 fmt.Println("Status:", resp.Status)28}29import (30func main() {31 if err != nil {32 fmt.Println("

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := tdhttp.NewClient()4 if err != nil {5 panic(err)6 }7 req.Header.Add("Accept", "application/json")8 req.Header.Add("Accept", "application/xml")9 req.Header.Add("Accept", "text/html")10 req.Header.Add("Accept", "text/plain")11 resp, err := client.Do(req)12 if err != nil {13 panic(err)14 }15 fmt.Println(resp.Status)16}17import (18func main() {19 client := tdhttp.NewClient()20 if err != nil {21 panic(err)22 }23 req.Header.Add("Accept", "application/json")24 req.Header.Add("Accept", "application/xml")25 req.Header.Add("Accept", "text/html")26 req.Header.Add("Accept", "text/plain")27 resp, err := client.Do(req)28 if err != nil {29 panic(err)30 }31 fmt.Println(resp.Status)32}

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 }5 client := &http.Client{}6 resp, err := client.Do(req)7 if err != nil {8 }9 fmt.Println(resp)10}11&{200 OK 200 HTTP/1.1 1 1 map[Content-Type:[text/html; charset=utf-8] Date:[Thu, 20 Sep 2018 12:19:43 GMT] Content-Length:[1169] X-Content-Type-Options:[nosniff] Age:[1] X-Frame-Options:[SAMEORIGIN] Etag:["5ba2b9c3-491"] X-Xss-Protection:[1; mode=block] Server:[GitHub.com]] 1169 [] false false map[] 0xc4200f7b80 0xc4200f7b40}12import (13func main() {14 if err != nil {15 }16 client := &http.Client{}17 resp, err := client.Do(req)18 if err != nil {19 }20 fmt.Println(resp)21}22&{200 OK 200 HTTP/1.1 1 1 map[Content-Type:[text/html; charset=utf-8] Date:[Thu, 20 Sep 2018 12:19:43 GMT] Content-Length:[1169] X-Content-Type-Options:[nosniff] Age:[1] X-Frame-Options:[SAMEORIGIN] Etag:["5ba2b9c3-491

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 client := tdhttp.NewClient()7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println(err)10 }11 defer resp.Body.Close()12 fmt.Println(resp.StatusCode)13}

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 req.Header.Add("X-My-Header", "my value")7 client := tdhttp.NewClient()8 resp, err := client.Do(req)9 if err != nil {10 panic(err)11 }12 fmt.Printf("%s13}14Content-Type: text/html; charset=UTF-815Alt-Svc: h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"16Content-Type: text/html; charset=UTF-8

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 tdhttp.NewRequest()4 fmt.Println("Hello, playground")5}6import (7func main() {8 tdhttp.NewRequest()9 fmt.Println("Hello, playground")10}11import (12func main() {13 tdhttp.NewRequest()14 fmt.Println("Hello, playground")15}16import (17func main() {18 tdhttp.NewRequest()19 fmt.Println("Hello, playground")20}21import (22func main() {23 tdhttp.NewRequest()24 fmt.Println("Hello, playground")25}26import (27func main() {28 tdhttp.NewRequest()29 fmt.Println("Hello, playground")30}31import (32func main() {33 tdhttp.NewRequest()34 fmt.Println("Hello, playground")35}36import (37func main() {38 tdhttp.NewRequest()39 fmt.Println("Hello,

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http := tdhttp.New()4 response, err := http.Do(req)5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(string(response))9}10import (11func main() {12 http := tdhttp.New()13 response, err := http.Do(req)14 if err != nil {15 fmt.Println(err)16 }17 fmt.Println(string(response))18}19import (20func main() {21 http := tdhttp.New()22 response, err := http.Do(req)23 if err != nil {24 fmt.Println(err)25 }26 fmt.Println(string(response))27}28import (29func main() {30 http := tdhttp.New()

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 }5 fmt.Println(req)6}7import (8func main() {9 if err != nil {10 }11 fmt.Println(req)12}13import (14func main() {15 if err != nil {16 }17 fmt.Println(req)18}19import (20func main() {21 if err != nil {22 }23 fmt.Println(req)24}25import (26func main() {27 if err != nil {28 }29 fmt.Println(req)30}

Full Screen

Full Screen

NewRequest

Using AI Code Generation

copy

Full Screen

1import "tdhttp"2var req = tdhttp.NewRequest()3req.SetMethod("GET")4req.SetHeader("Content-Type", "application/json")5req.SetBody("This is the request body")6var resp = req.Send()7var statusCode = resp.GetStatusCode()8var body = resp.GetBody()9var header = resp.GetHeader()10var contentType = resp.GetHeader("Content-Type")11var contentLength = resp.GetHeader("Content-Length")12var server = resp.GetHeader("Server")13var date = resp.GetHeader("Date")14var connection = resp.GetHeader("Connection")15var xFrameOptions = resp.GetHeader("X-Frame-Options")16var xXssProtection = resp.GetHeader("X-XSS-Protection")17var xContentTypeOptions = resp.GetHeader("X-Content-Type-Options")18var p3p = resp.GetHeader("P3P")19var setCookie = resp.GetHeader("Set-Cookie")20var expires = resp.GetHeader("Expires")21var cacheControl = resp.GetHeader("Cache-Control")22var pragma = resp.GetHeader("Pragma")23var vary = resp.GetHeader("Vary")24var transferEncoding = resp.GetHeader("Transfer-Encoding")25var altSvc = resp.GetHeader("Alt-Svc")

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