Skip to content

Commit

Permalink
Raise errors when serialize inf and nan for Value.number_value in jso…
Browse files Browse the repository at this point in the history
…n format. fixes #11259

PiperOrigin-RevId: 495446149
  • Loading branch information
anandolee authored and copybara-github committed Dec 16, 2022
1 parent 66b260f commit da21767
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
17 changes: 17 additions & 0 deletions python/google/protobuf/internal/json_format_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,23 @@ def testValueMessage(self):
json_format.Parse('{"value": null}', message)
self.assertEqual(message.value.WhichOneof('kind'), 'null_value')

def testValueMessageErrors(self):
message = json_format_proto3_pb2.TestValue()
message.value.number_value = math.inf
with self.assertRaises(json_format.SerializeToJsonError) as cm:
json_format.MessageToJson(message)
self.assertEqual(
'Failed to serialize value field: Fail to serialize Infinity for '
'Value.number_value, which would parse as string_value.',
str(cm.exception))
message.value.number_value = math.nan
with self.assertRaises(json_format.SerializeToJsonError) as cm:
json_format.MessageToJson(message)
self.assertEqual(
'Failed to serialize value field: Fail to serialize NaN for '
'Value.number_value, which would parse as string_value.',
str(cm.exception))

def testListValueMessage(self):
message = json_format_proto3_pb2.TestListValue()
message.value.values.add().number_value = 11.1
Expand Down
10 changes: 8 additions & 2 deletions python/google/protobuf/json_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,8 +354,14 @@ def _ValueMessageToJsonObject(self, message):
return None
if which == 'list_value':
return self._ListValueMessageToJsonObject(message.list_value)
if which == 'struct_value':
value = message.struct_value
if which == 'number_value':
value = message.number_value
if math.isinf(value):
raise ValueError('Fail to serialize Infinity for Value.number_value, '
'which would parse as string_value')
if math.isnan(value):
raise ValueError('Fail to serialize NaN for Value.number_value, '
'which would parse as string_value')
else:
value = getattr(message, which)
oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]
Expand Down

0 comments on commit da21767

Please sign in to comment.