-
Notifications
You must be signed in to change notification settings - Fork 696
/
Copy pathmock_textmap.py
104 lines (88 loc) · 2.83 KB
/
mock_textmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import typing
from opentelemetry import trace
from opentelemetry.context import Context
from opentelemetry.propagators.textmap import (
CarrierT,
Getter,
Setter,
TextMapPropagator,
default_getter,
default_setter,
)
class NOOPTextMapPropagator(TextMapPropagator):
"""A propagator that does not extract nor inject.
This class is useful for catching edge cases assuming
a SpanContext will always be present.
"""
def extract(
self,
carrier: CarrierT,
context: typing.Optional[Context] = None,
getter: Getter = default_getter,
) -> Context:
return Context()
def inject(
self,
carrier: CarrierT,
context: typing.Optional[Context] = None,
setter: Setter = default_setter,
) -> None:
return None
@property
def fields(self):
return set()
class MockTextMapPropagator(TextMapPropagator):
"""Mock propagator for testing purposes."""
TRACE_ID_KEY = "mock-traceid"
SPAN_ID_KEY = "mock-spanid"
def extract(
self,
carrier: CarrierT,
context: typing.Optional[Context] = None,
getter: Getter = default_getter,
) -> Context:
if context is None:
context = Context()
trace_id_list = getter.get(carrier, self.TRACE_ID_KEY)
span_id_list = getter.get(carrier, self.SPAN_ID_KEY)
if not trace_id_list or not span_id_list:
return context
return trace.set_span_in_context(
trace.NonRecordingSpan(
trace.SpanContext(
trace_id=int(trace_id_list[0]),
span_id=int(span_id_list[0]),
is_remote=True,
)
),
context,
)
def inject(
self,
carrier: CarrierT,
context: typing.Optional[Context] = None,
setter: Setter = default_setter,
) -> None:
span = trace.get_current_span(context)
setter.set(
carrier, self.TRACE_ID_KEY, str(span.get_span_context().trace_id)
)
setter.set(
carrier, self.SPAN_ID_KEY, str(span.get_span_context().span_id)
)
@property
def fields(self):
return {self.TRACE_ID_KEY, self.SPAN_ID_KEY}