...

Source file src/github.com/go-kit/kit/tracing/opentracing/grpc_test.go

Documentation: github.com/go-kit/kit/tracing/opentracing

     1  package opentracing_test
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/opentracing/opentracing-go"
     8  	"github.com/opentracing/opentracing-go/mocktracer"
     9  	"google.golang.org/grpc/metadata"
    10  
    11  	kitot "github.com/go-kit/kit/tracing/opentracing"
    12  	"github.com/go-kit/log"
    13  )
    14  
    15  func TestTraceGRPCRequestRoundtrip(t *testing.T) {
    16  	logger := log.NewNopLogger()
    17  	tracer := mocktracer.New()
    18  
    19  	// Initialize the ctx with a Span to inject.
    20  	beforeSpan := tracer.StartSpan("to_inject").(*mocktracer.MockSpan)
    21  	defer beforeSpan.Finish()
    22  	beforeSpan.SetBaggageItem("baggage", "check")
    23  	beforeCtx := opentracing.ContextWithSpan(context.Background(), beforeSpan)
    24  
    25  	toGRPCFunc := kitot.ContextToGRPC(tracer, logger)
    26  	md := metadata.Pairs()
    27  	// Call the RequestFunc.
    28  	afterCtx := toGRPCFunc(beforeCtx, &md)
    29  
    30  	// The Span should not have changed.
    31  	afterSpan := opentracing.SpanFromContext(afterCtx)
    32  	if beforeSpan != afterSpan {
    33  		t.Error("Should not swap in a new span")
    34  	}
    35  
    36  	// No spans should have finished yet.
    37  	finishedSpans := tracer.FinishedSpans()
    38  	if want, have := 0, len(finishedSpans); want != have {
    39  		t.Errorf("Want %v span(s), found %v", want, have)
    40  	}
    41  
    42  	// Use GRPCToContext to verify that we can join with the trace given MD.
    43  	fromGRPCFunc := kitot.GRPCToContext(tracer, "joined", logger)
    44  	joinCtx := fromGRPCFunc(afterCtx, md)
    45  	joinedSpan := opentracing.SpanFromContext(joinCtx).(*mocktracer.MockSpan)
    46  
    47  	joinedContext := joinedSpan.Context().(mocktracer.MockSpanContext)
    48  	beforeContext := beforeSpan.Context().(mocktracer.MockSpanContext)
    49  
    50  	if joinedContext.SpanID == beforeContext.SpanID {
    51  		t.Error("SpanID should have changed", joinedContext.SpanID, beforeContext.SpanID)
    52  	}
    53  
    54  	// Check that the parent/child relationship is as expected for the joined span.
    55  	if want, have := beforeContext.SpanID, joinedSpan.ParentID; want != have {
    56  		t.Errorf("Want ParentID %q, have %q", want, have)
    57  	}
    58  	if want, have := "joined", joinedSpan.OperationName; want != have {
    59  		t.Errorf("Want %q, have %q", want, have)
    60  	}
    61  	if want, have := "check", joinedSpan.BaggageItem("baggage"); want != have {
    62  		t.Errorf("Want %q, have %q", want, have)
    63  	}
    64  }
    65  

View as plain text