1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package tracetest
16
17 import (
18 "context"
19 "sync"
20 "testing"
21
22 "github.com/stretchr/testify/assert"
23
24 sdktrace "go.opentelemetry.io/otel/sdk/trace"
25 )
26
27 type rwSpan struct {
28 sdktrace.ReadWriteSpan
29 }
30
31 func TestSpanRecorderOnStartAppends(t *testing.T) {
32 s0, s1 := new(rwSpan), new(rwSpan)
33 ctx := context.Background()
34 sr := new(SpanRecorder)
35
36 assert.Len(t, sr.started, 0)
37 sr.OnStart(ctx, s0)
38 assert.Len(t, sr.started, 1)
39 sr.OnStart(ctx, s1)
40 assert.Len(t, sr.started, 2)
41
42
43 started := sr.Started()
44 assert.Same(t, s0, started[0])
45 assert.Same(t, s1, started[1])
46 }
47
48 type roSpan struct {
49 sdktrace.ReadOnlySpan
50 }
51
52 func TestSpanRecorderOnEndAppends(t *testing.T) {
53 s0, s1 := new(roSpan), new(roSpan)
54 sr := new(SpanRecorder)
55
56 assert.Len(t, sr.ended, 0)
57 sr.OnEnd(s0)
58 assert.Len(t, sr.ended, 1)
59 sr.OnEnd(s1)
60 assert.Len(t, sr.ended, 2)
61
62
63 ended := sr.Ended()
64 assert.Same(t, s0, ended[0])
65 assert.Same(t, s1, ended[1])
66 }
67
68 func TestSpanRecorderShutdownNoError(t *testing.T) {
69 ctx := context.Background()
70 assert.NoError(t, new(SpanRecorder).Shutdown(ctx))
71
72 var c context.CancelFunc
73 ctx, c = context.WithCancel(ctx)
74 c()
75 assert.NoError(t, new(SpanRecorder).Shutdown(ctx))
76 }
77
78 func TestSpanRecorderForceFlushNoError(t *testing.T) {
79 ctx := context.Background()
80 assert.NoError(t, new(SpanRecorder).ForceFlush(ctx))
81
82 var c context.CancelFunc
83 ctx, c = context.WithCancel(ctx)
84 c()
85 assert.NoError(t, new(SpanRecorder).ForceFlush(ctx))
86 }
87
88 func runConcurrently(funcs ...func()) {
89 var wg sync.WaitGroup
90
91 for _, f := range funcs {
92 wg.Add(1)
93 go func(f func()) {
94 f()
95 wg.Done()
96 }(f)
97 }
98
99 wg.Wait()
100 }
101
102 func TestEndingConcurrentSafe(t *testing.T) {
103 sr := NewSpanRecorder()
104
105 runConcurrently(
106 func() { sr.OnEnd(new(roSpan)) },
107 func() { sr.OnEnd(new(roSpan)) },
108 func() { sr.Ended() },
109 )
110
111 assert.Len(t, sr.Ended(), 2)
112 }
113
114 func TestStartingConcurrentSafe(t *testing.T) {
115 sr := NewSpanRecorder()
116
117 ctx := context.Background()
118 runConcurrently(
119 func() { sr.OnStart(ctx, new(rwSpan)) },
120 func() { sr.OnStart(ctx, new(rwSpan)) },
121 func() { sr.Started() },
122 )
123
124 assert.Len(t, sr.Started(), 2)
125 }
126
View as plain text