Debian Codegraph @

exporter/exporterhelper/internal/queuebatch/batch_context_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package queuebatch
5
6 import (
7 "context"
8 "testing"
9
10 "github.com/stretchr/testify/require"
11 "go.opentelemetry.io/otel/trace"
12
13 "go.opentelemetry.io/collector/component/componenttest"
14 )
15
16 type testTimestampKeyType int
17
18 const testTimestampKey testTimestampKeyType = iota
19
20 // mergeCtxFunc corresponds to user specified mergeCtx function in the batcher settings.
21 // This specific merge Context function keeps the greater of timestamps from two contexts.
22 func mergeCtxFunc(ctx1, ctx2 context.Context) context.Context {
23 timestamp1 := ctx1.Value(testTimestampKey)
24 timestamp2 := ctx2.Value(testTimestampKey)
25 if timestamp1 != nil && timestamp2 != nil {
26 if timestamp1.(int) > timestamp2.(int) {
27 return context.WithValue(context.Background(), testTimestampKey, timestamp1)
28 }
29 return context.WithValue(context.Background(), testTimestampKey, timestamp2)
30 }
31 if timestamp1 != nil {
32 return context.WithValue(context.Background(), testTimestampKey, timestamp1)
33 }
34 return context.WithValue(context.Background(), testTimestampKey, timestamp2)
35 }
36
37 // mergeContextHelper performs the same operation done during batching.
38 func mergeContextHelper(ctx1, ctx2 context.Context) context.Context {
39 return contextWithMergedLinks(mergeCtxFunc(ctx1, ctx2), ctx1, ctx2)
40 }
41
42 func TestBatchContextLink(t *testing.T) {
43 tracerProvider := componenttest.NewTelemetry().NewTelemetrySettings().TracerProvider
44 tracer := tracerProvider.Tracer("go.opentelemetry.io/collector/exporter/exporterhelper")
45
46 ctx1 := context.Background()
47
48 ctx2, span2 := tracer.Start(ctx1, "span2")
49 defer span2.End()
50
51 ctx3, span3 := tracer.Start(ctx1, "span3")
52 defer span3.End()
53
54 ctx4, span4 := tracer.Start(ctx1, "span4")
55 defer span4.End()
56
57 batchContext := mergeContextHelper(ctx2, ctx3)
58 batchContext = mergeContextHelper(batchContext, ctx4)
59
60 actualLinks := LinksFromContext(batchContext)
61 require.Len(t, actualLinks, 3)
62 require.Equal(t, trace.SpanContextFromContext(ctx2), actualLinks[0].SpanContext)
63 require.Equal(t, trace.SpanContextFromContext(ctx3), actualLinks[1].SpanContext)
64 require.Equal(t, trace.SpanContextFromContext(ctx4), actualLinks[2].SpanContext)
65 }
66
67 func TestMergedContext_GetValue(t *testing.T) {
68 ctx1 := context.WithValue(context.Background(), testTimestampKey, 1234)
69 ctx2 := context.WithValue(context.Background(), testTimestampKey, 2345)
70 batchContext := mergeContextHelper(ctx1, ctx2)
71 require.Equal(t, 2345, batchContext.Value(testTimestampKey))
72 }