| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package trace // import "go.opentelemetry.io/otel/trace" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/stretchr/testify/assert" |
| 11 |
) |
| 12 |
|
| 13 |
type testSpan struct { |
| 14 |
noopSpan |
| 15 |
|
| 16 |
ID byte |
| 17 |
Remote bool |
| 18 |
} |
| 19 |
|
| 20 |
func (s testSpan) SpanContext() SpanContext { |
| 21 |
return SpanContext{ |
| 22 |
traceID: [16]byte{1}, |
| 23 |
spanID: [8]byte{s.ID}, |
| 24 |
remote: s.Remote, |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
var ( |
| 29 |
emptySpan = noopSpan{} |
| 30 |
localSpan = testSpan{ID: 1, Remote: false} |
| 31 |
remoteSpan = testSpan{ID: 1, Remote: true} |
| 32 |
wrappedSpan = nonRecordingSpan{sc: remoteSpan.SpanContext()} |
| 33 |
) |
| 34 |
|
| 35 |
func TestSpanFromContext(t *testing.T) { |
| 36 |
testCases := []struct { |
| 37 |
name string |
| 38 |
context context.Context |
| 39 |
expectedSpan Span |
| 40 |
}{ |
| 41 |
{ |
| 42 |
name: "empty context", |
| 43 |
context: nil, |
| 44 |
expectedSpan: emptySpan, |
| 45 |
}, |
| 46 |
{ |
| 47 |
name: "background context", |
| 48 |
context: t.Context(), |
| 49 |
expectedSpan: emptySpan, |
| 50 |
}, |
| 51 |
{ |
| 52 |
name: "local span", |
| 53 |
context: ContextWithSpan(t.Context(), localSpan), |
| 54 |
expectedSpan: localSpan, |
| 55 |
}, |
| 56 |
{ |
| 57 |
name: "remote span", |
| 58 |
context: ContextWithSpan(t.Context(), remoteSpan), |
| 59 |
expectedSpan: remoteSpan, |
| 60 |
}, |
| 61 |
{ |
| 62 |
name: "wrapped remote span", |
| 63 |
context: ContextWithRemoteSpanContext(t.Context(), remoteSpan.SpanContext()), |
| 64 |
expectedSpan: wrappedSpan, |
| 65 |
}, |
| 66 |
{ |
| 67 |
name: "wrapped local span becomes remote", |
| 68 |
context: ContextWithRemoteSpanContext(t.Context(), localSpan.SpanContext()), |
| 69 |
expectedSpan: wrappedSpan, |
| 70 |
}, |
| 71 |
} |
| 72 |
|
| 73 |
for _, tc := range testCases { |
| 74 |
t.Run(tc.name, func(t *testing.T) { |
| 75 |
assert.Equal(t, tc.expectedSpan, SpanFromContext(tc.context)) |
| 76 |
|
| 77 |
// Ensure SpanContextFromContext is just |
| 78 |
// SpanFromContext(…).SpanContext(). |
| 79 |
assert.Equal(t, tc.expectedSpan.SpanContext(), SpanContextFromContext(tc.context)) |
| 80 |
|
| 81 |
// Check that SpanFromContext does not produce any heap allocation. |
| 82 |
assert.Equal(t, 0.0, testing.AllocsPerRun(5, func() { |
| 83 |
SpanFromContext(tc.context) |
| 84 |
}), "SpanFromContext allocs") |
| 85 |
|
| 86 |
// Check that SpanContextFromContext does not produce any heap allocation. |
| 87 |
assert.Equal(t, 0.0, testing.AllocsPerRun(5, func() { |
| 88 |
SpanContextFromContext(tc.context) |
| 89 |
}), "SpanContextFromContext allocs") |
| 90 |
}) |
| 91 |
} |
| 92 |
} |