github.com/songzhibin97/gkit@v1.2.13/trace/middle_test.go (about) 1 package trace 2 3 import ( 4 "context" 5 "testing" 6 7 "go.opentelemetry.io/otel/propagation" 8 sdk "go.opentelemetry.io/otel/sdk/trace" 9 "go.opentelemetry.io/otel/trace" 10 ) 11 12 var _ Transporter = &Transport{} 13 14 type _Transport struct { 15 kind Kind 16 endpoint string 17 operation string 18 header headerCarrier 19 } 20 21 func (tr *_Transport) Kind() Kind { return tr.kind } 22 func (tr *_Transport) Endpoint() string { return tr.endpoint } 23 func (tr *_Transport) Operation() string { return tr.operation } 24 func (tr *_Transport) RequestHeader() Header { return tr.header } 25 func (tr *_Transport) ResponseHeader() Header { return tr.header } 26 27 func TestTrace(t *testing.T) { 28 carrier := headerCarrier{} 29 tp := sdk.NewTracerProvider(sdk.WithSampler(sdk.TraceIDRatioBased(0))) 30 31 // caller use Inject 32 tracer := NewTracer(trace.SpanKindClient, WithTracerProvider(tp), WithPropagator(propagation.NewCompositeTextMapPropagator(propagation.Baggage{}, propagation.TraceContext{}))) 33 ts := &_Transport{kind: KindHTTP, header: carrier} 34 35 ctx, aboveSpan := tracer.Start(NewClientTransportContext(context.Background(), ts), ts.Operation(), ts.RequestHeader()) 36 defer tracer.End(ctx, aboveSpan, nil, nil) 37 38 // server use Extract fetch traceInfo from carrier 39 tracer = NewTracer(trace.SpanKindServer, WithPropagator(propagation.NewCompositeTextMapPropagator(propagation.Baggage{}, propagation.TraceContext{}))) 40 ts = &_Transport{kind: KindHTTP, header: carrier} 41 42 ctx, span := tracer.Start(NewServerTransportContext(ctx, ts), ts.Operation(), ts.RequestHeader()) 43 defer tracer.End(ctx, span, nil, nil) 44 45 if aboveSpan.SpanContext().TraceID() != span.SpanContext().TraceID() { 46 t.Fatalf("TraceID failed to deliver") 47 } 48 49 if v, ok := FromClientTransportContext(ctx); !ok || len(v.RequestHeader().Keys()) == 0 { 50 t.Fatalf("traceHeader failed to deliver") 51 } else { 52 t.Log(v) 53 t.Log(v.RequestHeader().Keys()) 54 } 55 }