Skip to content

Commit

Permalink
Handle nonexistent properties
Browse files Browse the repository at this point in the history
  • Loading branch information
dmfallak committed Sep 20, 2024
1 parent 26d933e commit 340ab6a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
27 changes: 19 additions & 8 deletions pyramid_zipkin/request_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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__,
}
Expand Down
17 changes: 17 additions & 0 deletions tests/request_helper_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from unittest import mock

from pyramid.registry import Registry
from pyramid.request import Request

from pyramid_zipkin import request_helper


Expand Down Expand Up @@ -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

0 comments on commit 340ab6a

Please sign in to comment.