Skip to content

Commit e800462

Browse files
committed
add check that trace id is propagated correctly in fastapi
1 parent 9ec76d4 commit e800462

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

packages/service-library/tests/fastapi/test_tracing.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import random
66
import string
77
from collections.abc import Callable, Iterator
8+
from functools import partial
89
from typing import Any
910

1011
import pip
@@ -13,6 +14,7 @@
1314
from fastapi.exceptions import HTTPException
1415
from fastapi.responses import PlainTextResponse
1516
from fastapi.testclient import TestClient
17+
from opentelemetry import trace
1618
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
1719
from pydantic import ValidationError
1820
from servicelib.fastapi.tracing import (
@@ -199,12 +201,19 @@ async def test_trace_id_in_response_header(
199201
) -> None:
200202
tracing_settings = TracingSettings()
201203

202-
@mocked_app.get("/")
203-
async def handler():
204+
handler_data = dict()
205+
206+
async def handler(handler_data: dict):
207+
current_span = trace.get_current_span()
208+
handler_data[_OSPARC_TRACE_ID_HEADER] = format(
209+
current_span.get_span_context().trace_id, "032x"
210+
)
204211
if isinstance(server_response, HTTPException):
205212
raise server_response
206213
return server_response
207214

215+
mocked_app.get("/")(partial(handler, handler_data))
216+
208217
async for _ in get_tracing_instrumentation_lifespan(
209218
tracing_settings=tracing_settings,
210219
service_name="Mock-OpenTelemetry-Pytest",
@@ -215,3 +224,4 @@ async def handler():
215224
assert _OSPARC_TRACE_ID_HEADER in response.headers
216225
trace_id = response.headers[_OSPARC_TRACE_ID_HEADER]
217226
assert len(trace_id) == 32 # Ensure trace ID is a 32-character hex string
227+
assert trace_id == handler_data[_OSPARC_TRACE_ID_HEADER]

0 commit comments

Comments
 (0)