From 0d5ed37c96f9b40bccae98e228163a88abeb1763 Mon Sep 17 00:00:00 2001 From: Mark Daoust Date: Tue, 22 Oct 2024 07:24:59 -0700 Subject: [PATCH] fix: Improve `Any` decode error (#712) * Improve Any decoding-error. Was: TypeError: Could not convert Any to PredictLongRunningResponse Now: TypeError: Could not convert Any[google.ai.generativelanguage.v1main.PredictLongRunningResponse] to google.ai.generativelanguage.v1beta.PredictLongRunningResponse * update test * update error message * address review feedback --------- Co-authored-by: Anthonios Partheniou --- google/api_core/protobuf_helpers.py | 4 +--- tests/unit/test_protobuf_helpers.py | 8 +++++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/google/api_core/protobuf_helpers.py b/google/api_core/protobuf_helpers.py index d777c5f8..30cd7c85 100644 --- a/google/api_core/protobuf_helpers.py +++ b/google/api_core/protobuf_helpers.py @@ -63,9 +63,7 @@ def from_any_pb(pb_type, any_pb): # Unpack the Any object and populate the protobuf message instance. if not any_pb.Unpack(msg_pb): raise TypeError( - "Could not convert {} to {}".format( - any_pb.__class__.__name__, pb_type.__name__ - ) + f"Could not convert `{any_pb.TypeName()}` with underlying type `google.protobuf.any_pb2.Any` to `{msg_pb.DESCRIPTOR.full_name}`" ) # Done; return the message. diff --git a/tests/unit/test_protobuf_helpers.py b/tests/unit/test_protobuf_helpers.py index 5b2c6dfd..5678d3bc 100644 --- a/tests/unit/test_protobuf_helpers.py +++ b/tests/unit/test_protobuf_helpers.py @@ -13,6 +13,7 @@ # limitations under the License. import pytest +import re from google.api import http_pb2 from google.api_core import protobuf_helpers @@ -65,7 +66,12 @@ def test_from_any_pb_failure(): in_message = any_pb2.Any() in_message.Pack(date_pb2.Date(year=1990)) - with pytest.raises(TypeError): + with pytest.raises( + TypeError, + match=re.escape( + "Could not convert `google.type.Date` with underlying type `google.protobuf.any_pb2.Any` to `google.type.TimeOfDay`" + ), + ): protobuf_helpers.from_any_pb(timeofday_pb2.TimeOfDay, in_message)