From d3e9897b037a81d3a024d0af0c3626724286534d Mon Sep 17 00:00:00 2001 From: Jie Luo Date: Tue, 19 Nov 2024 17:49:13 -0800 Subject: [PATCH] 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 --- .../protobuf/internal/text_format_test.py | 26 +++++++++++++++++++ python/google/protobuf/text_format.py | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py index b8c8331837..ec7ccb8406 100644 --- a/python/google/protobuf/internal/text_format_test.py +++ b/python/google/protobuf/internal/text_format_test.py @@ -1866,6 +1866,32 @@ class Proto3Tests(unittest.TestCase): ' }\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() diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py index 7e17b43e0c..cc07449323 100644 --- a/python/google/protobuf/text_format.py +++ b/python/google/protobuf/text_format.py @@ -430,7 +430,7 @@ class _Printer(object): 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))