Raise ParseError when JSON string is expected and not given (#7935)

Raise ParseError when JSON string is expected and not given
pull/8775/head
Ilya Konstantinov 4 years ago committed by GitHub
parent 611a08ee00
commit 991bcada05
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 26
      python/google/protobuf/internal/json_format_test.py
  2. 9
      python/google/protobuf/internal/well_known_types.py

@ -1119,6 +1119,30 @@ class JsonFormatTest(JsonFormatBase):
'Failed to parse value field: Struct must be in a dict which is 1234',
json_format.Parse, text, message)
def testTimestampInvalidStringValue(self):
message = json_format_proto3_pb2.TestTimestamp()
text = '{"value": {"foo": 123}}'
self.assertRaisesRegexp(
json_format.ParseError,
r"Timestamp JSON value not a string: {u?'foo': 123}",
json_format.Parse, text, message)
def testDurationInvalidStringValue(self):
message = json_format_proto3_pb2.TestDuration()
text = '{"value": {"foo": 123}}'
self.assertRaisesRegexp(
json_format.ParseError,
r"Duration JSON value not a string: {u?'foo': 123}",
json_format.Parse, text, message)
def testFieldMaskInvalidStringValue(self):
message = json_format_proto3_pb2.TestFieldMask()
text = '{"value": {"foo": 123}}'
self.assertRaisesRegexp(
json_format.ParseError,
r"FieldMask JSON value not a string: {u?'foo': 123}",
json_format.Parse, text, message)
def testInvalidAny(self):
message = any_pb2.Any()
text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
@ -1217,7 +1241,7 @@ class JsonFormatTest(JsonFormatBase):
def testParseDictUnknownValueType(self):
class UnknownClass(object):
def __str__(self):
def __repr__(self):
return 'v'
message = json_format_proto3_pb2.TestValue()
self.assertRaisesRegexp(

@ -143,6 +143,9 @@ class Timestamp(object):
Raises:
ValueError: On parsing problems.
"""
if not isinstance(value, six.string_types):
raise ValueError(
'Timestamp JSON value not a string: {!r}'.format(value))
timezone_offset = value.find('Z')
if timezone_offset == -1:
timezone_offset = value.find('+')
@ -303,6 +306,9 @@ class Duration(object):
Raises:
ValueError: On parsing problems.
"""
if not isinstance(value, six.string_types):
raise ValueError(
'Duration JSON value not a string: {!r}'.format(value))
if len(value) < 1 or value[-1] != 's':
raise ValueError(
'Duration must end with letter "s": {0}.'.format(value))
@ -428,6 +434,9 @@ class FieldMask(object):
def FromJsonString(self, value):
"""Converts string to FieldMask according to proto3 JSON spec."""
if not isinstance(value, six.string_types):
raise ValueError(
'FieldMask JSON value not a string: {!r}'.format(value))
self.Clear()
if value:
for path in value.split(','):

Loading…
Cancel
Save