context_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package trace // import "go.opentelemetry.io/otel/trace"
  15. import (
  16. "context"
  17. "testing"
  18. "github.com/stretchr/testify/assert"
  19. )
  20. type testSpan struct {
  21. noopSpan
  22. ID byte
  23. Remote bool
  24. }
  25. func (s testSpan) SpanContext() SpanContext {
  26. return SpanContext{
  27. traceID: [16]byte{1},
  28. spanID: [8]byte{s.ID},
  29. remote: s.Remote,
  30. }
  31. }
  32. var (
  33. emptySpan = noopSpan{}
  34. localSpan = testSpan{ID: 1, Remote: false}
  35. remoteSpan = testSpan{ID: 1, Remote: true}
  36. wrappedSpan = nonRecordingSpan{sc: remoteSpan.SpanContext()}
  37. )
  38. func TestSpanFromContext(t *testing.T) {
  39. testCases := []struct {
  40. name string
  41. context context.Context
  42. expectedSpan Span
  43. }{
  44. {
  45. name: "empty context",
  46. context: nil,
  47. expectedSpan: emptySpan,
  48. },
  49. {
  50. name: "background context",
  51. context: context.Background(),
  52. expectedSpan: emptySpan,
  53. },
  54. {
  55. name: "local span",
  56. context: ContextWithSpan(context.Background(), localSpan),
  57. expectedSpan: localSpan,
  58. },
  59. {
  60. name: "remote span",
  61. context: ContextWithSpan(context.Background(), remoteSpan),
  62. expectedSpan: remoteSpan,
  63. },
  64. {
  65. name: "wrapped remote span",
  66. context: ContextWithRemoteSpanContext(context.Background(), remoteSpan.SpanContext()),
  67. expectedSpan: wrappedSpan,
  68. },
  69. {
  70. name: "wrapped local span becomes remote",
  71. context: ContextWithRemoteSpanContext(context.Background(), localSpan.SpanContext()),
  72. expectedSpan: wrappedSpan,
  73. },
  74. }
  75. for _, tc := range testCases {
  76. t.Run(tc.name, func(t *testing.T) {
  77. assert.Equal(t, tc.expectedSpan, SpanFromContext(tc.context))
  78. // Ensure SpanContextFromContext is just
  79. // SpanFromContext(…).SpanContext().
  80. assert.Equal(t, tc.expectedSpan.SpanContext(), SpanContextFromContext(tc.context))
  81. })
  82. }
  83. }