Best K6 code snippet using http.expectedStatuses
client.go
Source:client.go
...82// It also logs and records them and checks that response status code is equal to one of the provided.83// Request and response Body fields are filled, inner *http.(Request|Response).Body fields84// are replaced by stubs.85// In case of error it fails test.86func (c *Client) Do(t TestingT, req *Request, expectedStatuses ...int) *Response {87 status, headers, body, err := dumpRequest(req.Request)88 if err != nil {89 t.Fatalf("can't dump request: %s", err)90 }91 repr := bodyRepr(req.Header.Get("Content-Type"), body)92 colorF := func(b []byte) string { return color.BlueString("%s", string(b)) }93 if config.Default.Verbose {94 t.Logf("\n%s\n%s\n\n%s\n", colorF(status), colorF(headers), colorF(repr))95 } else {96 t.Logf("%s\n", colorF(status))97 }98 if req.Recorder != nil && req.RequestWC != nil {99 err = req.Recorder.RecordRequest(req.Request, status, headers, repr, req.RequestWC)100 if err != nil {101 t.Fatalf("can't record request: %s", err)102 }103 if f, ok := req.RequestWC.(*os.File); ok {104 t.Logf("request recorded to %s", f.Name())105 } else {106 t.Logf("request recorded")107 }108 }109 r, err := c.HTTPClient.Do(req.Request)110 if r != nil {111 origBody := r.Body112 defer func() {113 err = origBody.Close()114 if err != nil {115 t.Fatalf("can't close response body: %s", err)116 }117 }()118 }119 if err != nil {120 t.Fatalf("can't make request: %s", err)121 }122 // put dumped request body back123 req.Body = body124 req.Request.Body = errorReadCloser{}125 resp := &Response{Response: r}126 status, headers, body, err = dumpResponse(resp.Response)127 if err != nil {128 t.Fatalf("can't dump response: %s", err)129 }130 // put dumped response body back131 resp.Body = body132 resp.Response.Body = errorReadCloser{}133 repr = bodyRepr(resp.Header.Get("Content-Type"), body)134 switch {135 case resp.StatusCode >= 400:136 colorF = func(b []byte) string { return color.RedString("%s", string(b)) }137 case resp.StatusCode >= 300:138 colorF = func(b []byte) string { return color.YellowString("%s", string(b)) }139 default:140 colorF = func(b []byte) string { return color.GreenString("%s", string(b)) }141 }142 if config.Default.Verbose {143 t.Logf("\n%s\n%s\n\n%s\n", colorF(status), colorF(headers), colorF(repr))144 } else {145 t.Logf("%s\n", colorF(status))146 }147 if req.Recorder != nil && req.ResponseWC != nil {148 err = req.Recorder.RecordResponse(resp.Response, status, headers, repr, req.ResponseWC)149 if err != nil {150 t.Fatalf("can't record response: %s", err)151 }152 if f, ok := req.ResponseWC.(*os.File); ok {153 t.Logf("response recorded to %s", f.Name())154 } else {155 t.Logf("response recorded")156 }157 }158 if len(expectedStatuses) > 0 {159 var found bool160 for _, s := range expectedStatuses {161 if resp.StatusCode == s {162 found = true163 break164 }165 }166 if !found {167 t.Errorf("%s %s: expected status code to be in %v, got %s", req.Method, req.URL.String(), expectedStatuses, resp.Status)168 }169 }170 return resp171}172// Head makes HEAD request. See Do for more details.173func (c *Client) Head(t TestingT, urlStr string, expectedStatuses ...int) *Response {174 return c.Do(t, c.NewRequest(t, "HEAD", urlStr, nil), expectedStatuses...)175}176// Get makes GET request. See Do for more details.177func (c *Client) Get(t TestingT, urlStr string, expectedStatuses ...int) *Response {178 return c.Do(t, c.NewRequest(t, "GET", urlStr, nil), expectedStatuses...)179}180// Post makes POST request. See Do for more details.181func (c *Client) Post(t TestingT, urlStr string, body fmt.Stringer, expectedStatuses ...int) *Response {182 return c.Do(t, c.NewRequest(t, "POST", urlStr, body), expectedStatuses...)183}184// Put makes PUT request. See Do for more details.185func (c *Client) Put(t TestingT, urlStr string, body fmt.Stringer, expectedStatuses ...int) *Response {186 return c.Do(t, c.NewRequest(t, "PUT", urlStr, body), expectedStatuses...)187}188// Patch makes PATCH request. See Do for more details.189func (c *Client) Patch(t TestingT, urlStr string, body fmt.Stringer, expectedStatuses ...int) *Response {190 return c.Do(t, c.NewRequest(t, "PATCH", urlStr, body), expectedStatuses...)191}192// Delete makes DELETE request. See Do for more details.193func (c *Client) Delete(t TestingT, urlStr string, expectedStatuses ...int) *Response {194 return c.Do(t, c.NewRequest(t, "DELETE", urlStr, nil), expectedStatuses...)195}...
http.go
Source:http.go
...14func (c *client) doGet(15 ctx context.Context,16 path string,17 queryParams interface{},18 expectedStatuses ...int,19) (*http.Response, error) {20 return c.doRequest(ctx, http.MethodGet, path, queryParams, nil, expectedStatuses...)21}22func (c *client) doPost(23 ctx context.Context,24 path string,25 queryParams interface{},26 formData interface{},27 expectedStatuses ...int,28) (*http.Response, error) {29 return c.doRequest(ctx, http.MethodPost, path, queryParams, formData, expectedStatuses...)30}31func (c *client) doPut(32 ctx context.Context,33 path string,34 queryParams interface{},35 formData interface{},36 expectedStatuses ...int,37) (*http.Response, error) {38 return c.doRequest(ctx, http.MethodPut, path, queryParams, formData, expectedStatuses...)39}40func (c *client) doDelete(41 ctx context.Context,42 path string,43 queryParams interface{},44 expectedStatuses ...int,45) (*http.Response, error) {46 return c.doRequest(ctx, http.MethodDelete, path, queryParams, nil, expectedStatuses...)47}48func (c *client) doHead(49 ctx context.Context,50 path string,51 queryParams interface{},52 expectedStatuses ...int,53) (*http.Response, error) {54 return c.doRequest(ctx, http.MethodHead, path, queryParams, nil, expectedStatuses...)55}56func (c *client) doRequest(57 ctx context.Context,58 method string,59 path string,60 queryParams interface{},61 formData interface{},62 expectedStatuses ...int,63) (*http.Response, error) {64 u := c.resolveURL(path)65 if queryParams != nil {66 queryValues, err := c.paramSourceToValues(queryParams)67 if err != nil {68 return nil, err69 }70 u.RawQuery = queryValues.Encode()71 }72 var body string73 var bodyReader io.Reader74 if formData != nil {75 formValues, err := c.paramSourceToValues(formData)76 if err != nil {77 return nil, err78 }79 body = formValues.Encode()80 bodyReader = strings.NewReader(body)81 }82 req, err := http.NewRequestWithContext(ctx, method, u.String(), bodyReader)83 if err != nil {84 return nil, err85 }86 if formData != nil {87 c.addFormHeaders(req, body)88 }89 c.addCommonHeaders(req)90 c.addAuthHeaders(req)91 res, err := c.httpClient.Do(req)92 if err == nil {93 err = c.checkResponseStatus(res, expectedStatuses...)94 }95 return res, err96}97func (c *client) mergeParamSources(paramSources ...interface{}) (*url.Values, error) {98 mergedValues := url.Values{}99 for _, paramSource := range paramSources {100 paramSourceValues, err := c.paramSourceToValues(paramSource)101 if err != nil {102 return nil, err103 }104 for key, values := range *paramSourceValues {105 mergedValues[key] = append(mergedValues[key], values...)106 }107 }108 return &mergedValues, nil109}110func (c *client) paramSourceToValues(paramSource interface{}) (*url.Values, error) {111 if paramSource == nil {112 return nil, nil113 }114 if values, ok := paramSource.(*url.Values); ok {115 return values, nil116 }117 if m, ok := paramSource.(map[string]string); ok {118 values := make(url.Values)119 for key, val := range m {120 values.Add(key, val)121 }122 return &values, nil123 }124 if m, ok := paramSource.(map[string][]string); ok {125 values := url.Values(m)126 return &values, nil127 }128 values, err := query.Values(paramSource)129 if err != nil {130 return nil, err131 }132 return &values, nil133}134func (c *client) resolveURL(path string) *url.URL {135 rel := &url.URL{Path: path}136 u := c.baseURL.ResolveReference(rel)137 return u138}139func (c *client) addFormHeaders(req *http.Request, requestBody string) {140 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")141 req.Header.Add("Content-Length", strconv.Itoa(len(requestBody)))142}143func (c *client) addCommonHeaders(req *http.Request) {144 req.Header.Set("Accept", "application/json;q=0.9,text/plain")145 if c.userAgent != "" {146 req.Header.Set("User-Agent", c.userAgent)147 }148}149func (c *client) addAuthHeaders(req *http.Request) {150 if c.jSessionId != nil {151 req.Header.Set("Cookie", fmt.Sprintf("JSESSIONID=%s", *c.jSessionId))152 }153 if c.jwt != nil {154 req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *c.jwt))155 }156}157func (c *client) readBodyAsString(res *http.Response) (string, error) {158 b, err := ioutil.ReadAll(res.Body)159 if err != nil {160 return "", err161 }162 return string(b), nil163}164func (c *client) readBodyAsJson(res *http.Response, v interface{}) error {165 err := json.NewDecoder(res.Body).Decode(v)166 _ = res.Body.Close()167 return err168}169func (c *client) checkResponseStatus(res *http.Response, expectedStatuses ...int) error {170 if len(expectedStatuses) == 0 {171 // the caller didn't specify any status: assume they will deal with statuses themselves172 return nil173 }174 for _, status := range expectedStatuses {175 if res.StatusCode == status {176 return nil177 }178 }179 return c.bodyToError(res)180}181func (c *client) bodyToError(res *http.Response) error {182 message, err := c.readBodyAsString(res)183 if message != "" && err == nil {184 contentType := res.Header.Get("Content-Type")185 if contentType == "application/json" {186 payload := &errorPayload{}187 err = json.NewDecoder(strings.NewReader(message)).Decode(payload)188 if err == nil && payload.Message != "" {...
response_callback.go
Source:response_callback.go
...24 "github.com/dop251/goja"25 "go.k6.io/k6/js/common"26)27//nolint:gochecknoglobals28var defaultExpectedStatuses = expectedStatuses{29 minmax: [][2]int{{200, 399}},30}31// expectedStatuses is specifically totally unexported so it can't be used for anything else but32// SetResponseCallback and nothing can be done from the js side to modify it or make an instance of33// it except using ExpectedStatuses34type expectedStatuses struct {35 minmax [][2]int36 exact []int37}38func (e expectedStatuses) match(status int) bool {39 for _, v := range e.exact {40 if v == status {41 return true42 }43 }44 for _, v := range e.minmax {45 if v[0] <= status && status <= v[1] {46 return true47 }48 }49 return false50}51// expectedStatuses returns expectedStatuses object based on the provided arguments.52// The arguments must be either integers or object of `{min: <integer>, max: <integer>}`53// kind. The "integer"ness is checked by the Number.isInteger.54func (mi *ModuleInstance) expectedStatuses(args ...goja.Value) *expectedStatuses {55 rt := mi.vu.Runtime()56 if len(args) == 0 {57 common.Throw(rt, errors.New("no arguments"))58 }59 var result expectedStatuses60 jsIsInt, _ := goja.AssertFunction(rt.GlobalObject().Get("Number").ToObject(rt).Get("isInteger"))61 isInt := func(a goja.Value) bool {62 v, err := jsIsInt(goja.Undefined(), a)63 return err == nil && v.ToBoolean()64 }65 errMsg := "argument number %d to expectedStatuses was neither an integer nor an object like {min:100, max:329}"66 for i, arg := range args {67 o := arg.ToObject(rt)68 if o == nil {69 common.Throw(rt, fmt.Errorf(errMsg, i+1))70 }71 if isInt(arg) {72 result.exact = append(result.exact, int(o.ToInteger()))73 } else {74 min := o.Get("min")75 max := o.Get("max")76 if min == nil || max == nil {77 common.Throw(rt, fmt.Errorf(errMsg, i+1))78 }79 if !(isInt(min) && isInt(max)) {80 common.Throw(rt, fmt.Errorf("both min and max need to be integers for argument number %d", i+1))81 }82 result.minmax = append(result.minmax, [2]int{int(min.ToInteger()), int(max.ToInteger())})83 }84 }85 return &result86}87// SetResponseCallback sets the responseCallback to the value provided. Supported values are88// expectedStatuses object or a `null` which means that metrics shouldn't be tagged as failed and89// `http_req_failed` should not be emitted - the behaviour previous to this90func (c *Client) SetResponseCallback(val goja.Value) {91 if val != nil && !goja.IsNull(val) {92 // This is done this way as ExportTo exports functions to empty structs without an error93 if es, ok := val.Export().(*expectedStatuses); ok {94 c.responseCallback = es.match95 } else {96 common.Throw(97 c.moduleInstance.vu.Runtime(),98 fmt.Errorf("unsupported argument, expected http.expectedStatuses"),99 )100 }101 } else {102 c.responseCallback = nil103 }104}...
expectedStatuses
Using AI Code Generation
1import (2func main() {3 fmt.Println(http.StatusContinue)4 fmt.Println(http.StatusSwitchingProtocols)5 fmt.Println(http.StatusProcessing)6 fmt.Println(http.StatusOK)7 fmt.Println(http.StatusCreated)8 fmt.Println(http.StatusAccepted)9 fmt.Println(http.StatusNonAuthoritativeInfo)10 fmt.Println(http.StatusNoContent)11 fmt.Println(http.StatusResetContent)12 fmt.Println(http.StatusPartialContent)13 fmt.Println(http.StatusMultiStatus)14 fmt.Println(http.StatusAlreadyReported)15 fmt.Println(http.StatusIMUsed)16 fmt.Println(http.StatusMultipleChoices)17 fmt.Println(http.StatusMovedPermanently)18 fmt.Println(http.StatusFound)19 fmt.Println(http.StatusSeeOther)20 fmt.Println(http.StatusNotModified)21 fmt.Println(http.StatusUseProxy)22 fmt.Println(http.StatusTemporaryRedirect)23 fmt.Println(http.StatusPermanentRedirect)24 fmt.Println(http.StatusBadRequest)25 fmt.Println(http.StatusUnauthorized)26 fmt.Println(http.StatusPaymentRequired)27 fmt.Println(http.StatusForbidden)28 fmt.Println(http.StatusNotFound)29 fmt.Println(http.StatusMethodNotAllowed)30 fmt.Println(http.StatusNotAcceptable)31 fmt.Println(http.StatusProxyAuthRequired)32 fmt.Println(http.StatusRequestTimeout)33 fmt.Println(http.StatusConflict)34 fmt.Println(http.StatusGone)35 fmt.Println(http.StatusLengthRequired)36 fmt.Println(http.StatusPreconditionFailed)37 fmt.Println(http.StatusRequestEntityTooLarge)38 fmt.Println(http.StatusRequestURITooLong)39 fmt.Println(http.StatusUnsupportedMediaType)40 fmt.Println(http.StatusRequestedRangeNotSatisfiable)41 fmt.Println(http.StatusExpectationFailed)42 fmt.Println(http.StatusTeapot)43 fmt.Println(http.StatusMisdirectedRequest)44 fmt.Println(http.StatusUnprocessableEntity)45 fmt.Println(http.StatusLocked)46 fmt.Println(http.StatusFailedDependency)47 fmt.Println(http.StatusUpgradeRequired)48 fmt.Println(http.StatusPreconditionRequired)49 fmt.Println(http.StatusTooManyRequests)50 fmt.Println(http.StatusRequestHeaderFieldsTooLarge)51 fmt.Println(http.StatusUnavailableForLegalReasons)52 fmt.Println(http.StatusInternalServerError)53 fmt.Println(http.StatusNotImplemented)54 fmt.Println(http.StatusBadGateway)55 fmt.Println(http.StatusServiceUnavailable)56 fmt.Println(http.StatusGatewayTimeout)57 fmt.Println(http.StatusHTTPVersionNotSupported)58 fmt.Println(http.StatusVariantAlsoNegotiates)59 fmt.Println(http.StatusInsufficientStorage)
expectedStatuses
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer resp.Body.Close()7 fmt.Println("Response status:", resp.Status)8 fmt.Println("Response Headers:", resp.Header)9 fmt.Println("Response Body:", resp.Body)10}11Response Headers: map[Cache-Control:[private, max-age=0] Content-Type:[text/plain; charset=UTF-8] Date:[Thu, 09 May 2019 09:17:47 GMT] Expires:[-1] Server:[gws] Vary:[Accept-Encoding] X-Xss-Protection:[0]]12import (13func main() {14 if err != nil {15 fmt.Println(err)16 }17 defer resp.Body.Close()18 fmt.Println("Response status:", resp.StatusCode)19 fmt.Println("Response Headers:", resp.Header)20 fmt.Println("Response Body:", resp.Body)21}22Response Headers: map[Date:[Thu, 09 May 2019 09:19:02 GMT] Expires:[-1] Cache-Control:[private, max-age=0] Content-Type:[text/plain; charset=UTF-8] Server:[gws] Vary:[Accept-Encoding] X-Xss-Protection:[0]]23import (24func main() {25 if err != nil {26 fmt.Println(err)27 }28 defer resp.Body.Close()29 fmt.Println("Response status:", resp.Status)30 fmt.Println("Response Headers:", resp.Header)31 fmt.Println("Response Body:", resp.Body)32}33Response Headers: map[Cache-Control:[private, max-age=0] Content-Type:[text/plain; charset=UTF-8] Date:[Thu
expectedStatuses
Using AI Code Generation
1import (2func main() {3 if err != nil {4 panic(err)5 }6 defer resp.Body.Close()7 fmt.Println(resp.Status)8 fmt.Println(resp.Header)9 if resp.StatusCode == http.StatusOK {10 fmt.Println("Connection established")11 } else {12 fmt.Println("Connection failed")13 }14}15map[Content-Type:[text/html; charset=ISO-8859-1] Date:[Sat, 09 Apr 2016 09:11:14 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[1; mode=block]]16Your name to display (optional):17Your name to display (optional):18if err != nil {19 panic(err)20}21defer resp.Body.Close()22fmt.Println(resp.Status)23fmt.Println(resp.Header)24if resp.StatusCode == http.StatusOK {25 fmt.Println("Connection established")26} else {27 fmt.Println("Connection failed")28}
expectedStatuses
Using AI Code Generation
1import (2func main() {3 if err != nil {4 }5 defer resp.Body.Close()6 body, err := ioutil.ReadAll(resp.Body)7 if err != nil {8 }9 fmt.Println(resp.Status)10 fmt.Println(string(body))11}
expectedStatuses
Using AI Code Generation
1import (2func TestHelloWorld(t *testing.T) {3 req, err := http.NewRequest("GET", "/", nil)4 if err != nil {5 t.Fatal(err)6 }7 rr := httptest.NewRecorder()8 handler := http.HandlerFunc(HelloWorldHandler)9 handler.ServeHTTP(rr, req)10 if status := rr.Code; status != http.StatusOK {11 t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)12 }13 if rr.Body.String() != expected {14 t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected)15 }16}17func HelloWorldHandler(w http.ResponseWriter, r *http.Request) {18 fmt.Fprintf(w, "Hello World!")19}20import (21func TestHelloWorld(t *testing.T) {22 req, err := http.NewRequest("GET", "/", nil)23 if err != nil {24 t.Fatal(err)25 }26 rr := httptest.NewRecorder()27 handler := http.HandlerFunc(HelloWorldHandler)28 handler.ServeHTTP(rr, req)29 if status := rr.Code; status != http.StatusOK {30 t.Errorf("handler returned wrong status code: got
expectedStatuses
Using AI Code Generation
1import ("net/http"; "net/http/httptest")2func TestHandler(t *testing.T) {3 req, err := http.NewRequest("GET", "/", nil)4 if err != nil {5 t.Fatal(err)6 }7 rr := httptest.NewRecorder()8 handler := http.HandlerFunc(Handler)9 handler.ServeHTTP(rr, req)10 if status := rr.Code; status != http.StatusOK {11 t.Errorf("handler returned wrong status code: got %v want %v",12 }13 expected := `{"alive": true}`14 if rr.Body.String() != expected {15 t.Errorf("handler returned unexpected body: got %v want %v",16 rr.Body.String(), expected)17 }18}19import ("net/http"; "net/http/httptest"; "testing")20func TestHandler(t *testing.T) {21 req, err := http.NewRequest("GET", "/", nil)22 if err != nil {23 t.Fatal(err)24 }25 rr := httptest.NewRecorder()26 handler := http.HandlerFunc(Handler)27 handler.ServeHTTP(rr, req)28 if status := rr.Code; status != http.StatusOK {29 t.Errorf("handler returned wrong status code: got %v want %v",30 }31 expected := `{"alive": true}`32 if rr.Body.String() != expected {33 t.Errorf("handler returned unexpected body: got %v want %v",34 rr.Body.String(), expected)35 }36}37import ("net/http"; "net/http/httptest"; "testing")38func TestHandler(t *testing.T) {39 req, err := http.NewRequest("GET", "/", nil)40 if err != nil {41 t.Fatal(err)42 }43 rr := httptest.NewRecorder()44 handler := http.HandlerFunc(Handler)45 handler.ServeHTTP(rr, req)
expectedStatuses
Using AI Code Generation
1import (2func main() {3 if status != expectedStatus {4 panic(fmt.Sprintf("Status code is %d instead of %d", status, expectedStatus))5 }6 fmt.Println("URL is valid")7}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!