Skip to content

Commit 4e923a8

Browse files
authored
Wrap calculation of protobuf package version in a try/catch (#857)
1 parent 6d42d38 commit 4e923a8

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

google/ads/googleads/interceptors/metadata_interceptor.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@
2525
# https://github.com/googleapis/python-api-core/issues/416
2626
from importlib import metadata
2727

28-
_PROTOBUF_VERSION = metadata.version("protobuf")
28+
try:
29+
_PROTOBUF_VERSION = metadata.version("protobuf")
30+
except metadata.PackageNotFoundError:
31+
_PROTOBUF_VERSION = None
2932

3033

3134
from google.protobuf.internal import api_implementation

tests/interceptors/metadata_interceptor_test.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,52 @@ def mock_continuation(client_call_details, request):
239239
# value pair because it was already present when passed in.
240240
self.assertEqual(user_agent.count("pb"), 1)
241241

242+
@mock.patch(
243+
"google.ads.googleads.interceptors.metadata_interceptor._PROTOBUF_VERSION",
244+
None,
245+
)
246+
def test_absent_pb_version(self):
247+
"""Asserts that the protobuf package version is left out if not present.
248+
249+
In a situation where the `metadata` package cannot find a version for
250+
the `protobuf` package, we assert that the "pb/x.y.x" substring is left
251+
out of the user agent of the request.
252+
"""
253+
interceptor = MetadataInterceptor(
254+
self.mock_developer_token,
255+
self.mock_login_customer_id,
256+
self.mock_linked_customer_id,
257+
)
258+
259+
mock_request = mock.Mock()
260+
mock_client_call_details = mock.Mock()
261+
mock_client_call_details.method = "test/method"
262+
mock_client_call_details.timeout = 5
263+
mock_client_call_details.metadata = [
264+
("apples", "oranges"),
265+
(
266+
"x-goog-api-client",
267+
f"gl-python/{self.python_version} grpc/1.45.0",
268+
),
269+
]
270+
271+
def mock_continuation(client_call_details, _):
272+
return client_call_details
273+
274+
with mock.patch.object(
275+
interceptor,
276+
"_update_client_call_details_metadata",
277+
wraps=interceptor._update_client_call_details_metadata,
278+
):
279+
modified_client_call_details = interceptor._intercept(
280+
mock_continuation, mock_client_call_details, mock_request
281+
)
282+
283+
user_agent = modified_client_call_details.metadata[1][1]
284+
# We assert that the _intercept method did not add the "pb" key
285+
# value pair because it was already present when passed in.
286+
self.assertEqual(user_agent.count("pb"), 0)
287+
242288
def test_intercept_unary_stream_use_cloud_org_for_api_access(self):
243289
interceptor = MetadataInterceptor(
244290
self.mock_developer_token,

0 commit comments

Comments
 (0)