...

Source file src/go.opencensus.io/plugin/ochttp/propagation_test.go

Documentation: go.opencensus.io/plugin/ochttp

     1  // Copyright 2018, OpenCensus Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package ochttp
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"net/http"
    22  	"net/http/httptest"
    23  	"testing"
    24  
    25  	"go.opencensus.io/plugin/ochttp/propagation/b3"
    26  	"go.opencensus.io/plugin/ochttp/propagation/tracecontext"
    27  	"go.opencensus.io/trace"
    28  	"go.opencensus.io/trace/propagation"
    29  )
    30  
    31  func TestRoundTripAllFormats(t *testing.T) {
    32  	// TODO: test combinations of different formats for chains of calls
    33  	formats := []propagation.HTTPFormat{
    34  		&b3.HTTPFormat{},
    35  		&tracecontext.HTTPFormat{},
    36  	}
    37  
    38  	ctx := context.Background()
    39  	ctx, span := trace.StartSpan(ctx, "test", trace.WithSampler(trace.AlwaysSample()))
    40  	sc := span.SpanContext()
    41  	wantStr := fmt.Sprintf("trace_id=%x, span_id=%x, options=%d", sc.TraceID, sc.SpanID, sc.TraceOptions)
    42  	defer span.End()
    43  
    44  	for _, format := range formats {
    45  		srv := httptest.NewServer(http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
    46  			sc, ok := format.SpanContextFromRequest(req)
    47  			if !ok {
    48  				resp.WriteHeader(http.StatusBadRequest)
    49  			}
    50  			fmt.Fprintf(resp, "trace_id=%x, span_id=%x, options=%d", sc.TraceID, sc.SpanID, sc.TraceOptions)
    51  		}))
    52  		req, err := http.NewRequest("GET", srv.URL, nil)
    53  		if err != nil {
    54  			t.Fatal(err)
    55  		}
    56  		format.SpanContextToRequest(span.SpanContext(), req)
    57  		resp, err := http.DefaultClient.Do(req)
    58  		if err != nil {
    59  			t.Fatal(err)
    60  		}
    61  		if resp.StatusCode != 200 {
    62  			t.Fatal(resp.Status)
    63  		}
    64  		body, err := ioutil.ReadAll(resp.Body)
    65  		if err != nil {
    66  			t.Fatal(err)
    67  		}
    68  		resp.Body.Close()
    69  		if got, want := string(body), wantStr; got != want {
    70  			t.Errorf("%s; want %s", got, want)
    71  		}
    72  		srv.Close()
    73  	}
    74  }
    75  

View as plain text