How to use updateK6Response method of httpext Package

Best K6 code snippet using httpext.updateK6Response

request.go

Source:request.go Github

copy

Full Screen

...92 }93 return result94}95// TODO: move as a response method? or constructor?96func updateK6Response(k6Response *Response, finishedReq *finishedRequest) {97 k6Response.ErrorCode = int(finishedReq.errorCode)98 k6Response.Error = finishedReq.errorMsg99 trail := finishedReq.trail100 if trail.ConnRemoteAddr != nil {101 remoteHost, remotePortStr, _ := net.SplitHostPort(trail.ConnRemoteAddr.String())102 remotePort, _ := strconv.Atoi(remotePortStr)103 k6Response.RemoteIP = remoteHost104 k6Response.RemotePort = remotePort105 }106 k6Response.Timings = ResponseTimings{107 Duration: metrics.D(trail.Duration),108 Blocked: metrics.D(trail.Blocked),109 Connecting: metrics.D(trail.Connecting),110 TLSHandshaking: metrics.D(trail.TLSHandshaking),111 Sending: metrics.D(trail.Sending),112 Waiting: metrics.D(trail.Waiting),113 Receiving: metrics.D(trail.Receiving),114 }115}116// MakeRequest makes http request for tor the provided ParsedHTTPRequest.117//118// TODO: split apart...119// nolint: cyclop, gocyclo, funlen, gocognit120func MakeRequest(ctx context.Context, state *lib.State, preq *ParsedHTTPRequest) (*Response, error) {121 respReq := &Request{122 Method: preq.Req.Method,123 URL: preq.Req.URL.String(),124 Cookies: stdCookiesToHTTPRequestCookies(preq.Req.Cookies()),125 Headers: preq.Req.Header,126 }127 if preq.Body != nil {128 // TODO: maybe hide this behind of flag in order for this to not happen for big post/puts?129 // should we set this after the compression? what will be the point ?130 respReq.Body = preq.Body.String()131 if len(preq.Compressions) > 0 {132 compressedBody, contentEncoding, err := compressBody(preq.Compressions, ioutil.NopCloser(preq.Body))133 if err != nil {134 return nil, err135 }136 preq.Body = compressedBody137 currentContentEncoding := preq.Req.Header.Get("Content-Encoding")138 if currentContentEncoding == "" {139 preq.Req.Header.Set("Content-Encoding", contentEncoding)140 } else if currentContentEncoding != contentEncoding {141 state.Logger.Warningf(142 "There's a mismatch between the desired `compression` the manually set `Content-Encoding` header "+143 "in the %s request for '%s', the custom header has precedence and won't be overwritten. "+144 "This may result in invalid data being sent to the server.", preq.Req.Method, preq.Req.URL,145 )146 }147 }148 preq.Req.ContentLength = int64(preq.Body.Len()) // This will make Go set the content-length header149 preq.Req.GetBody = func() (io.ReadCloser, error) {150 // using `Bytes()` should reuse the same buffer and as such help with the memory usage. We151 // should not be writing to it any way so there shouldn't be way to corrupt it (?)152 return ioutil.NopCloser(bytes.NewBuffer(preq.Body.Bytes())), nil153 }154 // as per the documentation using GetBody still requires setting the Body.155 preq.Req.Body, _ = preq.Req.GetBody()156 }157 if contentLengthHeader := preq.Req.Header.Get("Content-Length"); contentLengthHeader != "" {158 // The content-length header was set by the user, delete it (since Go159 // will set it automatically) and warn if there were differences160 preq.Req.Header.Del("Content-Length")161 length, err := strconv.Atoi(contentLengthHeader)162 if err != nil || preq.Req.ContentLength != int64(length) {163 state.Logger.Warnf(164 "The specified Content-Length header %q in the %s request for %s "+165 "doesn't match the actual request body length of %d, so it will be ignored!",166 contentLengthHeader, preq.Req.Method, preq.Req.URL, preq.Req.ContentLength,167 )168 }169 }170 tags := state.CloneTags()171 // Override any global tags with request-specific ones.172 for k, v := range preq.Tags {173 tags[k] = v174 }175 // Only set the name system tag if the user didn't explicitly set it beforehand,176 // and the Name was generated from a tagged template string (via http.url).177 if _, ok := tags["name"]; !ok && state.Options.SystemTags.Has(metrics.TagName) &&178 preq.URL.Name != "" && preq.URL.Name != preq.URL.Clean() {179 tags["name"] = preq.URL.Name180 }181 // Check rate limit *after* we've prepared a request; no need to wait with that part.182 if rpsLimit := state.RPSLimit; rpsLimit != nil {183 if err := rpsLimit.Wait(ctx); err != nil {184 return nil, err185 }186 }187 tracerTransport := newTransport(ctx, state, tags, preq.ResponseCallback)188 var transport http.RoundTripper = tracerTransport189 // Combine tags with common log fields190 combinedLogFields := map[string]interface{}{"source": "http-debug", "vu": state.VUID, "iter": state.Iteration}191 for k, v := range tags {192 if _, present := combinedLogFields[k]; !present {193 combinedLogFields[k] = v194 }195 }196 if state.Options.HTTPDebug.String != "" {197 transport = httpDebugTransport{198 originalTransport: transport,199 httpDebugOption: state.Options.HTTPDebug.String,200 logger: state.Logger.WithFields(combinedLogFields),201 }202 }203 if preq.Auth == "digest" {204 // Until digest authentication is refactored, the first response will always205 // be a 401 error, so we expect that.206 if tracerTransport.responseCallback != nil {207 originalResponseCallback := tracerTransport.responseCallback208 tracerTransport.responseCallback = func(status int) bool {209 tracerTransport.responseCallback = originalResponseCallback210 return status == 401211 }212 }213 transport = digestTransport{originalTransport: transport}214 } else if preq.Auth == "ntlm" {215 // The first response of NTLM auth may be a 401 error.216 if tracerTransport.responseCallback != nil {217 originalResponseCallback := tracerTransport.responseCallback218 tracerTransport.responseCallback = func(status int) bool {219 tracerTransport.responseCallback = originalResponseCallback220 // ntlm is connection-level based so we could've already authorized the connection and to now reuse it221 return status == 401 || originalResponseCallback(status)222 }223 }224 transport = ntlmssp.Negotiator{RoundTripper: transport}225 }226 resp := &Response{URL: preq.URL.URL, Request: respReq}227 client := http.Client{228 Transport: transport,229 CheckRedirect: func(req *http.Request, via []*http.Request) error {230 resp.URL = req.URL.String()231 // Update active jar with cookies found in "Set-Cookie" header(s) of redirect response232 if preq.ActiveJar != nil {233 if respCookies := req.Response.Cookies(); len(respCookies) > 0 {234 preq.ActiveJar.SetCookies(via[len(via)-1].URL, respCookies)235 }236 req.Header.Del("Cookie")237 SetRequestCookies(req, preq.ActiveJar, preq.Cookies)238 }239 if l := len(via); int64(l) > preq.Redirects.Int64 {240 if !preq.Redirects.Valid {241 url := req.URL242 if l > 0 {243 url = via[0].URL244 }245 state.Logger.WithFields(logrus.Fields{"url": url.String()}).Warnf(246 "Stopped after %d redirects and returned the redirection; pass { redirects: n }"+247 " in request params or set global maxRedirects to silence this", l)248 }249 return http.ErrUseLastResponse250 }251 return nil252 },253 }254 reqCtx, cancelFunc := context.WithTimeout(ctx, preq.Timeout)255 defer cancelFunc()256 mreq := preq.Req.WithContext(reqCtx)257 res, resErr := client.Do(mreq)258 // TODO(imiric): It would be safer to check for a writeable259 // response body here instead of status code, but those are260 // wrapped in a read-only body when using client timeouts and are261 // unusable until https://github.com/golang/go/issues/31391 is fixed.262 if res != nil && res.StatusCode == http.StatusSwitchingProtocols {263 _ = res.Body.Close()264 return nil, fmt.Errorf("unsupported response status: %s", res.Status)265 }266 if resErr == nil {267 resp.Body, resErr = readResponseBody(state, preq.ResponseType, res, resErr)268 if resErr != nil && errors.Is(resErr, context.DeadlineExceeded) {269 // TODO This can be more specific that the timeout happened in the middle of the reading of the body270 resErr = NewK6Error(requestTimeoutErrorCode, requestTimeoutErrorCodeMsg, resErr)271 }272 }273 finishedReq := tracerTransport.processLastSavedRequest(wrapDecompressionError(resErr))274 if finishedReq != nil {275 updateK6Response(resp, finishedReq)276 }277 if resErr == nil {278 if preq.ActiveJar != nil {279 if rc := res.Cookies(); len(rc) > 0 {280 preq.ActiveJar.SetCookies(res.Request.URL, rc)281 }282 }283 resp.URL = res.Request.URL.String()284 resp.Status = res.StatusCode285 resp.StatusText = res.Status286 resp.Proto = res.Proto287 if res.TLS != nil {288 resp.setTLSInfo(res.TLS)289 }...

Full Screen

Full Screen

updateK6Response

Using AI Code Generation

copy

Full Screen

1import (2func TestUpdateK6Response(t *testing.T) {3 tb := httpmultibin.NewHTTPMultiBin(t)4 defer tb.Cleanup()5 rt := testutils.NewRuntime()6 defer func() { assert.NoError(t, rt.Cleanup()) }()7 state := &lib.State{Options: lib.Options{}}8 ctx := context.Background()

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.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful