Skip to content

Commit

Permalink
Fix a python bug for text_format pretty print when Struct in Any
Browse files Browse the repository at this point in the history
Struct has a default bool function, and empty Struct returns False for bool().
Should compare with None instead of bool() when check if Struct is able to be
created.

PiperOrigin-RevId: 698205106
  • Loading branch information
anandolee authored and copybara-github committed Nov 20, 2024
1 parent 0e6a310 commit d3e9897
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
26 changes: 26 additions & 0 deletions python/google/protobuf/internal/text_format_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1866,6 +1866,32 @@ def testPrintMessageExpandAny(self):
' }\n'
'}\n')

def testPrintStructInAny(self):
packed_message = struct_pb2.Struct()
packed_message['name'] = 'Jim'
message = any_test_pb2.TestAny()
message.any_value.Pack(packed_message)
print(
text_format.MessageToString(
message, descriptor_pool=descriptor_pool.Default()
)
)
self.assertEqual(
text_format.MessageToString(
message, descriptor_pool=descriptor_pool.Default()
),
'any_value {\n'
' [type.googleapis.com/google.protobuf.Struct] {\n'
' fields {\n'
' key: "name"\n'
' value {\n'
' string_value: "Jim"\n'
' }\n'
' }\n'
' }\n'
'}\n',
)

def testTopAnyMessage(self):
packed_msg = unittest_pb2.OneString()
msg = any_pb2.Any()
Expand Down
2 changes: 1 addition & 1 deletion python/google/protobuf/text_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def _TryPrintAsAnyMessage(self, message):
return False
packed_message = _BuildMessageFromTypeName(message.TypeName(),
self.descriptor_pool)
if packed_message:
if packed_message is not None:
packed_message.MergeFromString(message.value)
colon = ':' if self.force_colon else ''
self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon))
Expand Down

0 comments on commit d3e9897

Please sign in to comment.