Buckets:

download
raw
55.9 kB
from __future__ import annotations import importlib import os import warnings from abc import ABC, abstractmethod from contextlib import contextmanager from typing import Any, Generic, TypeAlias, TypeVar, cast from unittest import mock import httpx import httpx2 import pytest from dirty_equals import IsAnyStr, IsStr from inline_snapshot import Is, snapshot from opentelemetry.instrumentation._semconv import _OpenTelemetrySemanticConventionStability # type: ignore from opentelemetry.instrumentation.httpx import ( HTTPX2ClientInstrumentor, HTTPXClientInstrumentor, RequestInfo, ResponseInfo, ) from opentelemetry.trace.span import Span import logfire import logfire._internal.integrations.httpx from logfire._internal.integrations.httpx import CODES_FOR_METHODS_WITH_DATA_PARAM, is_json_type from logfire.testing import TestExporter pytestmark = pytest.mark.anyio RESPONSE_BODY = b'{"good": "response"}' RequestT = TypeVar('RequestT', httpx.Request, httpx2.Request) ResponseT = TypeVar('ResponseT', httpx.Response, httpx2.Response) class HTTPXFamily(ABC, Generic[RequestT, ResponseT]): name: str @staticmethod @abstractmethod def response_handler(request: RequestT, response_body: bytes = RESPONSE_BODY) -> ResponseT: raise NotImplementedError @staticmethod @abstractmethod def transport_response_handler(_transport: object, request: RequestT) -> ResponseT: raise NotImplementedError @abstractmethod def create_transport(self, response_body: bytes = RESPONSE_BODY) -> httpx.MockTransport | httpx2.MockTransport: raise NotImplementedError @abstractmethod def patch_transport(self, monkeypatch: pytest.MonkeyPatch) -> None: raise NotImplementedError @abstractmethod def client(self, response_body: bytes = RESPONSE_BODY) -> httpx.Client | httpx2.Client: raise NotImplementedError @abstractmethod def async_client(self, response_body: bytes = RESPONSE_BODY) -> httpx.AsyncClient | httpx2.AsyncClient: raise NotImplementedError class HTTPXClientFamily(HTTPXFamily[httpx.Request, httpx.Response]): name = 'httpx' @staticmethod def response_handler(request: httpx.Request, response_body: bytes = RESPONSE_BODY) -> httpx.Response: return httpx.Response(200, headers=request.headers, stream=httpx.ByteStream(response_body)) @staticmethod def transport_response_handler(_transport: object, request: httpx.Request) -> httpx.Response: return HTTPXClientFamily.response_handler(request) def create_transport(self, response_body: bytes = RESPONSE_BODY) -> httpx.MockTransport: return httpx.MockTransport(lambda request: self.response_handler(request, response_body)) def patch_transport(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(httpx.HTTPTransport, 'handle_request', self.transport_response_handler) def client(self, response_body: bytes = RESPONSE_BODY) -> httpx.Client: return httpx.Client(transport=self.create_transport(response_body)) def async_client(self, response_body: bytes = RESPONSE_BODY) -> httpx.AsyncClient: return httpx.AsyncClient(transport=self.create_transport(response_body)) class HTTPX2ClientFamily(HTTPXFamily[httpx2.Request, httpx2.Response]): name = 'httpx2' @staticmethod def response_handler(request: httpx2.Request, response_body: bytes = RESPONSE_BODY) -> httpx2.Response: return httpx2.Response(200, headers=request.headers, stream=httpx2.ByteStream(response_body)) @staticmethod def transport_response_handler(_transport: object, request: httpx2.Request) -> httpx2.Response: return HTTPX2ClientFamily.response_handler(request) def create_transport(self, response_body: bytes = RESPONSE_BODY) -> httpx2.MockTransport: return httpx2.MockTransport(lambda request: self.response_handler(request, response_body)) def patch_transport(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(httpx2.HTTPTransport, 'handle_request', self.transport_response_handler) def client(self, response_body: bytes = RESPONSE_BODY) -> httpx2.Client: return httpx2.Client(transport=self.create_transport(response_body)) def async_client(self, response_body: bytes = RESPONSE_BODY) -> httpx2.AsyncClient: return httpx2.AsyncClient(transport=self.create_transport(response_body)) HTTPX_CLIENT_FAMILY = HTTPXClientFamily() HTTPX2_CLIENT_FAMILY = HTTPX2ClientFamily() HTTPXFamilyType: TypeAlias = HTTPXClientFamily | HTTPX2ClientFamily HTTPX_FAMILIES: tuple[HTTPXFamilyType, ...] = (HTTPX_CLIENT_FAMILY, HTTPX2_CLIENT_FAMILY) @pytest.fixture(params=HTTPX_FAMILIES, ids=lambda family: family.name) def httpx_family(request: pytest.FixtureRequest) -> HTTPXFamilyType: return cast(HTTPXFamilyType, request.param) @contextmanager def check_traceparent_header(): with logfire.set_baggage(baggage_key='baggage_value'), logfire.span('test span') as span: assert span.context trace_id = span.context.trace_id def checker(response: httpx.Response | httpx2.Response): # Validation of context propagation: ensure that the traceparent header contains the trace ID traceparent_header = response.headers['traceparent'] assert f'{trace_id:032x}' == traceparent_header.split('-')[1] assert response.headers['baggage'] == 'baggage_key=baggage_value' yield checker def without_metrics(spans: list[dict[str, Any]]) -> list[dict[str, Any]]: """Remove metrics from spans for comparison.""" for span in spans: span['attributes'].pop('logfire.metrics', None) return spans def test_httpx_client_instrumentation(exporter: TestExporter, httpx_family: HTTPXFamilyType): with check_traceparent_header() as checker: with httpx_family.client() as client: logfire.instrument_httpx(client) response = client.get('https://example.org:8080/foo') checker(response) assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'GET', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 3000000000, 'attributes': { 'http.method': 'GET', 'http.request.method': 'GET', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'GET example.org/foo', 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.target': '/foo', }, }, { 'name': 'test span', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 4000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.lineno': 123, 'code.function': 'check_traceparent_header', 'logfire.msg_template': 'test span', 'logfire.span_type': 'span', 'logfire.msg': 'test span', }, }, ] ) def test_global_httpx_and_httpx2_instrumentation(exporter: TestExporter, monkeypatch: pytest.MonkeyPatch): for family in HTTPX_FAMILIES: family.patch_transport(monkeypatch) try: logfire.instrument_httpx() with check_traceparent_header() as checker: with httpx.Client() as httpx_client: response = httpx_client.get('https://example.org/httpx') checker(response) with httpx2.Client() as httpx2_client: response = httpx2_client.get('https://example.org/httpx2') checker(response) finally: HTTPXClientInstrumentor().uninstrument() HTTPX2ClientInstrumentor().uninstrument() spans = exporter.exported_spans_as_dict(parse_json_attributes=True) assert [span['attributes'].get('url.full') for span in spans] == snapshot( ['https://example.org/httpx', 'https://example.org/httpx2', None] ) def test_global_httpx_instrumentation_with_old_otel(exporter: TestExporter, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(logfire._internal.integrations.httpx, 'HTTPX2ClientInstrumentor', None) HTTPX_CLIENT_FAMILY.patch_transport(monkeypatch) try: with pytest.warns( UserWarning, match='`httpx2` will not be instrumented because it requires ' '`opentelemetry-instrumentation-httpx>=0.65b0`.', ): logfire.instrument_httpx() with httpx.Client() as client: client.get('https://example.org/httpx') finally: HTTPXClientInstrumentor().uninstrument() spans = exporter.exported_spans_as_dict(parse_json_attributes=True) assert [span['attributes']['url.full'] for span in spans] == ['https://example.org/httpx'] def test_httpx2_client_without_httpx_module(exporter: TestExporter, monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(logfire._internal.integrations.httpx, '_httpx', None) with HTTPX2_CLIENT_FAMILY.client() as client: logfire.instrument_httpx(client) client.get('https://example.org/httpx2') spans = exporter.exported_spans_as_dict(parse_json_attributes=True) assert [span['attributes']['url.full'] for span in spans] == ['https://example.org/httpx2'] def test_instrumentors_for_optional_client_modules(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(logfire._internal.integrations.httpx, '_httpx2', None) instrumentors = logfire._internal.integrations.httpx._instrumentors_for_installed_modules() # pyright: ignore[reportPrivateUsage] assert [type(instrumentor) for instrumentor in instrumentors] == [HTTPXClientInstrumentor] monkeypatch.setattr(logfire._internal.integrations.httpx, '_httpx', None) monkeypatch.setattr(logfire._internal.integrations.httpx, '_httpx2', httpx2) instrumentors = logfire._internal.integrations.httpx._instrumentors_for_installed_modules() # pyright: ignore[reportPrivateUsage] assert [type(instrumentor) for instrumentor in instrumentors] == [HTTPX2ClientInstrumentor] monkeypatch.setattr(logfire._internal.integrations.httpx, '_httpx2', None) with pytest.raises(RuntimeError, match='requires either the `httpx` or `httpx2` package'): logfire._internal.integrations.httpx._instrumentors_for_installed_modules() # pyright: ignore[reportPrivateUsage] def test_httpx2_requires_new_otel(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(logfire._internal.integrations.httpx, 'HTTPX2ClientInstrumentor', None) with HTTPX2_CLIENT_FAMILY.client() as client: with pytest.raises(RuntimeError) as exc_info: logfire.instrument_httpx(client) assert str(exc_info.value) == snapshot("""\ Instrumenting `httpx2` requires `opentelemetry-instrumentation-httpx>=0.65b0`. You can update this with: pip install -U 'logfire[httpx]' 'opentelemetry-instrumentation-httpx>=0.65b0'\ """) monkeypatch.setattr(logfire._internal.integrations.httpx, '_httpx', None) with pytest.raises(RuntimeError, match='Instrumenting `httpx2` requires'): logfire.instrument_httpx() def test_invalid_httpx_client(): with pytest.raises(TypeError, match='Expected an `httpx` or `httpx2` client, got object'): logfire.instrument_httpx(cast(Any, object())) @pytest.mark.parametrize('missing_name', ['httpx', 'httpcore']) def test_import_optional_client_module(missing_name: str, monkeypatch: pytest.MonkeyPatch): def import_missing_module(name: str): raise ModuleNotFoundError(name=missing_name) monkeypatch.setattr(logfire._internal.integrations.httpx, 'import_module', import_missing_module) if missing_name == 'httpx': assert ( logfire._internal.integrations.httpx._import_optional_client_module('httpx') # pyright: ignore[reportPrivateUsage] is None ) else: with pytest.raises(ModuleNotFoundError) as exc_info: logfire._internal.integrations.httpx._import_optional_client_module( # pyright: ignore[reportPrivateUsage] 'httpx' ) assert exc_info.value.name == 'httpcore' def test_httpx_client_instrumentation_old_semconv(exporter: TestExporter, httpx_family: HTTPXFamilyType): with mock.patch.dict('os.environ', {'OTEL_SEMCONV_STABILITY_OPT_IN': ''}): with httpx_family.client() as client: # Pick up the new value of OTEL_SEMCONV_STABILITY_OPT_IN _OpenTelemetrySemanticConventionStability._initialized = False # type: ignore logfire.instrument_httpx(client) client.get('https://example.org:8080/foo') # Now let other tests get the original value set in conftest.py _OpenTelemetrySemanticConventionStability._initialized = False # type: ignore assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'GET', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'http.method': 'GET', 'http.url': 'https://example.org:8080/foo', 'logfire.span_type': 'span', 'logfire.msg': 'GET example.org/foo', 'http.status_code': 200, 'http.target': '/foo', }, } ] ) async def test_async_httpx_client_instrumentation(exporter: TestExporter, httpx_family: HTTPXFamilyType): with check_traceparent_header() as checker: async with httpx_family.async_client() as client: logfire.instrument_httpx(client) response = await client.get('https://example.org:8080/foo') checker(response) assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'GET', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 3000000000, 'attributes': { 'http.method': 'GET', 'http.request.method': 'GET', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'GET example.org/foo', 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.target': '/foo', }, }, { 'name': 'test span', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 4000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'check_traceparent_header', 'code.lineno': 123, 'logfire.msg_template': 'test span', 'logfire.msg': 'test span', 'logfire.span_type': 'span', }, }, ] ) def request_hook(span: Span, request: RequestInfo) -> None: span.set_attribute('request_hook', True) def response_hook(span: Span, request: RequestInfo, response: ResponseInfo) -> None: span.set_attribute('response_hook', True) async def async_request_hook(span: Span, request: RequestInfo) -> None: span.set_attribute('async_request_hook', True) async def async_response_hook(span: Span, request: RequestInfo, response: ResponseInfo) -> None: span.set_attribute('async_response_hook', True) REQUEST_ATTRIBUTES = { 'http.request.header.host', 'http.request.header.accept', 'http.request.header.accept-encoding', 'http.request.header.connection', 'http.request.header.user-agent', } RESPONSE_ATTRIBUTES = { 'http.response.header.host', 'http.response.header.accept', 'http.response.header.accept-encoding', 'http.response.header.connection', 'http.response.header.user-agent', 'http.response.header.traceparent', } @pytest.mark.parametrize( ('instrument_kwargs', 'expected_attributes'), [ ({'capture_headers': True}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES}), ( {'capture_headers': True, 'request_hook': request_hook}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES, 'request_hook'}, ), ({'capture_headers': False, 'request_hook': request_hook}, {'request_hook'}), ( {'capture_headers': True, 'response_hook': response_hook}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES, 'response_hook'}, ), ({'capture_headers': False, 'response_hook': response_hook}, {'response_hook'}), ], ) def test_httpx_client_instrumentation_with_capture_headers( exporter: TestExporter, httpx_family: HTTPXFamilyType, instrument_kwargs: dict[str, Any], expected_attributes: set[str], ): with check_traceparent_header() as checker: with httpx_family.client() as client: logfire.instrument_httpx(client, **instrument_kwargs) response = client.get('https://example.org:8080/foo') checker(response) span = exporter.exported_spans_as_dict(parse_json_attributes=True)[0] assert all(key in span['attributes'] for key in expected_attributes), list(span['attributes']) @pytest.mark.parametrize( ('instrument_kwargs', 'expected_attributes'), [ ({'capture_headers': True}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES}), ( {'capture_headers': True, 'request_hook': request_hook}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES, 'request_hook'}, ), ({'capture_headers': False, 'request_hook': request_hook}, {'request_hook'}), ( {'capture_headers': True, 'response_hook': response_hook}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES, 'response_hook'}, ), ({'capture_headers': False, 'response_hook': response_hook}, {'response_hook'}), ( {'capture_headers': True, 'request_hook': async_request_hook}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES, 'async_request_hook'}, ), ( {'capture_headers': True, 'response_hook': async_response_hook}, {*REQUEST_ATTRIBUTES, *RESPONSE_ATTRIBUTES, 'async_response_hook'}, ), ], ) async def test_async_httpx_client_instrumentation_with_capture_headers( exporter: TestExporter, httpx_family: HTTPXFamilyType, instrument_kwargs: dict[str, Any], expected_attributes: set[str], ): with check_traceparent_header() as checker: async with httpx_family.async_client() as client: logfire.instrument_httpx(client, **instrument_kwargs) response = await client.get('https://example.org:8080/foo') checker(response) span = exporter.exported_spans_as_dict(parse_json_attributes=True)[0] assert all(key in span['attributes'] for key in expected_attributes) @pytest.mark.parametrize('removed_parameter', ['capture_request_headers', 'capture_response_headers']) def test_removed_capture_header_parameters(removed_parameter: str, httpx_family: HTTPXFamilyType): expected_message = f'The `{removed_parameter}` parameter has been removed. Use `capture_headers` instead.' with warnings.catch_warnings(): warnings.simplefilter('error') with pytest.raises(TypeError) as exc_info: cast(Any, logfire.instrument_httpx)(capture_all=True, capture_headers=True, **{removed_parameter: True}) assert str(exc_info.value) == expected_message with httpx_family.client() as client: with pytest.raises(TypeError) as exc_info: cast(Any, logfire.instrument_httpx)(client, **{removed_parameter: True}) assert str(exc_info.value) == expected_message CAPTURE_JSON_BODY_PARAMETERS: tuple[tuple[str, ...], list[Any]] = ( ('content_type', 'body', 'expected_http_request_body_text'), [ ('application/json', '{"hello": "world"}', '{"hello": "world"}'), ('application/json; charset=utf-8', '{"hello": "world"}', '{"hello": "world"}'), ('application/json; charset=iso-8859-1', '{"hello": "world"}', '{"hello": "world"}'), ('application/json; charset=utf-32', '{"hello": "world"}', None), ('application/json; charset=potato', '{"hello": "world"}', None), ('application/json; charset=ascii', b'\x80\x81\x82', None), ('application/json; charset=utf8', b'\x80\x81\x82', None), ('text/plain', '{"hello": "world"}', '{"hello": "world"}'), ('', '{"hello": "world"}', '{"hello": "world"}'), ], ) @pytest.mark.parametrize(*CAPTURE_JSON_BODY_PARAMETERS) def test_httpx_client_instrumentation_with_capture_json_body( exporter: TestExporter, httpx_family: HTTPXFamilyType, content_type: str, body: Any, expected_http_request_body_text: str, ): with check_traceparent_header() as checker: with httpx_family.client() as client: logfire.instrument_httpx(client, capture_request_body=True) headers = {'Content-Type': content_type} if content_type else {} response = client.post('https://example.org:8080/foo', headers=headers, content=body) checker(response) span = exporter.exported_spans_as_dict()[0] assert span['attributes'].get('http.request.body.text') == expected_http_request_body_text @pytest.mark.parametrize(*CAPTURE_JSON_BODY_PARAMETERS) async def test_async_httpx_client_instrumentation_with_capture_json_body( exporter: TestExporter, httpx_family: HTTPXFamilyType, content_type: str, body: Any, expected_http_request_body_text: str, ): with check_traceparent_header() as checker: async with httpx_family.async_client() as client: logfire.instrument_httpx(client, capture_request_body=True) response = await client.post( 'https://example.org:8080/foo', headers={'Content-Type': content_type}, content=body ) checker(response) span = exporter.exported_spans_as_dict()[0] assert span['attributes'].get('http.request.body.text') == expected_http_request_body_text CAPTURE_FULL_REQUEST_ATTRIBUTES = { *REQUEST_ATTRIBUTES, 'http.request.header.content-type', 'http.request.header.content-length', 'http.request.body.text', } def test_httpx_client_capture_stream_body(exporter: TestExporter, httpx_family: HTTPXFamilyType): def stream(): yield b'{"hello": ' yield b'"world"}' with check_traceparent_header() as checker: with httpx_family.client() as client: logfire.instrument_httpx(client, capture_request_body=True) response = client.post( 'https://example.org:8080/foo', headers={'Content-Type': 'application/json'}, content=stream() ) checker(response) span = exporter.exported_spans_as_dict(parse_json_attributes=True)[0] # Streaming bodies aren't captured assert 'http.request.body.json' not in span['attributes'] def test_httpx_client_capture_full_request(exporter: TestExporter, httpx_family: HTTPXFamilyType): with check_traceparent_header() as checker: with httpx_family.client() as client: logfire.instrument_httpx(client, capture_headers=True, capture_request_body=True) response = client.post('https://example.org:8080/foo', json={'hello': 'world'}) checker(response) span = exporter.exported_spans_as_dict(parse_json_attributes=True)[0] assert all(key in span['attributes'] for key in CAPTURE_FULL_REQUEST_ATTRIBUTES) async def test_async_httpx_client_capture_full_request(exporter: TestExporter, httpx_family: HTTPXFamilyType): with check_traceparent_header() as checker: async with httpx_family.async_client() as client: logfire.instrument_httpx(client, capture_headers=True, capture_request_body=True) response = await client.post('https://example.org:8080/foo', json={'hello': 'world'}) checker(response) span = exporter.exported_spans_as_dict(parse_json_attributes=True)[0] assert all(key in span['attributes'] for key in CAPTURE_FULL_REQUEST_ATTRIBUTES) def test_httpx_client_capture_full(exporter: TestExporter, httpx_family: HTTPXFamilyType): with check_traceparent_header() as checker: with httpx_family.client() as client: logfire.instrument_httpx( client, capture_headers=True, capture_request_body=True, capture_response_body=True ) response = client.post('https://example.org:8080/foo', json={'hello': 'world'}) checker(response) assert response.json() == {'good': 'response'} assert response.read() == b'{"good": "response"}' assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'POST', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 3000000000, 'attributes': { 'http.method': 'POST', 'http.request.method': 'POST', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'POST example.org/foo', 'http.request.header.host': ('example.org:8080',), 'http.request.header.accept': ('*/*',), 'http.request.header.accept-encoding': ( IsAnyStr(regex='^gzip, deflate(?:, br|, zstd|, br, zstd)?$'), ), 'http.request.header.connection': ('keep-alive',), 'http.request.header.user-agent': (IsStr(),), 'http.request.header.content-length': (IsStr(),), 'http.request.header.content-type': ('application/json',), 'logfire.json_schema': { 'type': 'object', 'properties': {'http.request.body.text': {'type': 'object'}}, }, 'http.request.body.text': {'hello': 'world'}, 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.response.header.host': ('example.org:8080',), 'http.response.header.accept': ('*/*',), 'http.response.header.accept-encoding': ( IsAnyStr(regex='^gzip, deflate(?:, br|, zstd|, br, zstd)?$'), ), 'http.response.header.connection': ('keep-alive',), 'http.response.header.user-agent': (IsStr(),), 'http.response.header.content-length': (IsStr(),), 'http.response.header.content-type': ('application/json',), 'http.response.header.traceparent': ('00-00000000000000000000000000000001-0000000000000003-01',), 'http.response.header.baggage': ('baggage_key=baggage_value',), 'http.target': '/foo', }, }, { 'name': 'Reading response body', 'context': {'trace_id': 1, 'span_id': 5, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 4000000000, 'end_time': 5000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'test_httpx_client_capture_full', 'code.lineno': 123, 'logfire.msg_template': 'Reading response body', 'logfire.msg': 'Reading response body', 'logfire.span_type': 'span', 'http.response.body.text': {'good': 'response'}, 'logfire.json_schema': { 'type': 'object', 'properties': {'http.response.body.text': {'type': 'object'}}, }, }, }, { 'name': 'test span', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 6000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'check_traceparent_header', 'code.lineno': 123, 'logfire.msg_template': 'test span', 'logfire.msg': 'test span', 'logfire.span_type': 'span', }, }, ] ) async def test_async_httpx_client_capture_full(exporter: TestExporter, httpx_family: HTTPXFamilyType): with check_traceparent_header() as checker: async with httpx_family.async_client() as client: logfire.instrument_httpx( client, capture_headers=True, capture_request_body=True, capture_response_body=True ) response = await client.post('https://example.org:8080/foo', json={'hello': 'world'}) checker(response) assert response.json() == {'good': 'response'} assert await response.aread() == b'{"good": "response"}' assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'POST', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 3000000000, 'attributes': { 'http.method': 'POST', 'http.request.method': 'POST', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'POST example.org/foo', 'http.request.header.host': ('example.org:8080',), 'http.request.header.accept': ('*/*',), 'http.request.header.accept-encoding': ( IsAnyStr(regex='^gzip, deflate(?:, br|, zstd|, br, zstd)?$'), ), 'http.request.header.connection': ('keep-alive',), 'http.request.header.user-agent': (IsStr(),), 'http.request.header.content-length': (IsStr(),), 'http.request.header.content-type': ('application/json',), 'logfire.json_schema': { 'type': 'object', 'properties': {'http.request.body.text': {'type': 'object'}}, }, 'http.request.body.text': {'hello': 'world'}, 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.response.header.host': ('example.org:8080',), 'http.response.header.accept': ('*/*',), 'http.response.header.accept-encoding': ( IsAnyStr(regex='^gzip, deflate(?:, br|, zstd|, br, zstd)?$'), ), 'http.response.header.connection': ('keep-alive',), 'http.response.header.user-agent': (IsStr(),), 'http.response.header.content-length': (IsStr(),), 'http.response.header.content-type': ('application/json',), 'http.response.header.traceparent': ('00-00000000000000000000000000000001-0000000000000003-01',), 'http.response.header.baggage': ('baggage_key=baggage_value',), 'http.target': '/foo', }, }, { 'name': 'Reading response body', 'context': {'trace_id': 1, 'span_id': 5, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 4000000000, 'end_time': 5000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'test_async_httpx_client_capture_full', 'code.lineno': 123, 'logfire.msg_template': 'Reading response body', 'logfire.msg': 'Reading response body', 'logfire.span_type': 'span', 'http.response.body.text': {'good': 'response'}, 'logfire.json_schema': { 'type': 'object', 'properties': {'http.response.body.text': {'type': 'object'}}, }, }, }, { 'name': 'test span', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 6000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'check_traceparent_header', 'code.lineno': 123, 'logfire.msg_template': 'test span', 'logfire.msg': 'test span', 'logfire.span_type': 'span', }, }, ] ) def test_httpx_client_not_capture_response_body_on_wrong_encoding( exporter: TestExporter, httpx_family: HTTPXFamilyType ): with check_traceparent_header() as checker: with httpx_family.client(response_body=b'\x80\x81\x82') as client: logfire.instrument_httpx(client, capture_response_body=True) response = client.post('https://example.org:8080/foo') checker(response) assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'POST', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 3000000000, 'attributes': { 'http.method': 'POST', 'http.request.method': 'POST', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'POST example.org/foo', 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.target': '/foo', }, }, { 'name': 'Reading response body', 'context': {'trace_id': 1, 'span_id': 5, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 4000000000, 'end_time': 5000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'test_httpx_client_not_capture_response_body_on_wrong_encoding', 'code.lineno': 123, 'logfire.msg_template': 'Reading response body', 'logfire.msg': 'Reading response body', 'logfire.span_type': 'span', }, }, { 'name': 'test span', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 6000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'check_traceparent_header', 'code.lineno': 123, 'logfire.msg_template': 'test span', 'logfire.msg': 'test span', 'logfire.span_type': 'span', }, }, ] ) def test_codes_for_methods_with_data_param(): assert len({code.co_filename for code in CODES_FOR_METHODS_WITH_DATA_PARAM}) == 2 assert [code.co_name for code in CODES_FOR_METHODS_WITH_DATA_PARAM] == [ 'request', 'stream', 'request', 'stream', 'request', 'stream', 'request', 'stream', ] def test_httpx_client_capture_request_form_data(exporter: TestExporter, httpx_family: HTTPXFamilyType): with httpx_family.client() as client: logfire.instrument_httpx(client, capture_request_body=True) client.post('https://example.org:8080/foo', data={'form': 'values'}) assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'POST', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'http.method': 'POST', 'http.request.method': 'POST', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'POST example.org/foo', 'http.request.body.form': {'form': 'values'}, 'logfire.json_schema': { 'type': 'object', 'properties': {'http.request.body.form': {'type': 'object'}}, }, 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.target': '/foo', }, } ] ) def test_httpx_client_capture_request_text_body(exporter: TestExporter, httpx_family: HTTPXFamilyType): with httpx_family.client() as client: logfire.instrument_httpx(client, capture_request_body=True) client.post('https://example.org:8080/foo', headers={'Content-Type': 'text/plain'}, content='hello') assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'POST', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'http.method': 'POST', 'http.request.method': 'POST', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'POST example.org/foo', 'logfire.json_schema': { 'type': 'object', 'properties': {'http.request.body.text': {'type': 'object'}}, }, 'http.request.body.text': 'hello', 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.target': '/foo', }, } ] ) def test_is_json_type(): assert is_json_type('application/json') assert is_json_type(' APPLICATION / JSON ') assert is_json_type('application/json; charset=utf-8') assert is_json_type('application/json; charset=potato; foo=bar') assert is_json_type('application/json+ld') assert is_json_type('application/x-json+ld') assert is_json_type('application/ld+xml+json') assert not is_json_type('json') assert not is_json_type('json/application') assert not is_json_type('text/json') assert not is_json_type('other/json') assert not is_json_type('') assert not is_json_type('application/json-x') assert not is_json_type('application//json') async def test_httpx_client_capture_all(exporter: TestExporter, httpx_family: HTTPXFamilyType): with check_traceparent_header() as checker: async with httpx_family.async_client() as client: logfire.instrument_httpx(client, capture_all=True) response = await client.post('https://example.org:8080/foo', json={'hello': 'world'}) checker(response) assert response.json() == {'good': 'response'} assert await response.aread() == b'{"good": "response"}' assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'POST', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 2000000000, 'end_time': 3000000000, 'attributes': { 'http.method': 'POST', 'http.request.method': 'POST', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'POST example.org/foo', 'http.request.header.host': ('example.org:8080',), 'http.request.header.accept': ('*/*',), 'http.request.header.accept-encoding': ( IsAnyStr(regex='^gzip, deflate(?:, br|, zstd|, br, zstd)?$'), ), 'http.request.header.connection': ('keep-alive',), 'http.request.header.user-agent': (IsAnyStr(regex=r'^python-httpx2?/\d+(?:\.\d+)+$'),), 'http.request.header.content-length': ('17',), 'http.request.header.content-type': ('application/json',), 'logfire.json_schema': { 'type': 'object', 'properties': {'http.request.body.text': {'type': 'object'}}, }, 'http.request.body.text': {'hello': 'world'}, 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.response.header.host': ('example.org:8080',), 'http.response.header.accept': ('*/*',), 'http.response.header.accept-encoding': ( IsAnyStr(regex='^gzip, deflate(?:, br|, zstd|, br, zstd)?$'), ), 'http.response.header.connection': ('keep-alive',), 'http.response.header.user-agent': (IsAnyStr(regex=r'^python-httpx2?/\d+(?:\.\d+)+$'),), 'http.response.header.content-length': ('17',), 'http.response.header.content-type': ('application/json',), 'http.response.header.traceparent': ('00-00000000000000000000000000000001-0000000000000003-01',), 'http.response.header.baggage': ('baggage_key=baggage_value',), 'http.target': '/foo', }, }, { 'name': 'Reading response body', 'context': {'trace_id': 1, 'span_id': 5, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'start_time': 4000000000, 'end_time': 5000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'test_httpx_client_capture_all', 'code.lineno': 123, 'logfire.msg_template': 'Reading response body', 'logfire.msg': 'Reading response body', 'logfire.span_type': 'span', 'http.response.body.text': {'good': 'response'}, 'logfire.json_schema': { 'type': 'object', 'properties': {'http.response.body.text': {'type': 'object'}}, }, }, }, { 'name': 'test span', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 6000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'check_traceparent_header', 'code.lineno': 123, 'logfire.msg_template': 'test span', 'logfire.msg': 'test span', 'logfire.span_type': 'span', }, }, ] ) async def test_httpx_client_capture_all_environment_variable(exporter: TestExporter, httpx_family: HTTPXFamilyType): with mock.patch.dict(os.environ, {'LOGFIRE_HTTPX_CAPTURE_ALL': 'true'}): async with httpx_family.async_client() as client: logfire.instrument_httpx(client) response = await client.get('https://example.org:8080/foo') assert response.json() == {'good': 'response'} assert await response.aread() == b'{"good": "response"}' accept_encoding = response.request.headers['accept-encoding'] assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'GET', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'http.method': 'GET', 'http.request.method': 'GET', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'GET example.org/foo', 'http.request.header.host': ('example.org:8080',), 'http.request.header.accept': ('*/*',), 'http.request.header.accept-encoding': (Is(accept_encoding),), 'http.request.header.connection': ('keep-alive',), 'http.request.header.user-agent': (IsAnyStr(regex=r'^python-httpx2?/\d+(?:\.\d+)+$'),), 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.response.header.host': ('example.org:8080',), 'http.response.header.accept': ('*/*',), 'http.response.header.accept-encoding': (Is(accept_encoding),), 'http.response.header.connection': ('keep-alive',), 'http.response.header.user-agent': (IsAnyStr(regex=r'^python-httpx2?/\d+(?:\.\d+)+$'),), 'http.response.header.traceparent': ('00-00000000000000000000000000000001-0000000000000001-01',), 'http.target': '/foo', }, }, { 'name': 'Reading response body', 'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False}, 'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'start_time': 3000000000, 'end_time': 4000000000, 'attributes': { 'code.filepath': 'test_httpx.py', 'code.function': 'test_httpx_client_capture_all_environment_variable', 'code.lineno': 123, 'logfire.msg_template': 'Reading response body', 'logfire.msg': 'Reading response body', 'logfire.span_type': 'span', 'http.response.body.text': {'good': 'response'}, 'logfire.json_schema': { 'type': 'object', 'properties': {'http.response.body.text': {'type': 'object'}}, }, }, }, ] ) async def test_httpx_client_no_capture_empty_body(exporter: TestExporter, httpx_family: HTTPXFamilyType): async with httpx_family.async_client() as client: logfire.instrument_httpx(client, capture_request_body=True) await client.get('https://example.org:8080/foo') assert without_metrics(exporter.exported_spans_as_dict(parse_json_attributes=True)) == snapshot( [ { 'name': 'GET', 'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, 'parent': None, 'start_time': 1000000000, 'end_time': 2000000000, 'attributes': { 'http.method': 'GET', 'http.request.method': 'GET', 'http.url': 'https://example.org:8080/foo', 'url.full': 'https://example.org:8080/foo', 'http.host': 'example.org', 'server.address': 'example.org', 'network.peer.address': 'example.org', 'net.peer.port': 8080, 'server.port': 8080, 'network.peer.port': 8080, 'logfire.span_type': 'span', 'logfire.msg': 'GET example.org/foo', 'http.status_code': 200, 'http.response.status_code': 200, 'http.flavor': '1.1', 'network.protocol.version': '1.1', 'http.target': '/foo', }, } ] ) def test_httpx_capture_all_and_other_flags_should_warn(exporter: TestExporter, httpx_family: HTTPXFamilyType): with httpx_family.client() as client: with pytest.warns( UserWarning, match='You should use either `capture_all` or the specific capture parameters, not both.' ): logfire.instrument_httpx(client, capture_all=True, capture_request_body=True) def test_missing_opentelemetry_dependency(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delattr(importlib.import_module('opentelemetry.instrumentation'), 'httpx') with mock.patch.dict('sys.modules', {'opentelemetry.instrumentation.httpx': None}): with pytest.raises(RuntimeError) as exc_info: importlib.reload(logfire._internal.integrations.httpx) assert str(exc_info.value) == snapshot("""\ `logfire.instrument_httpx()` requires the `opentelemetry-instrumentation-httpx` package. You can install this with: pip install 'logfire[httpx]'\ """)
from __future__ import annotations
import importlib
import os
import warnings
from abc import ABC, abstractmethod
from contextlib import contextmanager
from typing import Any, Generic, TypeAlias, TypeVar, cast
from unittest import mock
import httpx
import httpx2
import pytest
from dirty_equals import IsAnyStr, IsStr
from inline_snapshot import Is, snapshot
from opentelemetry.instrumentation._semconv import _OpenTelemetrySemanticConventionStability # type: ignore
from opentelemetry.instrumentation.httpx import (
HTTPX2ClientInstrumentor,
HTTPXClientInstrumentor,
RequestInfo,
ResponseInfo,
)
from opentelemetry.trace.span import Span
import logfire
import logfire._internal.integrations.httpx
from logfire._internal.integrations.httpx import CODES_FOR_METHODS_WITH_DATA_PARAM, is_json_type
from logfire.testing import TestExporter
pytestmark = pytest.mark.anyio
RESPONSE_BODY = b'{"good": "response"}'
RequestT = TypeVar('RequestT', httpx.Request, httpx2.Request)
ResponseT = TypeVar('ResponseT', httpx.Response, httpx2.Response)
class HTTPXFamily(ABC, Generic[RequestT, ResponseT]):
name: str
@staticmethod
@abstractmethod
def response_handler(request: RequestT, response_body: bytes = RESPONSE_BODY) -> ResponseT:
raise NotImplementedError
@staticmethod
@abstractmethod
def transport_response_handler(_transport: object, request: RequestT) -> ResponseT:
raise NotImplementedError
@abstractmethod
def create_transport(self, response_body: bytes = RESPONSE_BODY) -> httpx.MockTransport | httpx2.MockTransport:
raise NotImplementedError
@abstractmethod
def patch_transport(self, monkeypatch: pytest.MonkeyPatch) -> None:
raise NotImplementedError
@abstractmethod
def client(self, response_body: bytes = RESPONSE_BODY) -> httpx.Client | httpx2.Client:
raise NotImplementedError
@abstractmethod
def async_client(self, response_body: bytes = RESPONSE_BODY) -> httpx.AsyncClient | httpx2.AsyncClient:
raise NotImplementedError
class HTTPXClientFamily(HTTPXFamily[httpx.Request, httpx.Response]):
name = 'httpx'
@staticmethod
def response_handler(request: httpx.Request, response_body: bytes = RESPONSE_BODY) -> httpx.Response:
return httpx.Response(200, headers=request.headers, stream=httpx.ByteStream(response_body))
@staticmethod
def transport_response_handler(_transport: object, request: httpx.Request) -> httpx.Response:
return HTTPXClientFamily.response_handler(request)
def create_transport(self, response_body: bytes = RESPONSE_BODY) -> httpx.MockTransport:
return httpx.MockTransport(lambda request: self.response_handler(request, response_body))
def patch_transport(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(httpx.HTTPTransport, 'handle_request', self.transport_response_handler)
def client(self, response_body: bytes = RESPONSE_BODY) -> httpx.Client:
return httpx.Client(transport=self.create_transport(response_body))
def async_client(self, response_body: bytes = RESPONSE_BODY) -> httpx.AsyncClient:
return httpx.AsyncClient(transport=self.create_transport(response_body))
class HTTPX2ClientFamily(HTTPXFamily[httpx2.Request, httpx2.Response]):
name = 'httpx2'
@staticmethod
def response_handler(request: httpx2.Request, response_body: bytes = RESPONSE_BODY) -> httpx2.Response:
return httpx2.Response(200, headers=request.headers, stream=httpx2.ByteStream(response_body))
@staticmethod
def transport_response_handler(_transport: object, request: httpx2.Request) -> httpx2.Response:

Xet Storage Details

Size:
55.9 kB
·
Xet hash:
d1e737178ae6a09c9aba9ad86a91b31e4adc212693f323a63861dcd06cd37eec

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.