Skip to content

Commit bb0d575

Browse files
authored
Fix a python bug when assign an empty Struct at creation. (#18977)
PiperOrigin-RevId: 689211445
1 parent c267286 commit bb0d575

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

python/google/protobuf/internal/python_message.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ def init(self, **kwargs):
568568
)
569569
)
570570

571-
if new_val:
571+
if new_val != None:
572572
try:
573573
field_copy.MergeFrom(new_val)
574574
except TypeError:

python/google/protobuf/internal/well_known_types_test.py

+31
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import datetime
1414
import unittest
1515

16+
from google.protobuf import json_format
1617
from google.protobuf import text_format
1718
from google.protobuf.internal import more_messages_pb2
1819
from google.protobuf.internal import well_known_types
@@ -1040,6 +1041,36 @@ def testPackDeterministic(self):
10401041
b'\x0e\x1a\x05\n\x018\x10\x10\x1a\x05\n\x019\x10\x12')
10411042
self.assertEqual(golden, serialized)
10421043

1044+
def testJsonStruct(self):
1045+
value = struct_pb2.Value(struct_value=struct_pb2.Struct())
1046+
value_dict = json_format.MessageToDict(
1047+
value,
1048+
always_print_fields_with_no_presence=True,
1049+
preserving_proto_field_name=True,
1050+
use_integers_for_enums=True,
1051+
)
1052+
self.assertDictEqual(value_dict, {})
1053+
1054+
s = struct_pb2.Struct(
1055+
fields={
1056+
'a': struct_pb2.Value(struct_value=struct_pb2.Struct()),
1057+
},
1058+
)
1059+
1060+
sdict = json_format.MessageToDict(
1061+
s,
1062+
always_print_fields_with_no_presence=True,
1063+
preserving_proto_field_name=True,
1064+
use_integers_for_enums=True,
1065+
)
1066+
1067+
self.assertDictEqual(
1068+
sdict,
1069+
{
1070+
'a': {},
1071+
},
1072+
)
1073+
10431074

10441075
if __name__ == '__main__':
10451076
unittest.main()

0 commit comments

Comments
 (0)