How to use TestTracer method of httpext Package

Best K6 code snippet using httpext.TestTracer

tracer_test.go

Source:tracer_test.go Github

copy

Full Screen

...39 "github.com/pkg/errors"40 "github.com/stretchr/testify/assert"41 "github.com/stretchr/testify/require"42)43func TestTracer(t *testing.T) {44 if runtime.GOOS == "windows" {45 t.Skip()46 }47 t.Parallel()48 srv := httptest.NewTLSServer(httpbin.New().Handler())49 defer srv.Close()50 transport, ok := srv.Client().Transport.(*http.Transport)51 assert.True(t, ok)52 transport.DialContext = netext.NewDialer(net.Dialer{}).DialContext53 var prev int6454 assertLaterOrZero := func(t *testing.T, val int64, canBeZero bool) {55 if canBeZero && val == 0 {56 return57 }58 if prev > val {59 _, file, line, _ := runtime.Caller(1)60 t.Errorf("Expected %d to be greater or equal to %d (from %s:%d)", val, prev, file, line)61 return62 }63 prev = val64 }65 for tnum, isReuse := range []bool{false, true, true} {66 t.Run(fmt.Sprintf("Test #%d", tnum), func(t *testing.T) {67 // Do not enable parallel testing, test relies on sequential execution68 tracer := &Tracer{}69 req, err := http.NewRequest("GET", srv.URL+"/get", nil)70 require.NoError(t, err)71 res, err := transport.RoundTrip(req.WithContext(httptrace.WithClientTrace(context.Background(), tracer.Trace())))72 require.NoError(t, err)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(),177 tracer.Trace())))178 assert.Error(t, err)179 assert.Len(t, tracer.protoErrors, 1)180 assert.Error(t, tracer.protoErrors[0])...

Full Screen

Full Screen

TestTracer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cfg := &config.Configuration{4 Sampler: &config.SamplerConfig{5 },6 Reporter: &config.ReporterConfig{7 },8 }9 tracer, closer := initJaeger("example")10 defer closer.Close()11 opentracing.SetGlobalTracer(tracer)12 span := opentracing.StartSpan("example-client-span")13 span.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCClientEnum))14 span.SetTag("example_client_span_key", "example_client_span_value")15 span.LogFields(16 log.String("event", "soft error"),17 log.String("type", "cache timeout"),18 log.Int("waited.millis", 1500),19 span.Finish()20 span = opentracing.StartSpan("example-server-span")21 span.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCServerEnum))22 span.SetTag("example_server_span_key", "example_server_span_value")23 span.LogFields(24 log.String("event", "soft error"),25 log.String("type", "cache timeout"),26 log.Int("waited.millis", 1500),27 span.Finish()28 span = opentracing.StartSpan("example-server-span")29 span.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCServerEnum))30 span.SetTag("example_server_span_key", "example_server_span_value")31 span.LogFields(32 log.String("event", "soft

Full Screen

Full Screen

TestTracer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Fprintf(w, "Hello, %q", r.URL.Path)5 })6 fmt.Println("Starting server at port 8080")7 http.ListenAndServe(":8080", apmhttp.Wrap(http.DefaultServeMux))8}9import (10func main() {11 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {12 fmt.Fprintf(w, "Hello, %q", r.URL.Path)13 })14 fmt.Println("Starting server at port 8080")15 http.ListenAndServe(":8080", apmhttp.Wrap(http.DefaultServeMux))16}17import (18func main() {19 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {20 fmt.Fprintf(w, "Hello, %q", r.URL.Path)21 })22 fmt.Println("Starting server at port 8080")23 http.ListenAndServe(":8080", apmhttp.Wrap(http.DefaultServeMux))24}25import (26func main() {27 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {28 fmt.Fprintf(w, "Hello, %q", r.URL.Path)29 })30 fmt.Println("Starting server at port 8080")31 http.ListenAndServe(":8080", apmhttp.Wrap(http.DefaultServeMux))32}33import (

Full Screen

Full Screen

TestTracer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{4 Transport: apmhttp.WrapRoundTripper(http.DefaultTransport),5 }6 if err != nil {7 fmt.Println("error in creating request")8 }9 resp, err := client.Do(req)10 if err != nil {11 fmt.Println("error in getting response")12 }13 fmt.Println(resp.Status)14}15import (16func main() {17 client := &http.Client{18 Transport: apmhttp.WrapRoundTripper(http.DefaultTransport),19 }20 if err != nil {21 fmt.Println("error in creating request")22 }23 resp, err := client.Do(req)24 if err != nil {25 fmt.Println("error in getting response")26 }27 fmt.Println(resp.Status)28}29import (30func main() {31 client := &http.Client{32 Transport: apmhttp.WrapRoundTripper(http.DefaultTransport),33 }34 if err != nil {35 fmt.Println("error in creating request")36 }37 resp, err := client.Do(req)38 if err != nil {39 fmt.Println("error in getting response")40 }41 fmt.Println(resp.Status)42}43import (44func main() {45 client := &http.Client{

Full Screen

Full Screen

TestTracer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 sensor := instana.NewSensor("my-service")4 tracer := instahttp.NewTracer(sensor)5 client := &http.Client{6 Transport: tracer.Transport(http.DefaultTransport),7 }8 resp, err := client.Do(req)9 if err != nil {10 fmt.Println(err)11 } else {12 fmt.Println(resp.Status)13 }14}15import (16func main() {17 sensor := instana.NewSensor("my-service")18 tracer := instahttp.NewTracer(sensor)19 client := &http.Client{20 Transport: tracer.Transport(http.DefaultTransport),21 }22 resp, err := client.Do(req)23 if err != nil {24 fmt.Println(err)25 } else {26 fmt.Println(resp.Status)27 }28}29import (30func main() {31 sensor := instana.NewSensor("my-service")32 tracer := instahttp.NewTracer(sensor)33 client := &http.Client{34 Transport: tracer.Transport(http.DefaultTransport),35 }

Full Screen

Full Screen

TestTracer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 tracer, err := apm.NewTracer("my-service", "1.0.0")4 if err != nil {5 panic(err)6 }7 client := &http.Client{8 Transport: apmhttp.WrapRoundTripper(http.DefaultTransport),9 }10 if err != nil {11 panic(err)12 }13 res, err := client.Do(req)14 if err != nil {15 panic(err)16 }17 fmt.Println(res.Status)18}

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