From 340ab6aa9c15925a28aed34de5c595cbeb012be0 Mon Sep 17 00:00:00 2001 From: Devin Fallak Date: Fri, 20 Sep 2024 11:34:56 -0700 Subject: [PATCH] Handle nonexistent properties --- pyramid_zipkin/request_helper.py | 27 +++++++++++++++++++-------- tests/request_helper_test.py | 17 +++++++++++++++++ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/pyramid_zipkin/request_helper.py b/pyramid_zipkin/request_helper.py index 73424d0..0c018b1 100644 --- a/pyramid_zipkin/request_helper.py +++ b/pyramid_zipkin/request_helper.py @@ -157,6 +157,16 @@ def create_zipkin_attr(request: Request) -> ZipkinAttrs: ) +def safe_get_property( + obj: Request, + prop: str, + default: str) -> Optional[str]: + try: + return getattr(obj, prop) + except KeyError: + return default + + def get_binary_annotations( request: Request, response: Response, @@ -169,14 +179,15 @@ def get_binary_annotations( """ annotations = { - 'http.request.method': request.method, - 'network.protocol.version': request.http_version, - 'url.path': request.path, - 'server.address': request.server_name, - 'server.port': str(request.server_port), - 'url.scheme': request.scheme, - 'http.uri': request.path, - 'http.uri.qs': request.path_qs, + 'http.request.method': safe_get_property(request, 'method', 'unknown'), + 'network.protocol.version': + safe_get_property(request, 'http_version', 'unknown'), + 'url.path': safe_get_property(request, 'path', 'unknown'), + 'server.address': safe_get_property(request, 'server_name', 'unknown'), + 'server.port': str(safe_get_property(request, 'server_port', 'unknown')), + 'url.scheme': safe_get_property(request, 'scheme', 'unknown'), + 'http.uri': safe_get_property(request, 'path', 'unknown'), + 'http.uri.qs': safe_get_property(request, 'path_qs', 'unknown'), 'otel.library.name': __name__.split('.')[0], 'otel.library.version': __version__, } diff --git a/tests/request_helper_test.py b/tests/request_helper_test.py index e616539..23261f0 100644 --- a/tests/request_helper_test.py +++ b/tests/request_helper_test.py @@ -1,5 +1,8 @@ from unittest import mock +from pyramid.registry import Registry +from pyramid.request import Request + from pyramid_zipkin import request_helper @@ -181,3 +184,17 @@ def test_convert_signed_hex(): request_helper._convert_signed_hex('-0x3ab5151d76fb85e1') == 'c54aeae289047a1f' ) + + +def test_request_has_no_server_protocol(get_request): + class TestRequest(Request): + http_version = property(fget=lambda a: {}["SERVER_PROTOCOL"]) + + testRequest = TestRequest.blank("GET /") + testRequest.registry = Registry() + testRequest.registry.settings = {} + + try: + request_helper.get_binary_annotations(testRequest, None) + except KeyError: + assert False