Skip to content

Commit 47a5723

Browse files
lukesneeringercrwilcox
authored andcommitted
Add support to unwrap Anys into wrapped pb2 objects. (#7430)
This commit adds support for unwrapping wrapped pb2 objects from Anys (needed for LRO support with wrapping).
1 parent d9c3be1 commit 47a5723

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

google/api_core/protobuf_helpers.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,22 @@ def from_any_pb(pb_type, any_pb):
5555
TypeError: if the message could not be converted.
5656
"""
5757
msg = pb_type()
58-
if not any_pb.Unpack(msg):
58+
59+
# Unwrap proto-plus wrapped messages.
60+
if callable(getattr(pb_type, "pb", None)):
61+
msg_pb = pb_type.pb(msg)
62+
else:
63+
msg_pb = msg
64+
65+
# Unpack the Any object and populate the protobuf message instance.
66+
if not any_pb.Unpack(msg_pb):
5967
raise TypeError(
6068
"Could not convert {} to {}".format(
6169
any_pb.__class__.__name__, pb_type.__name__
6270
)
6371
)
6472

73+
# Done; return the message.
6574
return msg
6675

6776

tests/unit/test_protobuf_helpers.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,29 @@ def test_from_any_pb_success():
3838
assert in_message == out_message
3939

4040

41+
def test_from_any_pb_wrapped_success():
42+
# Declare a message class conforming to wrapped messages.
43+
class WrappedDate(object):
44+
def __init__(self, **kwargs):
45+
self._pb = date_pb2.Date(**kwargs)
46+
47+
def __eq__(self, other):
48+
return self._pb == other
49+
50+
@classmethod
51+
def pb(cls, msg):
52+
return msg._pb
53+
54+
# Run the same test as `test_from_any_pb_success`, but using the
55+
# wrapped class.
56+
in_message = date_pb2.Date(year=1990)
57+
in_message_any = any_pb2.Any()
58+
in_message_any.Pack(in_message)
59+
out_message = protobuf_helpers.from_any_pb(WrappedDate, in_message_any)
60+
61+
assert out_message == in_message
62+
63+
4164
def test_from_any_pb_failure():
4265
in_message = any_pb2.Any()
4366
in_message.Pack(date_pb2.Date(year=1990))

0 commit comments

Comments
 (0)