Skip to content

Commit fcca86c

Browse files
committed
test(fastapi): added span assertions for custom api route tests
1 parent 79adade commit fcca86c

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,11 +191,9 @@ def client_response_hook(span: Span, scope: dict[str, Any], message: dict[str, A
191191
import fastapi
192192
from starlette.applications import Starlette
193193
from starlette.middleware.errors import ServerErrorMiddleware
194-
195194
from starlette.routing import Match, Route
196195
from starlette.types import ASGIApp, Receive, Scope, Send
197196

198-
199197
from opentelemetry.instrumentation._semconv import (
200198
_get_schema_url,
201199
_OpenTelemetrySemanticConventionStability,

instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_instrumentation.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import weakref as _weakref
2121
from contextlib import ExitStack
2222
from timeit import default_timer
23-
from typing import Any, cast
23+
from typing import Any, Final, cast
2424
from unittest.mock import Mock, call, patch
2525

2626
import fastapi
@@ -341,15 +341,27 @@ def test_sub_app_fastapi_call(self):
341341
span.attributes[HTTP_URL],
342342
)
343343

344-
345344
def test_custom_api_router(self):
346345
"""
347346
This test is to ensure that custom API routers the OpenTelemetryMiddleware does not cause issues with
348347
custom API routers that depend on non-standard fields on the ASGI scope.
349348
"""
350-
resp = self._client.get("/custom-router/success")
351-
self.assertEqual(resp.status_code, 200)
352-
349+
resp: Final = self._client.get("/custom-router/success")
350+
spans: Final = self.memory_exporter.get_finished_spans()
351+
spans_with_http_attributes = [
352+
span
353+
for span in spans
354+
if (HTTP_URL in span.attributes or HTTP_TARGET in span.attributes)
355+
]
356+
self.assertEqual(200, resp.status_code)
357+
for span in spans_with_http_attributes:
358+
self.assertEqual(
359+
"/custom-router/success", span.attributes[HTTP_TARGET]
360+
)
361+
self.assertEqual(
362+
"https://testserver/custom-router/success",
363+
span.attributes[HTTP_URL],
364+
)
353365

354366
def test_host_fastapi_call(self):
355367
client = TestClient(self._app, base_url="https://testserver2:443")

0 commit comments

Comments
 (0)