gocontext_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package opentracing
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestContextWithSpan(t *testing.T) {
  9. span := &noopSpan{}
  10. ctx := ContextWithSpan(context.Background(), span)
  11. span2 := SpanFromContext(ctx)
  12. if span != span2 {
  13. t.Errorf("Not the same span returned from context, expected=%+v, actual=%+v", span, span2)
  14. }
  15. ctx = context.Background()
  16. span2 = SpanFromContext(ctx)
  17. if span2 != nil {
  18. t.Errorf("Expected nil span, found %+v", span2)
  19. }
  20. ctx = ContextWithSpan(ctx, span)
  21. span2 = SpanFromContext(ctx)
  22. if span != span2 {
  23. t.Errorf("Not the same span returned from context, expected=%+v, actual=%+v", span, span2)
  24. }
  25. }
  26. func TestStartSpanFromContext(t *testing.T) {
  27. testTracer := testTracer{}
  28. // Test the case where there *is* a Span in the Context.
  29. {
  30. parentSpan := &testSpan{}
  31. parentCtx := ContextWithSpan(context.Background(), parentSpan)
  32. childSpan, childCtx := StartSpanFromContextWithTracer(parentCtx, testTracer, "child")
  33. if !childSpan.Context().(testSpanContext).HasParent {
  34. t.Errorf("Failed to find parent: %v", childSpan)
  35. }
  36. if !childSpan.(testSpan).Equal(SpanFromContext(childCtx)) {
  37. t.Errorf("Unable to find child span in context: %v", childCtx)
  38. }
  39. }
  40. // Test the case where there *is not* a Span in the Context.
  41. {
  42. emptyCtx := context.Background()
  43. childSpan, childCtx := StartSpanFromContextWithTracer(emptyCtx, testTracer, "child")
  44. if childSpan.Context().(testSpanContext).HasParent {
  45. t.Errorf("Should not have found parent: %v", childSpan)
  46. }
  47. if !childSpan.(testSpan).Equal(SpanFromContext(childCtx)) {
  48. t.Errorf("Unable to find child span in context: %v", childCtx)
  49. }
  50. }
  51. }
  52. func TestStartSpanFromContextOptions(t *testing.T) {
  53. testTracer := testTracer{}
  54. // Test options are passed to tracer
  55. startTime := time.Now().Add(-10 * time.Second) // ten seconds ago
  56. span, ctx := StartSpanFromContextWithTracer(
  57. context.Background(), testTracer, "parent", StartTime(startTime), Tag{"component", "test"})
  58. assert.Equal(t, "test", span.(testSpan).Tags["component"])
  59. assert.Equal(t, startTime, span.(testSpan).StartTime)
  60. // Test it also works for a child span
  61. childStartTime := startTime.Add(3 * time.Second)
  62. childSpan, _ := StartSpanFromContextWithTracer(
  63. ctx, testTracer, "child", StartTime(childStartTime))
  64. assert.Equal(t, childSpan.(testSpan).Tags["component"], nil)
  65. assert.Equal(t, childSpan.(testSpan).StartTime, childStartTime)
  66. }