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 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
|
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""Tests for the distributed tracing policy."""
import logging
import time
import urllib
from unittest import mock
from azure.core.pipeline import Pipeline, PipelineResponse, PipelineRequest, PipelineContext
from azure.core.pipeline.policies import DistributedTracingPolicy, UserAgentPolicy, RetryPolicy
from azure.core.pipeline.transport import HttpTransport, RequestsTransport
from azure.core.settings import settings
from azure.core.tracing._models import SpanKind
from azure.core.tracing._abstract_span import HttpSpanMixin
import pytest
from opentelemetry.trace import format_span_id, format_trace_id
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from utils import HTTP_RESPONSES, HTTP_REQUESTS, create_http_response, request_and_responses_product
from tracing_common import FakeSpan
class TestTracingPolicyPluginImplementation:
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_solo(self, tracing_implementation, http_request, http_response):
"""Test policy with no other policy and happy path"""
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
request.headers[policy._REQUEST_ID] = "some client request id"
pipeline_request = PipelineRequest(request, PipelineContext(None))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
response.headers[policy._RESPONSE_ID] = "some request id"
assert request.headers.get("traceparent") == "00-12345-GET-01"
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
time.sleep(0.001)
policy.on_request(pipeline_request)
try:
raise ValueError("Transport trouble")
except:
policy.on_exception(pipeline_request)
# Check on_response
network_span = root_span.children[0]
assert network_span.name == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_METHOD) == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_URL) == "http://localhost/temp?query=query"
assert network_span.attributes.get(HttpSpanMixin._NET_PEER_NAME) == "localhost"
assert network_span.attributes.get(HttpSpanMixin._HTTP_USER_AGENT) is None
assert network_span.attributes.get(policy._RESPONSE_ID_ATTR) == "some request id"
assert network_span.attributes.get(policy._REQUEST_ID_ATTR) == "some client request id"
assert network_span.attributes.get(HttpSpanMixin._HTTP_STATUS_CODE) == 202
assert policy._ERROR_TYPE not in network_span.attributes
# Check on_exception
network_span = root_span.children[1]
assert network_span.name == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_METHOD) == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_URL) == "http://localhost/temp?query=query"
assert network_span.attributes.get(policy._REQUEST_ID_ATTR) == "some client request id"
assert network_span.attributes.get(HttpSpanMixin._HTTP_USER_AGENT) is None
assert network_span.attributes.get(policy._RESPONSE_ID_ATTR) == None
assert network_span.attributes.get(HttpSpanMixin._HTTP_STATUS_CODE) == 504
assert network_span.attributes.get(policy._ERROR_TYPE)
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_error_response(self, tracing_implementation, http_request, http_response):
"""Test policy when the HTTP response corresponds to an error."""
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy(tracing_attributes={"myattr": "myvalue"})
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 403
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
network_span = root_span.children[0]
assert network_span.name == "GET"
assert network_span.attributes.get(policy._ERROR_TYPE) == "403"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_attributes(self, tracing_implementation, http_request, http_response):
"""Test policy with no other policy and happy path"""
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy(tracing_attributes={"myattr": "myvalue"})
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
# Check on_response
network_span = root_span.children[0]
assert network_span.attributes.get("myattr") == "myvalue"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_attributes_per_operation(
self, tracing_implementation, http_request, http_response
):
"""Test policy with no other policy and happy path"""
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy(tracing_attributes={"myattr": "myvalue"})
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None, tracing_attributes={"foo": "bar"}))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
# Check on_response
network_span = root_span.children[0]
assert network_span.attributes.get("foo") == "bar"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_exception(self, caplog, tracing_implementation, http_request, http_response):
"""Test policy with an exception during on_request before span is created, and be sure policy ignores it"""
def bad_namer(http_request):
path = urllib.parse.urlparse(http_request.url).path
return f"{http_request.method} {path}"
with FakeSpan(name="parent") as root_span:
# Force an exception before the network span is created with invalid URL parsing.
policy = DistributedTracingPolicy(network_span_namer=bad_namer)
request = http_request("GET", "http://[[[")
request.headers[policy._REQUEST_ID] = "some client request id"
pipeline_request = PipelineRequest(request, PipelineContext(None))
with caplog.at_level(logging.WARNING, logger="azure.core.pipeline.policies.distributed_tracing"):
policy.on_request(pipeline_request)
assert "Unable to start network span" in caplog.text
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
response.headers[policy._RESPONSE_ID] = "some request id"
assert request.headers.get("traceparent") is None # Got not network trace
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
time.sleep(0.001)
policy.on_request(pipeline_request)
try:
raise ValueError("Transport trouble")
except:
policy.on_exception(pipeline_request)
assert len(root_span.children) == 0
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_with_user_agent(self, tracing_implementation, http_request, http_response):
"""Test policy working with user agent."""
with mock.patch.dict("os.environ", {"AZURE_HTTP_USER_AGENT": "mytools"}):
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost")
request.headers[policy._REQUEST_ID] = "some client request id"
pipeline_request = PipelineRequest(request, PipelineContext(None))
user_agent = UserAgentPolicy()
user_agent.on_request(pipeline_request)
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
response.headers[policy._RESPONSE_ID] = "some request id"
pipeline_response = PipelineResponse(request, response, PipelineContext(None))
assert request.headers.get("traceparent") == "00-12345-GET-01"
policy.on_response(pipeline_request, pipeline_response)
time.sleep(0.001)
policy.on_request(pipeline_request)
try:
raise ValueError("Transport trouble")
except:
policy.on_exception(pipeline_request)
user_agent.on_response(pipeline_request, pipeline_response)
network_span = root_span.children[0]
assert network_span.name == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_METHOD) == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_URL) == "http://localhost"
assert network_span.attributes.get(HttpSpanMixin._HTTP_USER_AGENT).endswith("mytools")
assert network_span.attributes.get(policy._RESPONSE_ID_ATTR) == "some request id"
assert network_span.attributes.get(policy._REQUEST_ID_ATTR) == "some client request id"
assert network_span.attributes.get(HttpSpanMixin._HTTP_STATUS_CODE) == 202
network_span = root_span.children[1]
assert network_span.name == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_METHOD) == "GET"
assert network_span.attributes.get(HttpSpanMixin._HTTP_URL) == "http://localhost"
assert network_span.attributes.get(HttpSpanMixin._HTTP_USER_AGENT).endswith("mytools")
assert network_span.attributes.get(policy._REQUEST_ID_ATTR) == "some client request id"
assert network_span.attributes.get(policy._RESPONSE_ID_ATTR) is None
assert network_span.attributes.get(HttpSpanMixin._HTTP_STATUS_CODE) == 504
# Exception should propagate status for Opencensus
assert network_span.status == "Transport trouble"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_span_retry_attributes(self, tracing_implementation, http_request, http_response):
class MockTransport(HttpTransport):
def __init__(self):
self._count = 0
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def close(self):
pass
def open(self):
pass
def send(self, request, **kwargs):
self._count += 1
response = create_http_response(http_response, request, None)
response.status_code = 429
return response
http_request = http_request("GET", "http://localhost/")
retry_policy = RetryPolicy(retry_total=2)
distributed_tracing_policy = DistributedTracingPolicy()
transport = MockTransport()
with FakeSpan(name="parent") as root_span:
pipeline = Pipeline(transport, [retry_policy, distributed_tracing_policy])
pipeline.run(http_request)
assert transport._count == 3
assert len(root_span.children) == 3
assert root_span.children[0].attributes.get("http.request.resend_count") is None
assert root_span.children[1].attributes.get("http.request.resend_count") == 1
assert root_span.children[2].attributes.get("http.request.resend_count") == 2
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_span_namer(self, tracing_implementation, http_request, http_response):
with FakeSpan(name="parent") as root_span:
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
def fixed_namer(http_request):
assert http_request is request
return "overriddenname"
policy = DistributedTracingPolicy(network_span_namer=fixed_namer)
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
def operation_namer(http_request):
assert http_request is request
return "operation level name"
pipeline_request.context.options["network_span_namer"] = operation_namer
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
# Check init kwargs
network_span = root_span.children[0]
assert network_span.name == "overriddenname"
# Check operation kwargs
network_span = root_span.children[1]
assert network_span.name == "operation level name"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_with_tracing_options(self, tracing_implementation, http_request, http_response):
"""Test policy when tracing options are provided."""
settings.tracing_enabled = False
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
pipeline_request.context.options["tracing_options"] = {
"enabled": True,
"attributes": {"custom_key": "custom_value"},
}
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
assert len(root_span.children) == 1
network_span = root_span.children[0]
assert network_span.attributes.get("custom_key") == "custom_value"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_with_tracing_disabled(
self, tracing_implementation, http_request, http_response
):
"""Test policy when tracing is disabled through user options."""
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
pipeline_request.context.options["tracing_options"] = {"enabled": False}
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
assert len(root_span.children) == 0
class TestTracingPolicyNativeTracing:
"""Test the distributed tracing policy with the native core tracer."""
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy(self, tracing_helper, http_request, http_response):
"""Test policy when the HTTP response corresponds to a success."""
with tracing_helper.tracer.start_as_current_span("Root") as root_span:
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
traceparent = request.headers.get("traceparent")
assert traceparent is not None
assert traceparent.startswith("00-")
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
finished_spans = tracing_helper.exporter.get_finished_spans()
assert len(finished_spans) == 2
assert finished_spans[0].name == "GET"
assert finished_spans[0].parent is root_span.get_span_context()
span_context = finished_spans[0].get_span_context()
assert traceparent.split("-")[1] == format_trace_id(span_context.trace_id)
assert traceparent.split("-")[2] == format_span_id(span_context.span_id)
assert finished_spans[0].attributes.get(policy._HTTP_REQUEST_METHOD) == "GET"
assert finished_spans[0].attributes.get(policy._URL_FULL) == "http://localhost/temp?query=query"
assert finished_spans[0].attributes.get(policy._SERVER_ADDRESS) == "localhost"
assert finished_spans[0].attributes.get(policy._USER_AGENT_ORIGINAL) is None
assert finished_spans[0].attributes.get(policy._HTTP_RESPONSE_STATUS_CODE) == 202
assert finished_spans[1].name == "Root"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_error_response(self, tracing_helper, http_request, http_response):
"""Test policy when the HTTP response corresponds to an error."""
with tracing_helper.tracer.start_as_current_span("Root"):
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 403
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
finished_spans = tracing_helper.exporter.get_finished_spans()
assert finished_spans[0].name == "GET"
assert finished_spans[0].attributes.get("error.type") == "403"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_custom_instrumentation_config(
self, tracing_helper, http_request, http_response
):
"""Test policy when a custom tracer provider is provided."""
config = {
"library_name": "my-library",
"library_version": "1.0.0",
"attributes": {"az.namespace": "Sample.Namespace"},
}
with tracing_helper.tracer.start_as_current_span("Root"):
policy = DistributedTracingPolicy(instrumentation_config=config)
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 403
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
finished_spans = tracing_helper.exporter.get_finished_spans()
assert finished_spans[0].name == "GET"
assert finished_spans[0].attributes.get(policy._ERROR_TYPE) == "403"
assert finished_spans[0].instrumentation_scope.name == "my-library"
assert finished_spans[0].instrumentation_scope.version == "1.0.0"
assert finished_spans[0].instrumentation_scope.attributes.get("az.namespace") == "Sample.Namespace"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_exception(self, caplog, tracing_helper, http_request, http_response):
"""Test policy with an exception during on_request before span is created, and be sure policy ignores it."""
def bad_namer(http_request):
path = urllib.parse.urlparse(http_request.url).path
return f"{http_request.method} {path}"
with tracing_helper.tracer.start_as_current_span("Root"):
policy = DistributedTracingPolicy(network_span_namer=bad_namer)
request = http_request("GET", "http://[[[")
pipeline_request = PipelineRequest(request, PipelineContext(None))
with caplog.at_level(logging.WARNING, logger="azure.core.pipeline.policies.distributed_tracing"):
policy.on_request(pipeline_request)
assert "Unable to start network span" in caplog.text
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 403
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
# A span for the request should not have been created.
finished_spans = tracing_helper.exporter.get_finished_spans()
assert len(finished_spans) == 1
assert finished_spans[0].name == "Root"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_with_user_agent_policy(self, tracing_helper, http_request, http_response):
"""Test policy when used with the UserAgentPolicy."""
with mock.patch.dict("os.environ", {"AZURE_HTTP_USER_AGENT": "test-user-agent"}):
with tracing_helper.tracer.start_as_current_span("Root") as root_span:
policy = DistributedTracingPolicy()
user_agent_policy = UserAgentPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
user_agent_policy.on_request(pipeline_request)
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
traceparent = request.headers.get("traceparent")
assert traceparent is not None
assert traceparent.startswith("00-")
pipeline_response = PipelineResponse(request, response, PipelineContext(None))
policy.on_response(pipeline_request, pipeline_response)
user_agent_policy.on_response(pipeline_request, pipeline_response)
finished_spans = tracing_helper.exporter.get_finished_spans()
assert len(finished_spans) == 2
assert finished_spans[0].name == "GET"
assert finished_spans[0].parent is root_span.get_span_context()
span_context = finished_spans[0].get_span_context()
assert traceparent.split("-")[1] == format_trace_id(span_context.trace_id)
assert traceparent.split("-")[2] == format_span_id(span_context.span_id)
assert finished_spans[0].attributes.get(policy._HTTP_REQUEST_METHOD) == "GET"
assert finished_spans[0].attributes.get(policy._URL_FULL) == "http://localhost/temp?query=query"
assert finished_spans[0].attributes.get(policy._SERVER_ADDRESS) == "localhost"
assert finished_spans[0].attributes.get(policy._USER_AGENT_ORIGINAL) is not None
assert finished_spans[0].attributes.get(policy._USER_AGENT_ORIGINAL).endswith("test-user-agent")
assert finished_spans[0].attributes.get(policy._HTTP_RESPONSE_STATUS_CODE) == 202
assert finished_spans[1].name == "Root"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_span_retry_attributes(self, tracing_helper, http_request, http_response):
"""Test that the retry count is added to the span attributes."""
class MockTransport(HttpTransport):
def __init__(self):
self._count = 0
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def close(self):
pass
def open(self):
pass
def send(self, request, **kwargs):
self._count += 1
response = create_http_response(http_response, request, None)
response.status_code = 429
return response
http_request = http_request("GET", "http://localhost/")
retry_policy = RetryPolicy(retry_total=2)
distributed_tracing_policy = DistributedTracingPolicy()
transport = MockTransport()
with tracing_helper.tracer.start_as_current_span("Root") as root_span:
policies = [retry_policy, distributed_tracing_policy]
pipeline = Pipeline(transport, policies=policies)
pipeline.run(http_request)
assert transport._count == 3
finished_spans = tracing_helper.exporter.get_finished_spans()
parent_context = root_span.get_span_context()
assert len(finished_spans) == 4
assert finished_spans[0].parent == parent_context
assert finished_spans[0].attributes.get(distributed_tracing_policy._HTTP_RESEND_COUNT) is None
assert finished_spans[0].attributes.get(distributed_tracing_policy._URL_FULL) == "http://localhost/"
assert finished_spans[1].parent == parent_context
assert finished_spans[1].attributes.get(distributed_tracing_policy._HTTP_RESEND_COUNT) == 1
assert finished_spans[1].attributes.get(distributed_tracing_policy._URL_FULL) == "http://localhost/"
assert finished_spans[2].parent == parent_context
assert finished_spans[2].attributes.get(distributed_tracing_policy._HTTP_RESEND_COUNT) == 2
assert finished_spans[2].attributes.get(distributed_tracing_policy._URL_FULL) == "http://localhost/"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_with_tracing_options(self, tracing_helper, http_request, http_response):
"""Test policy when tracing options are provided."""
settings.tracing_enabled = False
with tracing_helper.tracer.start_as_current_span("Root") as root_span:
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
pipeline_request.context.options["tracing_options"] = {
"enabled": True,
"attributes": {"custom_key": "custom_value"},
}
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
finished_spans = tracing_helper.exporter.get_finished_spans()
assert len(finished_spans) == 2
assert finished_spans[0].name == "GET"
assert finished_spans[0].parent is root_span.get_span_context()
assert finished_spans[0].attributes.get(policy._HTTP_REQUEST_METHOD) == "GET"
assert finished_spans[0].attributes.get(policy._URL_FULL) == "http://localhost/temp?query=query"
assert finished_spans[0].attributes.get(policy._SERVER_ADDRESS) == "localhost"
assert finished_spans[0].attributes.get(policy._USER_AGENT_ORIGINAL) is None
assert finished_spans[0].attributes.get(policy._HTTP_RESPONSE_STATUS_CODE) == 202
assert finished_spans[0].attributes.get("custom_key") == "custom_value"
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_distributed_tracing_policy_disabled(self, tracing_helper, http_request, http_response):
"""Test policy when tracing is enabled globally but disabled on the operation."""
with tracing_helper.tracer.start_as_current_span("Root"):
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
pipeline_request.context.options["tracing_options"] = {
"enabled": False,
}
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
finished_spans = tracing_helper.exporter.get_finished_spans()
assert len(finished_spans) == 1
assert finished_spans[0].name == "Root"
@pytest.mark.parametrize("http_request", HTTP_REQUESTS)
def test_suppress_http_auto_instrumentation(self, port, tracing_helper, http_request):
"""Test that automatic HTTP instrumentation is suppressed when a request is made through the pipeline."""
# Enable auto-instrumentation for requests.
requests_instrumentor = RequestsInstrumentor()
requests_instrumentor.instrument()
policy = DistributedTracingPolicy()
transport = RequestsTransport()
request = http_request("GET", f"http://localhost:{port}/basic/string")
with Pipeline(transport, policies=[policy]) as pipeline:
pipeline.run(request)
finished_spans = tracing_helper.exporter.get_finished_spans()
assert len(finished_spans) == 1
assert finished_spans[0].attributes.get(policy._HTTP_REQUEST_METHOD) == "GET"
assert finished_spans[0].attributes.get(policy._URL_FULL) == f"http://localhost:{port}/basic/string"
assert finished_spans[0].attributes.get(policy._SERVER_ADDRESS) == "localhost"
assert finished_spans[0].attributes.get(policy._HTTP_RESPONSE_STATUS_CODE) == 200
requests_instrumentor.uninstrument()
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(HTTP_RESPONSES))
def test_tracing_impl_takes_precedence(self, tracing_implementation, http_request, http_response):
"""Test that a tracing implementation takes precedence over the native tracing."""
settings.tracing_enabled = True
assert settings.tracing_implementation() is FakeSpan
assert settings.tracing_enabled
with FakeSpan(name="parent") as root_span:
policy = DistributedTracingPolicy()
request = http_request("GET", "http://localhost/temp?query=query")
pipeline_request = PipelineRequest(request, PipelineContext(None))
policy.on_request(pipeline_request)
response = create_http_response(http_response, request, None)
response.headers = request.headers
response.status_code = 202
policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
assert len(root_span.children) == 1
network_span = root_span.children[0]
assert network_span.name == "GET"
assert network_span.kind == SpanKind.CLIENT
|