Fix a python bug for text_format pretty print when Struct in Any

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
pull/19312/head
Jie Luo 3 months ago committed by Copybara-Service
parent 0e6a310156
commit d3e9897b03
  1. 26
      python/google/protobuf/internal/text_format_test.py
  2. 2
      python/google/protobuf/text_format.py

@ -1866,6 +1866,32 @@ class Proto3Tests(unittest.TestCase):
' }\n' ' }\n'
'}\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): def testTopAnyMessage(self):
packed_msg = unittest_pb2.OneString() packed_msg = unittest_pb2.OneString()
msg = any_pb2.Any() msg = any_pb2.Any()

@ -430,7 +430,7 @@ class _Printer(object):
return False return False
packed_message = _BuildMessageFromTypeName(message.TypeName(), packed_message = _BuildMessageFromTypeName(message.TypeName(),
self.descriptor_pool) self.descriptor_pool)
if packed_message: if packed_message is not None:
packed_message.MergeFromString(message.value) packed_message.MergeFromString(message.value)
colon = ':' if self.force_colon else '' colon = ':' if self.force_colon else ''
self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon)) self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon))

Loading…
Cancel
Save