Skip to content

Commit

Permalink
run black
Browse files Browse the repository at this point in the history
  • Loading branch information
ebracho authored and ocelotl committed Jul 1, 2024
1 parent 354405d commit 8200f0b
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 140 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -316,9 +316,7 @@ def _instrument(self, **kwargs):
else parse_excluded_urls(_excluded_urls)
)
_DjangoMiddleware._otel_request_hook = kwargs.pop("request_hook", None)
_DjangoMiddleware._otel_response_hook = kwargs.pop(
"response_hook", None
)
_DjangoMiddleware._otel_response_hook = kwargs.pop("response_hook", None)
_DjangoMiddleware._duration_histogram = meter.create_histogram(
name=MetricInstruments.HTTP_SERVER_DURATION,
unit="ms",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,18 +142,14 @@ def _is_asgi_request(request: HttpRequest) -> bool:
class _DjangoMiddleware(MiddlewareMixin):
"""Django Middleware for OpenTelemetry"""

_environ_activation_key = (
"opentelemetry-instrumentor-django.activation_key"
)
_environ_activation_key = "opentelemetry-instrumentor-django.activation_key"
_environ_token = "opentelemetry-instrumentor-django.token"
_environ_span_key = "opentelemetry-instrumentor-django.span_key"
_environ_exception_key = "opentelemetry-instrumentor-django.exception_key"
_environ_active_request_attr_key = (
"opentelemetry-instrumentor-django.active_request_attr_key"
)
_environ_duration_attr_key = (
"opentelemetry-instrumentor-django.duration_attr_key"
)
_environ_duration_attr_key = "opentelemetry-instrumentor-django.duration_attr_key"
_environ_timer_key = "opentelemetry-instrumentor-django.timer_key"
_traced_request_attrs = get_traced_request_attrs("DJANGO")
_excluded_urls = get_excluded_urls("DJANGO")
Expand Down Expand Up @@ -224,9 +220,7 @@ def process_request(self, request):
attributes=attributes,
)

active_requests_count_attrs = _parse_active_request_count_attrs(
attributes
)
active_requests_count_attrs = _parse_active_request_count_attrs(attributes)
duration_attrs = _parse_duration_attrs(attributes)

request.META[self._environ_active_request_attr_key] = (
Expand Down Expand Up @@ -267,8 +261,8 @@ def process_request(self, request):
)
else:
if span.is_recording() and span.kind == SpanKind.SERVER:
custom_attributes = (
wsgi_collect_custom_request_headers_attributes(carrier)
custom_attributes = wsgi_collect_custom_request_headers_attributes(
carrier
)
if len(custom_attributes) > 0:
span.set_attributes(custom_attributes)
Expand Down Expand Up @@ -343,9 +337,7 @@ def process_response(self, request, response):
active_requests_count_attrs = request.META.pop(
self._environ_active_request_attr_key, None
)
duration_attrs = request.META.pop(
self._environ_duration_attr_key, None
)
duration_attrs = request.META.pop(self._environ_duration_attr_key, None)
if duration_attrs:
duration_attrs[SpanAttributes.HTTP_STATUS_CODE] = (
response.status_code
Expand Down Expand Up @@ -384,10 +376,8 @@ def process_response(self, request, response):
response.items(),
)
if span.is_recording() and span.kind == SpanKind.SERVER:
custom_attributes = (
wsgi_collect_custom_response_headers_attributes(
response.items()
)
custom_attributes = wsgi_collect_custom_response_headers_attributes(
response.items()
)
if len(custom_attributes) > 0:
span.set_attributes(custom_attributes)
Expand Down Expand Up @@ -422,15 +412,13 @@ def process_response(self, request, response):
activation.__exit__(None, None, None)

if request_start_time is not None:
duration = max(
round((default_timer() - request_start_time) * 1000), 0
)
duration = max(round((default_timer() - request_start_time) * 1000), 0)
self._duration_histogram.record(duration, duration_attrs)
self._active_request_counter.add(-1, active_requests_count_attrs)
if request.META.get(self._environ_token, None) is not None:
detach(request.META.get(self._environ_token))
request.META.pop(self._environ_token)

if response_hook_exception is not None:
raise response_hook_exception

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ def __call__(self, request) -> Any:
with ExitStack() as stack:
for db_alias in connections:
stack.enter_context(
connections[db_alias].execute_wrapper(
_QueryWrapper(request)
)
connections[db_alias].execute_wrapper(_QueryWrapper(request))
)
return self.get_response(request)

Expand All @@ -60,22 +58,14 @@ def __init__(self, request) -> None:

def __call__(self, execute: Type[T], sql, params, many, context) -> T:
# pylint: disable-msg=too-many-locals
with_framework = getattr(
conf.settings, "SQLCOMMENTER_WITH_FRAMEWORK", True
)
with_controller = getattr(
conf.settings, "SQLCOMMENTER_WITH_CONTROLLER", True
)
with_framework = getattr(conf.settings, "SQLCOMMENTER_WITH_FRAMEWORK", True)
with_controller = getattr(conf.settings, "SQLCOMMENTER_WITH_CONTROLLER", True)
with_route = getattr(conf.settings, "SQLCOMMENTER_WITH_ROUTE", True)
with_app_name = getattr(
conf.settings, "SQLCOMMENTER_WITH_APP_NAME", True
)
with_app_name = getattr(conf.settings, "SQLCOMMENTER_WITH_APP_NAME", True)
with_opentelemetry = getattr(
conf.settings, "SQLCOMMENTER_WITH_OPENTELEMETRY", True
)
with_db_driver = getattr(
conf.settings, "SQLCOMMENTER_WITH_DB_DRIVER", True
)
with_db_driver = getattr(conf.settings, "SQLCOMMENTER_WITH_DB_DRIVER", True)

db_driver = context["connection"].settings_dict.get("ENGINE", "")
resolver_match = self.request.resolver_match
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,7 @@ def test_traced_get(self):
"http://testserver/traced/",
)
if DJANGO_2_2:
self.assertEqual(
span.attributes[SpanAttributes.HTTP_ROUTE], "^traced/"
)
self.assertEqual(span.attributes[SpanAttributes.HTTP_ROUTE], "^traced/")
self.assertEqual(span.attributes[SpanAttributes.HTTP_SCHEME], "http")
self.assertEqual(span.attributes[SpanAttributes.HTTP_STATUS_CODE], 200)

Expand Down Expand Up @@ -239,9 +237,7 @@ def test_traced_post(self):
"http://testserver/traced/",
)
if DJANGO_2_2:
self.assertEqual(
span.attributes[SpanAttributes.HTTP_ROUTE], "^traced/"
)
self.assertEqual(span.attributes[SpanAttributes.HTTP_ROUTE], "^traced/")
self.assertEqual(span.attributes[SpanAttributes.HTTP_SCHEME], "http")
self.assertEqual(span.attributes[SpanAttributes.HTTP_STATUS_CODE], 200)

Expand All @@ -263,21 +259,15 @@ def test_error(self):
"http://testserver/error/",
)
if DJANGO_2_2:
self.assertEqual(
span.attributes[SpanAttributes.HTTP_ROUTE], "^error/"
)
self.assertEqual(span.attributes[SpanAttributes.HTTP_ROUTE], "^error/")
self.assertEqual(span.attributes[SpanAttributes.HTTP_SCHEME], "http")
self.assertEqual(span.attributes[SpanAttributes.HTTP_STATUS_CODE], 500)

self.assertEqual(len(span.events), 1)
event = span.events[0]
self.assertEqual(event.name, "exception")
self.assertEqual(
event.attributes[SpanAttributes.EXCEPTION_TYPE], "ValueError"
)
self.assertEqual(
event.attributes[SpanAttributes.EXCEPTION_MESSAGE], "error"
)
self.assertEqual(event.attributes[SpanAttributes.EXCEPTION_TYPE], "ValueError")
self.assertEqual(event.attributes[SpanAttributes.EXCEPTION_MESSAGE], "error")

def test_exclude_lists(self):
client = Client()
Expand Down Expand Up @@ -391,9 +381,8 @@ def response_hook(span, request, response):
self.assertIsInstance(response_hook_args[1], HttpRequest)
self.assertIsInstance(response_hook_args[2], HttpResponse)
self.assertEqual(response_hook_args[2], response)

def test_request_hook_exception(self):

def test_request_hook_exception(self):
class RequestHookException(Exception):
pass

Expand All @@ -409,9 +398,8 @@ def request_hook(span, request):
finished_spans = self.memory_exporter.get_finished_spans()
self.assertEqual(len(finished_spans), 1)
self.assertEquals(finished_spans[0].status.status_code, StatusCode.ERROR)

def test_response_hook_exception(self):

def test_response_hook_exception(self):
class ResponseHookException(Exception):
pass

Expand Down Expand Up @@ -522,16 +510,12 @@ def test_wsgi_metrics(self):
if isinstance(point, HistogramDataPoint):
self.assertEqual(point.count, 3)
histrogram_data_point_seen = True
self.assertAlmostEqual(
duration, point.sum, delta=100
)
self.assertAlmostEqual(duration, point.sum, delta=100)
if isinstance(point, NumberDataPoint):
number_data_point_seen = True
self.assertEqual(point.value, 0)
for attr in point.attributes:
self.assertIn(
attr, _recommended_attrs[metric.name]
)
self.assertIn(attr, _recommended_attrs[metric.name])
self.assertTrue(histrogram_data_point_seen and number_data_point_seen)

def test_wsgi_metrics_unistrument(self):
Expand All @@ -558,9 +542,7 @@ def setUpClass(cls):
def setUp(self):
super().setUp()
setup_test_environment()
resource = resources.Resource.create(
{"resource-key": "resource-value"}
)
resource = resources.Resource.create({"resource-key": "resource-value"})
result = self.create_tracer_provider(resource=resource)
tracer_provider, exporter = result
self.exporter = exporter
Expand All @@ -585,15 +567,11 @@ def test_tracer_provider_traced(self):

span = spans[0]

self.assertEqual(
span.resource.attributes["resource-key"], "resource-value"
)
self.assertEqual(span.resource.attributes["resource-key"], "resource-value")

def test_django_with_wsgi_instrumented(self):
tracer = self.tracer_provider.get_tracer(__name__)
with tracer.start_as_current_span(
"test", kind=SpanKind.SERVER
) as parent_span:
with tracer.start_as_current_span("test", kind=SpanKind.SERVER) as parent_span:
Client().get("/span_name/1234/")
span_list = self.exporter.get_finished_spans()
print(span_list)
Expand Down Expand Up @@ -640,12 +618,8 @@ def tearDownClass(cls):

def test_http_custom_request_headers_in_span_attributes(self):
expected = {
"http.request.header.custom_test_header_1": (
"test-header-value-1",
),
"http.request.header.custom_test_header_2": (
"test-header-value-2",
),
"http.request.header.custom_test_header_1": ("test-header-value-1",),
"http.request.header.custom_test_header_2": ("test-header-value-2",),
"http.request.header.regex_test_header_1": ("Regex Test Value 1",),
"http.request.header.regex_test_header_2": (
"RegexTestValue2,RegexTestValue3",
Expand All @@ -669,9 +643,7 @@ def test_http_custom_request_headers_in_span_attributes(self):

def test_http_custom_request_headers_not_in_span_attributes(self):
not_expected = {
"http.request.header.custom_test_header_2": (
"test-header-value-2",
),
"http.request.header.custom_test_header_2": ("test-header-value-2",),
}
Client(HTTP_CUSTOM_TEST_HEADER_1="test-header-value-1").get("/traced/")
spans = self.exporter.get_finished_spans()
Expand All @@ -685,12 +657,8 @@ def test_http_custom_request_headers_not_in_span_attributes(self):

def test_http_custom_response_headers_in_span_attributes(self):
expected = {
"http.response.header.custom_test_header_1": (
"test-header-value-1",
),
"http.response.header.custom_test_header_2": (
"test-header-value-2",
),
"http.response.header.custom_test_header_1": ("test-header-value-1",),
"http.response.header.custom_test_header_2": ("test-header-value-2",),
"http.response.header.my_custom_regex_header_1": (
"my-custom-regex-value-1,my-custom-regex-value-2",
),
Expand All @@ -710,9 +678,7 @@ def test_http_custom_response_headers_in_span_attributes(self):

def test_http_custom_response_headers_not_in_span_attributes(self):
not_expected = {
"http.response.header.custom_test_header_3": (
"test-header-value-3",
),
"http.response.header.custom_test_header_3": ("test-header-value-3",),
}
Client().get("/traced_custom_header/")
spans = self.exporter.get_finished_spans()
Expand Down
Loading

0 comments on commit 8200f0b

Please sign in to comment.