forked from open-telemetry/opentelemetry-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_shim.py
579 lines (445 loc) · 21 KB
/
test_shim.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# Copyright 2019, 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.
# TODO: make pylint use 3p opentracing module for type inference
# pylint:disable=no-member
import time
import typing
from unittest import TestCase
import opentracing
import opentelemetry.ext.opentracing_shim as opentracingshim
from opentelemetry import propagators, trace
from opentelemetry.context import Context
from opentelemetry.ext.opentracing_shim import util
from opentelemetry.trace.propagation import (
get_span_from_context,
set_span_in_context,
)
from opentelemetry.trace.propagation.httptextformat import (
Getter,
HTTPTextFormat,
HTTPTextFormatT,
Setter,
)
class TestShim(TestCase):
# pylint: disable=too-many-public-methods
def setUp(self):
"""Create an OpenTelemetry tracer and a shim before every test case."""
self.shim = opentracingshim.create_tracer(trace.get_tracer_provider())
@classmethod
def setUpClass(cls):
# Save current propagator to be restored on teardown.
cls._previous_propagator = propagators.get_global_httptextformat()
# Set mock propagator for testing.
propagators.set_global_httptextformat(MockHTTPTextFormat())
@classmethod
def tearDownClass(cls):
# Restore previous propagator.
propagators.set_global_httptextformat(cls._previous_propagator)
def test_shim_type(self):
# Verify shim is an OpenTracing tracer.
self.assertIsInstance(self.shim, opentracing.Tracer)
def test_start_active_span(self):
"""Test span creation and activation using `start_active_span()`."""
with self.shim.start_active_span("TestSpan") as scope:
# Verify correct type of Scope and Span objects.
self.assertIsInstance(scope, opentracing.Scope)
self.assertIsInstance(scope.span, opentracing.Span)
# Verify span is started.
self.assertIsNotNone(scope.span.unwrap().start_time)
# Verify span is active.
self.assertEqual(
self.shim.active_span.context.unwrap(),
scope.span.context.unwrap(),
)
# TODO: We can't check for equality of self.shim.active_span and
# scope.span because the same OpenTelemetry span is returned inside
# different SpanShim objects. A possible solution is described
# here:
# https://github.com/open-telemetry/opentelemetry-python/issues/161#issuecomment-534136274
# Verify span has ended.
self.assertIsNotNone(scope.span.unwrap().end_time)
# Verify no span is active.
self.assertIsNone(self.shim.active_span)
def test_start_span(self):
"""Test span creation using `start_span()`."""
with self.shim.start_span("TestSpan") as span:
# Verify correct type of Span object.
self.assertIsInstance(span, opentracing.Span)
# Verify span is started.
self.assertIsNotNone(span.unwrap().start_time)
# Verify `start_span()` does NOT make the span active.
self.assertIsNone(self.shim.active_span)
# Verify span has ended.
self.assertIsNotNone(span.unwrap().end_time)
def test_start_span_no_contextmanager(self):
"""Test `start_span()` without a `with` statement."""
span = self.shim.start_span("TestSpan")
# Verify span is started.
self.assertIsNotNone(span.unwrap().start_time)
# Verify `start_span()` does NOT make the span active.
self.assertIsNone(self.shim.active_span)
span.finish()
def test_explicit_span_finish(self):
"""Test `finish()` method on `Span` objects."""
span = self.shim.start_span("TestSpan")
# Verify span hasn't ended.
self.assertIsNone(span.unwrap().end_time)
span.finish()
# Verify span has ended.
self.assertIsNotNone(span.unwrap().end_time)
def test_explicit_start_time(self):
"""Test `start_time` argument."""
now = time.time()
with self.shim.start_active_span("TestSpan", start_time=now) as scope:
result = util.time_seconds_from_ns(scope.span.unwrap().start_time)
# Tolerate inaccuracies of less than a microsecond. See Note:
# https://open-telemetry.github.io/opentelemetry-python/opentelemetry.ext.opentracing_shim.html
# TODO: This seems to work consistently, but we should find out the
# biggest possible loss of precision.
self.assertAlmostEqual(result, now, places=6)
def test_explicit_end_time(self):
"""Test `end_time` argument of `finish()` method."""
span = self.shim.start_span("TestSpan")
now = time.time()
span.finish(now)
end_time = util.time_seconds_from_ns(span.unwrap().end_time)
# Tolerate inaccuracies of less than a microsecond. See Note:
# https://open-telemetry.github.io/opentelemetry-python/opentelemetry.ext.opentracing_shim.html
# TODO: This seems to work consistently, but we should find out the
# biggest possible loss of precision.
self.assertAlmostEqual(end_time, now, places=6)
def test_explicit_span_activation(self):
"""Test manual activation and deactivation of a span."""
span = self.shim.start_span("TestSpan")
# Verify no span is currently active.
self.assertIsNone(self.shim.active_span)
with self.shim.scope_manager.activate(
span, finish_on_close=True
) as scope:
# Verify span is active.
self.assertEqual(
self.shim.active_span.context.unwrap(),
scope.span.context.unwrap(),
)
# Verify no span is active.
self.assertIsNone(self.shim.active_span)
def test_start_active_span_finish_on_close(self):
"""Test `finish_on_close` argument of `start_active_span()`."""
with self.shim.start_active_span(
"TestSpan", finish_on_close=True
) as scope:
# Verify span hasn't ended.
self.assertIsNone(scope.span.unwrap().end_time)
# Verify span has ended.
self.assertIsNotNone(scope.span.unwrap().end_time)
with self.shim.start_active_span(
"TestSpan", finish_on_close=False
) as scope:
# Verify span hasn't ended.
self.assertIsNone(scope.span.unwrap().end_time)
# Verify span hasn't ended after scope had been closed.
self.assertIsNone(scope.span.unwrap().end_time)
scope.span.finish()
def test_activate_finish_on_close(self):
"""Test `finish_on_close` argument of `activate()`."""
span = self.shim.start_span("TestSpan")
with self.shim.scope_manager.activate(
span, finish_on_close=True
) as scope:
# Verify span is active.
self.assertEqual(
self.shim.active_span.context.unwrap(),
scope.span.context.unwrap(),
)
# Verify span has ended.
self.assertIsNotNone(span.unwrap().end_time)
span = self.shim.start_span("TestSpan")
with self.shim.scope_manager.activate(
span, finish_on_close=False
) as scope:
# Verify span is active.
self.assertEqual(
self.shim.active_span.context.unwrap(),
scope.span.context.unwrap(),
)
# Verify span hasn't ended.
self.assertIsNone(span.unwrap().end_time)
span.finish()
def test_explicit_scope_close(self):
"""Test `close()` method on `ScopeShim`."""
with self.shim.start_active_span("ParentSpan") as parent:
# Verify parent span is active.
self.assertEqual(
self.shim.active_span.context.unwrap(),
parent.span.context.unwrap(),
)
child = self.shim.start_active_span("ChildSpan")
# Verify child span is active.
self.assertEqual(
self.shim.active_span.context.unwrap(),
child.span.context.unwrap(),
)
# Verify child span hasn't ended.
self.assertIsNone(child.span.unwrap().end_time)
child.close()
# Verify child span has ended.
self.assertIsNotNone(child.span.unwrap().end_time)
# Verify parent span becomes active again.
self.assertEqual(
self.shim.active_span.context.unwrap(),
parent.span.context.unwrap(),
)
def test_parent_child_implicit(self):
"""Test parent-child relationship and activation/deactivation of spans
without specifying the parent span upon creation.
"""
with self.shim.start_active_span("ParentSpan") as parent:
# Verify parent span is the active span.
self.assertEqual(
self.shim.active_span.context.unwrap(),
parent.span.context.unwrap(),
)
with self.shim.start_active_span("ChildSpan") as child:
# Verify child span is the active span.
self.assertEqual(
self.shim.active_span.context.unwrap(),
child.span.context.unwrap(),
)
# Verify parent-child relationship.
parent_trace_id = parent.span.unwrap().get_context().trace_id
child_trace_id = child.span.unwrap().get_context().trace_id
self.assertEqual(parent_trace_id, child_trace_id)
self.assertEqual(
child.span.unwrap().parent, parent.span.unwrap()
)
# Verify parent span becomes the active span again.
self.assertEqual(
self.shim.active_span.context.unwrap(),
parent.span.context.unwrap()
# TODO: Check equality of the spans themselves rather than
# their context once the SpanShim reconstruction problem has
# been addressed (see previous TODO).
)
# Verify there is no active span.
self.assertIsNone(self.shim.active_span)
def test_parent_child_explicit_span(self):
"""Test parent-child relationship of spans when specifying a `Span`
object as a parent upon creation.
"""
with self.shim.start_span("ParentSpan") as parent:
with self.shim.start_active_span(
"ChildSpan", child_of=parent
) as child:
parent_trace_id = parent.unwrap().get_context().trace_id
child_trace_id = child.span.unwrap().get_context().trace_id
self.assertEqual(child_trace_id, parent_trace_id)
self.assertEqual(child.span.unwrap().parent, parent.unwrap())
with self.shim.start_span("ParentSpan") as parent:
child = self.shim.start_span("ChildSpan", child_of=parent)
parent_trace_id = parent.unwrap().get_context().trace_id
child_trace_id = child.unwrap().get_context().trace_id
self.assertEqual(child_trace_id, parent_trace_id)
self.assertEqual(child.unwrap().parent, parent.unwrap())
child.finish()
def test_parent_child_explicit_span_context(self):
"""Test parent-child relationship of spans when specifying a
`SpanContext` object as a parent upon creation.
"""
with self.shim.start_span("ParentSpan") as parent:
with self.shim.start_active_span(
"ChildSpan", child_of=parent.context
) as child:
parent_trace_id = parent.unwrap().get_context().trace_id
child_trace_id = child.span.unwrap().get_context().trace_id
self.assertEqual(child_trace_id, parent_trace_id)
self.assertEqual(
child.span.unwrap().parent, parent.context.unwrap()
)
with self.shim.start_span("ParentSpan") as parent:
with self.shim.start_span(
"SpanWithContextParent", child_of=parent.context
) as child:
parent_trace_id = parent.unwrap().get_context().trace_id
child_trace_id = child.unwrap().get_context().trace_id
self.assertEqual(child_trace_id, parent_trace_id)
self.assertEqual(
child.unwrap().parent, parent.context.unwrap()
)
def test_references(self):
"""Test span creation using the `references` argument."""
with self.shim.start_span("ParentSpan") as parent:
ref = opentracing.child_of(parent.context)
with self.shim.start_active_span(
"ChildSpan", references=[ref]
) as child:
self.assertEqual(
child.span.unwrap().links[0].context,
parent.context.unwrap(),
)
def test_set_operation_name(self):
"""Test `set_operation_name()` method."""
with self.shim.start_active_span("TestName") as scope:
self.assertEqual(scope.span.unwrap().name, "TestName")
scope.span.set_operation_name("NewName")
self.assertEqual(scope.span.unwrap().name, "NewName")
def test_tags(self):
"""Test tags behavior using the `tags` argument and the `set_tags()`
method.
"""
tags = {"foo": "bar"}
with self.shim.start_active_span("TestSetTag", tags=tags) as scope:
scope.span.set_tag("baz", "qux")
self.assertEqual(scope.span.unwrap().attributes["foo"], "bar")
self.assertEqual(scope.span.unwrap().attributes["baz"], "qux")
def test_span_tracer(self):
"""Test the `tracer` property on `Span` objects."""
with self.shim.start_active_span("TestSpan") as scope:
self.assertEqual(scope.span.tracer, self.shim)
def test_log_kv(self):
"""Test the `log_kv()` method on `Span` objects."""
with self.shim.start_span("TestSpan") as span:
span.log_kv({"foo": "bar"})
self.assertEqual(span.unwrap().events[0].attributes["foo"], "bar")
# Verify timestamp was generated automatically.
self.assertIsNotNone(span.unwrap().events[0].timestamp)
# Test explicit timestamp.
now = time.time()
span.log_kv({"foo": "bar"}, now)
result = util.time_seconds_from_ns(
span.unwrap().events[1].timestamp
)
self.assertEqual(span.unwrap().events[1].attributes["foo"], "bar")
# Tolerate inaccuracies of less than a microsecond. See Note:
# https://open-telemetry.github.io/opentelemetry-python/opentelemetry.ext.opentracing_shim.html
# TODO: This seems to work consistently, but we should find out the
# biggest possible loss of precision.
self.assertAlmostEqual(result, now, places=6)
def test_log(self):
"""Test the deprecated `log` method on `Span` objects."""
with self.shim.start_span("TestSpan") as span:
with self.assertWarns(DeprecationWarning):
span.log(event="foo", payload="bar")
self.assertEqual(span.unwrap().events[0].attributes["event"], "foo")
self.assertEqual(span.unwrap().events[0].attributes["payload"], "bar")
self.assertIsNotNone(span.unwrap().events[0].timestamp)
def test_log_event(self):
"""Test the deprecated `log_event` method on `Span` objects."""
with self.shim.start_span("TestSpan") as span:
with self.assertWarns(DeprecationWarning):
span.log_event("foo", "bar")
self.assertEqual(span.unwrap().events[0].attributes["event"], "foo")
self.assertEqual(span.unwrap().events[0].attributes["payload"], "bar")
self.assertIsNotNone(span.unwrap().events[0].timestamp)
def test_span_context(self):
"""Test construction of `SpanContextShim` objects."""
otel_context = trace.SpanContext(1234, 5678)
context = opentracingshim.SpanContextShim(otel_context)
self.assertIsInstance(context, opentracing.SpanContext)
self.assertEqual(context.unwrap().trace_id, 1234)
self.assertEqual(context.unwrap().span_id, 5678)
def test_span_on_error(self):
"""Verify error tag and logs are created on span when an exception is
raised.
"""
# Raise an exception while a span is active.
with self.assertRaises(Exception):
with self.shim.start_active_span("TestName") as scope:
raise Exception
# Verify exception details have been added to span.
self.assertEqual(scope.span.unwrap().attributes["error"], True)
self.assertEqual(
scope.span.unwrap().events[0].attributes["error.kind"], Exception
)
def test_inject_http_headers(self):
"""Test `inject()` method for Format.HTTP_HEADERS."""
otel_context = trace.SpanContext(trace_id=1220, span_id=7478)
context = opentracingshim.SpanContextShim(otel_context)
headers = {}
self.shim.inject(context, opentracing.Format.HTTP_HEADERS, headers)
self.assertEqual(headers[MockHTTPTextFormat.TRACE_ID_KEY], str(1220))
self.assertEqual(headers[MockHTTPTextFormat.SPAN_ID_KEY], str(7478))
def test_inject_text_map(self):
"""Test `inject()` method for Format.TEXT_MAP."""
otel_context = trace.SpanContext(trace_id=1220, span_id=7478)
context = opentracingshim.SpanContextShim(otel_context)
# Verify Format.TEXT_MAP
text_map = {}
self.shim.inject(context, opentracing.Format.TEXT_MAP, text_map)
self.assertEqual(text_map[MockHTTPTextFormat.TRACE_ID_KEY], str(1220))
self.assertEqual(text_map[MockHTTPTextFormat.SPAN_ID_KEY], str(7478))
def test_inject_binary(self):
"""Test `inject()` method for Format.BINARY."""
otel_context = trace.SpanContext(trace_id=1220, span_id=7478)
context = opentracingshim.SpanContextShim(otel_context)
# Verify exception for non supported binary format.
with self.assertRaises(opentracing.UnsupportedFormatException):
self.shim.inject(context, opentracing.Format.BINARY, bytearray())
def test_extract_http_headers(self):
"""Test `extract()` method for Format.HTTP_HEADERS."""
carrier = {
MockHTTPTextFormat.TRACE_ID_KEY: 1220,
MockHTTPTextFormat.SPAN_ID_KEY: 7478,
}
ctx = self.shim.extract(opentracing.Format.HTTP_HEADERS, carrier)
self.assertEqual(ctx.unwrap().trace_id, 1220)
self.assertEqual(ctx.unwrap().span_id, 7478)
def test_extract_text_map(self):
"""Test `extract()` method for Format.TEXT_MAP."""
carrier = {
MockHTTPTextFormat.TRACE_ID_KEY: 1220,
MockHTTPTextFormat.SPAN_ID_KEY: 7478,
}
ctx = self.shim.extract(opentracing.Format.TEXT_MAP, carrier)
self.assertEqual(ctx.unwrap().trace_id, 1220)
self.assertEqual(ctx.unwrap().span_id, 7478)
def test_extract_binary(self):
"""Test `extract()` method for Format.BINARY."""
# Verify exception for non supported binary format.
with self.assertRaises(opentracing.UnsupportedFormatException):
self.shim.extract(opentracing.Format.BINARY, bytearray())
class MockHTTPTextFormat(HTTPTextFormat):
"""Mock propagator for testing purposes."""
TRACE_ID_KEY = "mock-traceid"
SPAN_ID_KEY = "mock-spanid"
def extract(
self,
get_from_carrier: Getter[HTTPTextFormatT],
carrier: HTTPTextFormatT,
context: typing.Optional[Context] = None,
) -> Context:
trace_id_list = get_from_carrier(carrier, self.TRACE_ID_KEY)
span_id_list = get_from_carrier(carrier, self.SPAN_ID_KEY)
if not trace_id_list or not span_id_list:
return set_span_in_context(trace.INVALID_SPAN)
return set_span_in_context(
trace.DefaultSpan(
trace.SpanContext(
trace_id=int(trace_id_list[0]),
span_id=int(span_id_list[0]),
)
)
)
def inject(
self,
set_in_carrier: Setter[HTTPTextFormatT],
carrier: HTTPTextFormatT,
context: typing.Optional[Context] = None,
) -> None:
span = get_span_from_context(context)
set_in_carrier(
carrier, self.TRACE_ID_KEY, str(span.get_context().trace_id)
)
set_in_carrier(
carrier, self.SPAN_ID_KEY, str(span.get_context().span_id)
)