Debian Codegraph @

bridge/opencensus/internal/otel2oc/span_context_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otel2oc
5
6 import (
7 "testing"
8
9 "github.com/stretchr/testify/assert"
10 "go.opencensus.io/plugin/ochttp/propagation/tracecontext"
11 octrace "go.opencensus.io/trace"
12 "go.opencensus.io/trace/tracestate"
13
14 "go.opentelemetry.io/otel/bridge/opencensus/internal/oc2otel"
15 "go.opentelemetry.io/otel/trace"
16 )
17
18 func TestSpanContextConversion(t *testing.T) {
19 tsOc, _ := tracestate.New(nil,
20 // Oc has a reverse order of TraceState entries compared to OTel
21 tracestate.Entry{Key: "key1", Value: "value1"},
22 tracestate.Entry{Key: "key2", Value: "value2"},
23 )
24 tsOtel := trace.TraceState{}
25 tsOtel, _ = tsOtel.Insert("key2", "value2")
26 tsOtel, _ = tsOtel.Insert("key1", "value1")
27
28 httpFormatOc := &tracecontext.HTTPFormat{}
29
30 for _, tc := range []struct {
31 description string
32 input trace.SpanContext
33 expected octrace.SpanContext
34 expectedTracestate string
35 }{
36 {
37 description: "empty",
38 },
39 {
40 description: "sampled",
41 input: trace.NewSpanContext(trace.SpanContextConfig{
42 TraceID: trace.TraceID([16]byte{1}),
43 SpanID: trace.SpanID([8]byte{2}),
44 TraceFlags: trace.FlagsSampled,
45 }),
46 expected: octrace.SpanContext{
47 TraceID: octrace.TraceID([16]byte{1}),
48 SpanID: octrace.SpanID([8]byte{2}),
49 TraceOptions: octrace.TraceOptions(0x1),
50 },
51 },
52 {
53 description: "not sampled",
54 input: trace.NewSpanContext(trace.SpanContextConfig{
55 TraceID: trace.TraceID([16]byte{1}),
56 SpanID: trace.SpanID([8]byte{2}),
57 }),
58 expected: octrace.SpanContext{
59 TraceID: octrace.TraceID([16]byte{1}),
60 SpanID: octrace.SpanID([8]byte{2}),
61 TraceOptions: octrace.TraceOptions(0),
62 },
63 },
64 {
65 description: "trace state should be propagated",
66 input: trace.NewSpanContext(trace.SpanContextConfig{
67 TraceID: trace.TraceID([16]byte{1}),
68 SpanID: trace.SpanID([8]byte{2}),
69 TraceState: tsOtel,
70 }),
71 expected: octrace.SpanContext{
72 TraceID: octrace.TraceID([16]byte{1}),
73 SpanID: octrace.SpanID([8]byte{2}),
74 TraceOptions: octrace.TraceOptions(0),
75 Tracestate: tsOc,
76 },
77 expectedTracestate: "key1=value1,key2=value2",
78 },
79 } {
80 t.Run(tc.description, func(t *testing.T) {
81 output := SpanContext(tc.input)
82 assert.Equal(t, tc.expected, output)
83
84 // Ensure the otel tracestate and oc tracestate has the same header output
85 _, ts := httpFormatOc.SpanContextToHeaders(tc.expected)
86 assert.Equal(t, tc.expectedTracestate, ts)
87 assert.Equal(t, tc.expectedTracestate, tc.input.TraceState().String())
88
89 // The reverse conversion should yield the original input
90 input := oc2otel.SpanContext(output)
91 assert.Equal(t, tc.input, input)
92 })
93 }
94 }