...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package internaltest
19
20 import (
21 "context"
22 "fmt"
23 "strconv"
24 "strings"
25 "testing"
26
27 "go.opentelemetry.io/otel/propagation"
28 )
29
30 type ctxKeyType string
31
32 type state struct {
33 Injections uint64
34 Extractions uint64
35 }
36
37 func newState(encoded string) state {
38 if encoded == "" {
39 return state{}
40 }
41 s0, s1, _ := strings.Cut(encoded, ",")
42 injects, _ := strconv.ParseUint(s0, 10, 64)
43 extracts, _ := strconv.ParseUint(s1, 10, 64)
44 return state{
45 Injections: injects,
46 Extractions: extracts,
47 }
48 }
49
50 func (s state) String() string {
51 return fmt.Sprintf("%d,%d", s.Injections, s.Extractions)
52 }
53
54
55 type TextMapPropagator struct {
56 name string
57 ctxKey ctxKeyType
58 }
59
60 var _ propagation.TextMapPropagator = (*TextMapPropagator)(nil)
61
62
63
64 func NewTextMapPropagator(name string) *TextMapPropagator {
65 return &TextMapPropagator{name: name, ctxKey: ctxKeyType(name)}
66 }
67
68 func (p *TextMapPropagator) stateFromContext(ctx context.Context) state {
69 if v := ctx.Value(p.ctxKey); v != nil {
70 if s, ok := v.(state); ok {
71 return s
72 }
73 }
74 return state{}
75 }
76
77 func (p *TextMapPropagator) stateFromCarrier(carrier propagation.TextMapCarrier) state {
78 return newState(carrier.Get(p.name))
79 }
80
81
82 func (p *TextMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
83 s := p.stateFromContext(ctx)
84 s.Injections++
85 carrier.Set(p.name, s.String())
86 }
87
88
89 func (p *TextMapPropagator) InjectedN(t *testing.T, carrier *TextMapCarrier, n int) bool {
90 if actual := p.stateFromCarrier(carrier).Injections; actual != uint64(n) {
91 t.Errorf("TextMapPropagator{%q} injected %d times, not %d", p.name, actual, n)
92 return false
93 }
94 return true
95 }
96
97
98 func (p *TextMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
99 s := p.stateFromCarrier(carrier)
100 s.Extractions++
101 return context.WithValue(ctx, p.ctxKey, s)
102 }
103
104
105
106 func (p *TextMapPropagator) ExtractedN(t *testing.T, ctx context.Context, n int) bool {
107 if actual := p.stateFromContext(ctx).Extractions; actual != uint64(n) {
108 t.Errorf("TextMapPropagator{%q} extracted %d time, not %d", p.name, actual, n)
109 return false
110 }
111 return true
112 }
113
114
115 func (p *TextMapPropagator) Fields() []string { return []string{p.name} }
116
View as plain text