github.com/wangyougui/gf/v2@v2.6.5/net/gtrace/gtrace_z_unit_carrier_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gtrace_test
     8  
     9  import (
    10  	"context"
    11  	"testing"
    12  
    13  	"go.opentelemetry.io/otel"
    14  	"go.opentelemetry.io/otel/trace"
    15  
    16  	"github.com/wangyougui/gf/v2/net/gtrace"
    17  	"github.com/wangyougui/gf/v2/test/gtest"
    18  )
    19  
    20  const (
    21  	traceIDStr = "4bf92f3577b34da6a3ce929d0e0e4736"
    22  	spanIDStr  = "00f067aa0ba902b7"
    23  )
    24  
    25  var (
    26  	traceID = mustTraceIDFromHex(traceIDStr)
    27  	spanID  = mustSpanIDFromHex(spanIDStr)
    28  )
    29  
    30  func mustTraceIDFromHex(s string) (t trace.TraceID) {
    31  	var err error
    32  	t, err = trace.TraceIDFromHex(s)
    33  	if err != nil {
    34  		panic(err)
    35  	}
    36  	return
    37  }
    38  
    39  func mustSpanIDFromHex(s string) (t trace.SpanID) {
    40  	var err error
    41  	t, err = trace.SpanIDFromHex(s)
    42  	if err != nil {
    43  		panic(err)
    44  	}
    45  	return
    46  }
    47  
    48  func TestNewCarrier(t *testing.T) {
    49  	gtest.C(t, func(t *gtest.T) {
    50  		ctx := trace.ContextWithRemoteSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{
    51  			TraceID:    traceID,
    52  			SpanID:     spanID,
    53  			TraceFlags: trace.FlagsSampled,
    54  		}))
    55  		sc := trace.SpanContextFromContext(ctx)
    56  		t.Assert(sc.TraceID().String(), traceID.String())
    57  		t.Assert(sc.SpanID().String(), "00f067aa0ba902b7")
    58  
    59  		ctx, _ = otel.Tracer("").Start(ctx, "inject")
    60  		carrier1 := gtrace.NewCarrier()
    61  		otel.GetTextMapPropagator().Inject(ctx, carrier1)
    62  
    63  		ctx = otel.GetTextMapPropagator().Extract(ctx, carrier1)
    64  		gotSc := trace.SpanContextFromContext(ctx)
    65  		t.Assert(gotSc.TraceID().String(), traceID.String())
    66  		// New span is created internally, so the SpanID is different.
    67  	})
    68  }