How to use SaveSamples method of httpext Package

Best K6 code snippet using httpext.SaveSamples

tracer_test.go

Source:tracer_test.go Github

copy

Full Screen

...73 _, err = io.Copy(ioutil.Discard, res.Body)74 assert.NoError(t, err)75 assert.NoError(t, res.Body.Close())76 trail := tracer.Done()77 trail.SaveSamples(stats.IntoSampleTags(&map[string]string{"tag": "value"}))78 samples := trail.GetSamples()79 assert.Empty(t, tracer.protoErrors)80 assertLaterOrZero(t, tracer.getConn, isReuse)81 assertLaterOrZero(t, tracer.connectStart, isReuse)82 assertLaterOrZero(t, tracer.connectDone, isReuse)83 assertLaterOrZero(t, tracer.tlsHandshakeStart, isReuse)84 assertLaterOrZero(t, tracer.tlsHandshakeDone, isReuse)85 assertLaterOrZero(t, tracer.gotConn, false)86 assertLaterOrZero(t, tracer.wroteRequest, false)87 assertLaterOrZero(t, tracer.gotFirstResponseByte, false)88 assertLaterOrZero(t, now(), false)89 assert.Equal(t, strings.TrimPrefix(srv.URL, "https://"), trail.ConnRemoteAddr.String())90 assert.Len(t, samples, 8)91 seenMetrics := map[*stats.Metric]bool{}92 for i, s := range samples {93 assert.NotContains(t, seenMetrics, s.Metric)94 seenMetrics[s.Metric] = true95 assert.False(t, s.Time.IsZero())96 assert.Equal(t, map[string]string{"tag": "value"}, s.Tags.CloneTags())97 switch s.Metric {98 case metrics.HTTPReqs:99 assert.Equal(t, 1.0, s.Value)100 assert.Equal(t, 0, i, "`HTTPReqs` is reported before the other HTTP metrics")101 case metrics.HTTPReqConnecting, metrics.HTTPReqTLSHandshaking:102 if isReuse {103 assert.Equal(t, 0.0, s.Value)104 break105 }106 fallthrough107 case metrics.HTTPReqDuration, metrics.HTTPReqBlocked, metrics.HTTPReqSending, metrics.HTTPReqWaiting, metrics.HTTPReqReceiving:108 assert.True(t, s.Value > 0.0, "%s is <= 0", s.Metric.Name)109 default:110 t.Errorf("unexpected metric: %s", s.Metric.Name)111 }112 }113 })114 }115}116type failingConn struct {117 net.Conn118}119var failOnConnWrite = false120func (c failingConn) Write(b []byte) (int, error) {121 if failOnConnWrite {122 failOnConnWrite = false123 return 0, errors.New("write error")124 }125 return c.Conn.Write(b)126}127func TestTracerNegativeHttpSendingValues(t *testing.T) {128 if runtime.GOOS == "windows" {129 t.Skip()130 }131 t.Parallel()132 srv := httptest.NewTLSServer(httpbin.New().Handler())133 defer srv.Close()134 transport, ok := srv.Client().Transport.(*http.Transport)135 assert.True(t, ok)136 dialer := &net.Dialer{}137 transport.DialContext = func(ctx context.Context, proto, addr string) (net.Conn, error) {138 conn, err := dialer.DialContext(ctx, proto, addr)139 return failingConn{conn}, err140 }141 req, err := http.NewRequest("GET", srv.URL+"/get", nil)142 require.NoError(t, err)143 {144 tracer := &Tracer{}145 res, err := transport.RoundTrip(req.WithContext(httptrace.WithClientTrace(context.Background(), tracer.Trace())))146 require.NoError(t, err)147 _, err = io.Copy(ioutil.Discard, res.Body)148 assert.NoError(t, err)149 assert.NoError(t, res.Body.Close())150 tracer.Done()151 }152 // make the next connection write fail153 failOnConnWrite = true154 {155 tracer := &Tracer{}156 res, err := transport.RoundTrip(req.WithContext(httptrace.WithClientTrace(context.Background(), tracer.Trace())))157 require.NoError(t, err)158 _, err = io.Copy(ioutil.Discard, res.Body)159 assert.NoError(t, err)160 assert.NoError(t, res.Body.Close())161 trail := tracer.Done()162 trail.SaveSamples(nil)163 require.True(t, trail.Sending > 0)164 }165}166func TestTracerError(t *testing.T) {167 t.Parallel()168 srv := httptest.NewTLSServer(httpbin.New().Handler())169 defer srv.Close()170 tracer := &Tracer{}171 req, err := http.NewRequest("GET", srv.URL+"/get", nil)172 require.NoError(t, err)173 _, err = http.DefaultTransport.RoundTrip(174 req.WithContext(175 httptrace.WithClientTrace(176 context.Background(),...

Full Screen

Full Screen

transport.go

Source:transport.go Github

copy

Full Screen

...128 if ip, _, err := net.SplitHostPort(trail.ConnRemoteAddr.String()); err == nil {129 tags["ip"] = ip130 }131 }132 trail.SaveSamples(stats.IntoSampleTags(&tags))133 stats.PushIfNotCancelled(unfReq.ctx, t.state.Samples, trail)134 return result135}136func (t *transport) saveCurrentRequest(currentRequest *unfinishedRequest) {137 t.lastRequestLock.Lock()138 unprocessedRequest := t.lastRequest139 t.lastRequest = currentRequest140 t.lastRequestLock.Unlock()141 if unprocessedRequest != nil {142 // This shouldn't happen, since we have one transport per request, but just in case...143 t.state.Logger.Warnf("TracerTransport: unexpected unprocessed request for %s", unprocessedRequest.request.URL)144 t.measureAndEmitMetrics(unprocessedRequest)145 }146}...

Full Screen

Full Screen

SaveSamples

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {4 rw.Header().Set("Content-Type", "application/json")5 rw.WriteHeader(http.StatusOK)6 rw.Write([]byte(`{"message": "Hello there"}`))7 }))8 defer server.Close()9 req, err := http.NewRequest("GET", server.URL, nil)10 if err != nil {11 log.Fatal(err)12 }13 res := &http.Response{14 Header: make(http.Header),15 }16 res.Header.Set("Content-Type", "application/json")17 sample := &stats.Sample{18 Metric: stats.Metric{19 Threshold: stats.Thresholds{},20 },21 Time: stats.D(10 * time.Millisecond),22 Tags: stats.NewSampleTags(map[string]string{"url": server.URL, "status": "200"}),23 }24 samples := stats.NewSampleContainer()25 samples = append(samples, sample)26 ctx := context.Background()27 group := &sync.WaitGroup{}28 vu := &lib.VU{29 Logger: log.New(os.Stderr, "", log.LstdFlags),30 }

Full Screen

Full Screen

SaveSamples

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {4 fmt.Fprintln(w, "Hello, client")5 }))6 defer ts.Close()7 req, err := http.NewRequest("GET", ts.URL, nil)8 if err != nil {9 log.Fatal(err)10 }11 client := &http.Client{}12 resp, err := client.Do(req)13 if err != nil {14 log.Fatal(err)15 }16 dump, err := httputil.DumpResponse(resp, true)17 if err != nil {18 log.Fatal(err)19 }20 err = httpext.SaveSamples(dump, os.Stdout)21 if err != nil {22 log.Fatal(err)23 }

Full Screen

Full Screen

SaveSamples

Using AI Code Generation

copy

Full Screen

1func main() {2 samples := []Sample{3 {1, "one"},4 {2, "two"},5 {3, "three"},6 {4, "four"},7 {5, "five"},8 }9 httpext.SaveSamples(samples)10}11func main() {12 samples := []Sample{13 {6, "six"},14 {7, "seven"},15 {8, "eight"},16 {9, "nine"},17 {10, "ten"},18 }19 httpext.SaveSamples(samples)20}21func main() {22 samples := httpext.GetSamples()23 fmt.Println(samples)24}25[{1 one} {2 two} {3 three} {4 four} {5 five} {6 six} {7 seven} {8 eight} {9 nine} {10 ten}]

Full Screen

Full Screen

SaveSamples

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f := fasthttpadaptor.NewFastHTTPHandlerFunc(handler)4 http.ListenAndServe(":8080", f)5}6func handler(ctx *fasthttp.RequestCtx) {7 ctx.SetContentType("text/plain; charset=utf8")8 ctx.SetStatusCode(fasthttp.StatusOK)9 ctx.SetBodyString("Hello, world!")10}11import (12func main() {13 f := fasthttpadaptor.NewFastHTTPHandlerFunc(handler)14 http.ListenAndServe(":8080", f)15}16func handler(ctx *fasthttp.RequestCtx) {

Full Screen

Full Screen

SaveSamples

Using AI Code Generation

copy

Full Screen

1func main() {2 samples = append(samples, "Sample1")3 samples = append(samples, "Sample2")4 samples = append(samples, "Sample3")5 httpext.SaveSamples(samples, "test.txt")6}7func main() {8 samples = httpext.LoadSamples("test.txt")9 for i := 0; i < len(samples); i++ {10 fmt.Println(samples[i])11 }12}

Full Screen

Full Screen

SaveSamples

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &fasthttp.HostClient{4 }5 req := fasthttp.AcquireRequest()6 req.Header.SetMethod("GET")7 req.Header.Set("User-Agent", "Fasthttp")8 resp := fasthttp.AcquireResponse()9 err := client.Do(req, resp)10 if err != nil {11 fmt.Println("Error in sending request")12 }13 fmt.Println(string(resp.Body()))14}15import (16func main() {17 client := &fasthttp.HostClient{18 }19 req := fasthttp.AcquireRequest()20 req.Header.SetMethod("GET")21 req.Header.Set("User-Agent", "Fasthttp")22 resp := fasthttp.AcquireResponse()23 err := client.Do(req, resp)24 if err != nil {25 fmt.Println("Error in sending request")26 }27 fmt.Println(string(resp.Body()))28}29import (30func main() {31 client := &fasthttp.HostClient{32 }33 req := fasthttp.AcquireRequest()34 req.Header.SetMethod("GET")35 req.Header.Set("User-Agent", "Fasthttp")

Full Screen

Full Screen

SaveSamples

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter URL:")4 fmt.Scanln(&url)5 fmt.Println("Enter number of samples:")6 fmt.Scanln(&samples)7 httpext.SaveSamples(url, samples)8}9import (10func SaveSamples(url string, samples int) {11 file, err := os.Create("samples.txt")12 if err != nil {13 fmt.Println("Error creating file:", err)14 }15 defer file.Close()16 writer := bufio.NewWriter(file)17 header += "Samples: " + fmt.Sprint(samples) + "\r18 writer.WriteString(header)19 for i := 0; i < samples; i++ {20 t := time.Now()21 resp, err := http.Get(url)22 if err != nil {23 fmt.Println("Error making request:", err)24 }25 latency := time.Since(t)26 sample := t.Format(time.RFC3339) + "\t\t\t\t" + fmt.Sprint(status) + "\t\t\t\t" + latency.String() + "\r27 writer.WriteString(sample)28 }29 writer.Flush()30}

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