Skip to content

Commit

Permalink
Wrap calculation of protobuf package version in a try/catch (#857)
Browse files Browse the repository at this point in the history
  • Loading branch information
BenRKarl authored Apr 15, 2024
1 parent 6d42d38 commit 4e923a8
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
5 changes: 4 additions & 1 deletion google/ads/googleads/interceptors/metadata_interceptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
# https://github.com/googleapis/python-api-core/issues/416
from importlib import metadata

_PROTOBUF_VERSION = metadata.version("protobuf")
try:
_PROTOBUF_VERSION = metadata.version("protobuf")
except metadata.PackageNotFoundError:
_PROTOBUF_VERSION = None


from google.protobuf.internal import api_implementation
Expand Down
46 changes: 46 additions & 0 deletions tests/interceptors/metadata_interceptor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,52 @@ def mock_continuation(client_call_details, request):
# value pair because it was already present when passed in.
self.assertEqual(user_agent.count("pb"), 1)

@mock.patch(
"google.ads.googleads.interceptors.metadata_interceptor._PROTOBUF_VERSION",
None,
)
def test_absent_pb_version(self):
"""Asserts that the protobuf package version is left out if not present.
In a situation where the `metadata` package cannot find a version for
the `protobuf` package, we assert that the "pb/x.y.x" substring is left
out of the user agent of the request.
"""
interceptor = MetadataInterceptor(
self.mock_developer_token,
self.mock_login_customer_id,
self.mock_linked_customer_id,
)

mock_request = mock.Mock()
mock_client_call_details = mock.Mock()
mock_client_call_details.method = "test/method"
mock_client_call_details.timeout = 5
mock_client_call_details.metadata = [
("apples", "oranges"),
(
"x-goog-api-client",
f"gl-python/{self.python_version} grpc/1.45.0",
),
]

def mock_continuation(client_call_details, _):
return client_call_details

with mock.patch.object(
interceptor,
"_update_client_call_details_metadata",
wraps=interceptor._update_client_call_details_metadata,
):
modified_client_call_details = interceptor._intercept(
mock_continuation, mock_client_call_details, mock_request
)

user_agent = modified_client_call_details.metadata[1][1]
# We assert that the _intercept method did not add the "pb" key
# value pair because it was already present when passed in.
self.assertEqual(user_agent.count("pb"), 0)

def test_intercept_unary_stream_use_cloud_org_for_api_access(self):
interceptor = MetadataInterceptor(
self.mock_developer_token,
Expand Down

0 comments on commit 4e923a8

Please sign in to comment.