Example #1
0
 def testIntegersRepresentedAsFloat(self):
     message = json_format_proto3_pb2.TestMessage()
     json_format.Parse('{"int32Value": -2.147483648e9}', message)
     self.assertEqual(message.int32_value, -2147483648)
     json_format.Parse('{"int32Value": 1e5}', message)
     self.assertEqual(message.int32_value, 100000)
     json_format.Parse('{"int32Value": 1.0}', message)
     self.assertEqual(message.int32_value, 1)
Example #2
0
 def testIgnoreUnknownField(self):
     text = '{"unknownName": 1}'
     parsed_message = json_format_proto3_pb2.TestMessage()
     json_format.Parse(text, parsed_message, ignore_unknown_fields=True)
     text = ('{\n'
             '  "repeatedValue": [ {\n'
             '    "@type": "type.googleapis.com/proto3.MessageType",\n'
             '    "unknownName": 1\n'
             '  }]\n'
             '}\n')
     parsed_message = json_format_proto3_pb2.TestAny()
     json_format.Parse(text, parsed_message, ignore_unknown_fields=True)
Example #3
0
 def testValueMessage(self):
     message = json_format_proto3_pb2.TestValue()
     message.value.string_value = 'hello'
     message.repeated_value.add().number_value = 11.1
     message.repeated_value.add().bool_value = False
     message.repeated_value.add().null_value = 0
     self.assertEqual(
         json.loads(json_format.MessageToJson(message, False)),
         json.loads('{'
                    '  "value": "hello",'
                    '  "repeatedValue": [11.1, false, null]'
                    '}'))
     parsed_message = json_format_proto3_pb2.TestValue()
     self.CheckParseBack(message, parsed_message)
     # Can't parse back if the Value message is not set.
     message.repeated_value.add()
     self.assertEqual(
         json.loads(json_format.MessageToJson(message, False)),
         json.loads('{'
                    '  "value": "hello",'
                    '  "repeatedValue": [11.1, false, null, null]'
                    '}'))
     message.Clear()
     json_format.Parse('{"value": null}', message)
     self.assertEqual(message.value.WhichOneof('kind'), 'null_value')
Example #4
0
 def testAllFieldsToJson(self):
     message = json_format_proto3_pb2.TestMessage()
     text = (
         '{"int32Value": 20, '
         '"int64Value": "-20", '
         '"uint32Value": 3120987654,'
         '"uint64Value": "12345678900",'
         '"floatValue": "-Infinity",'
         '"doubleValue": 3.1415,'
         '"boolValue": true,'
         '"stringValue": "foo",'
         '"bytesValue": "YmFy",'
         '"messageValue": {"value": 10},'
         '"enumValue": "BAR",'
         '"repeatedInt32Value": [2147483647, -2147483648],'
         '"repeatedInt64Value": ["9007199254740992", "-9007199254740992"],'
         '"repeatedUint32Value": [268435455, 134217727],'
         '"repeatedUint64Value": ["9007199254740992", "9007199254740991"],'
         '"repeatedFloatValue": [0],'
         '"repeatedDoubleValue": [1e-15, "Infinity"],'
         '"repeatedBoolValue": [true, false],'
         '"repeatedStringValue": ["Few symbols!#$,;", "bar"],'
         '"repeatedBytesValue": ["Zm9v", "YmFy"],'
         '"repeatedMessageValue": [{"value": 10}, {"value": 11}],'
         '"repeatedEnumValue": ["FOO", "BAR"]'
         '}')
     self.FillAllFields(message)
     self.assertEqual(json.loads(json_format.MessageToJson(message)),
                      json.loads(text))
     parsed_message = json_format_proto3_pb2.TestMessage()
     json_format.Parse(text, parsed_message)
     self.assertEqual(message, parsed_message)
Example #5
0
 def testNanFloat(self):
     message = json_format_proto3_pb2.TestMessage()
     message.float_value = float('nan')
     text = '{\n  "floatValue": "NaN"\n}'
     self.assertEqual(json_format.MessageToJson(message), text)
     parsed_message = json_format_proto3_pb2.TestMessage()
     json_format.Parse(text, parsed_message)
     self.assertTrue(math.isnan(parsed_message.float_value))
Example #6
0
 def testUnknownEnumToJsonAndBack(self):
     text = '{\n  "enumValue": 999\n}'
     message = json_format_proto3_pb2.TestMessage()
     message.enum_value = 999
     self.assertEqual(json_format.MessageToJson(message), text)
     parsed_message = json_format_proto3_pb2.TestMessage()
     json_format.Parse(text, parsed_message)
     self.assertEqual(message, parsed_message)
Example #7
0
 def testParseNull(self):
     message = json_format_proto3_pb2.TestMessage()
     parsed_message = json_format_proto3_pb2.TestMessage()
     self.FillAllFields(parsed_message)
     json_format.Parse(
         '{"int32Value": null, '
         '"int64Value": null, '
         '"uint32Value": null,'
         '"uint64Value": null,'
         '"floatValue": null,'
         '"doubleValue": null,'
         '"boolValue": null,'
         '"stringValue": null,'
         '"bytesValue": null,'
         '"messageValue": null,'
         '"enumValue": null,'
         '"repeatedInt32Value": null,'
         '"repeatedInt64Value": null,'
         '"repeatedUint32Value": null,'
         '"repeatedUint64Value": null,'
         '"repeatedFloatValue": null,'
         '"repeatedDoubleValue": null,'
         '"repeatedBoolValue": null,'
         '"repeatedStringValue": null,'
         '"repeatedBytesValue": null,'
         '"repeatedMessageValue": null,'
         '"repeatedEnumValue": null'
         '}', parsed_message)
     self.assertEqual(message, parsed_message)
     # Null and {} should have different behavior for sub message.
     self.assertFalse(parsed_message.HasField('message_value'))
     json_format.Parse('{"messageValue": {}}', parsed_message)
     self.assertTrue(parsed_message.HasField('message_value'))
     # Null is not allowed to be used as an element in repeated field.
     self.assertRaisesRegex(
         json_format.ParseError,
         'Failed to parse repeatedInt32Value field: '
         'null is not allowed to be used as an element in a repeated field.',
         json_format.Parse, '{"repeatedInt32Value":[1, null]}',
         parsed_message)
     self.CheckError(
         '{"repeatedMessageValue":[null]}',
         'Failed to parse repeatedMessageValue field: null is not'
         ' allowed to be used as an element in a repeated field.')
Example #8
0
 def testExtensionToJsonAndBack(self):
     message = unittest_mset_pb2.TestMessageSetContainer()
     ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
     ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
     message.message_set.Extensions[ext1].i = 23
     message.message_set.Extensions[ext2].str = 'foo'
     message_text = json_format.MessageToJson(message)
     parsed_message = unittest_mset_pb2.TestMessageSetContainer()
     json_format.Parse(message_text, parsed_message)
     self.assertEqual(message, parsed_message)
Example #9
0
    def testPreservingProtoFieldNames(self):
        message = json_format_proto3_pb2.TestMessage()
        message.int32_value = 12345
        self.assertEqual('{\n  "int32Value": 12345\n}',
                         json_format.MessageToJson(message))
        self.assertEqual('{\n  "int32_value": 12345\n}',
                         json_format.MessageToJson(message, False, True))
        # When including_default_value_fields is True.
        message = json_format_proto3_pb2.TestTimestamp()
        self.assertEqual('{\n  "repeatedValue": []\n}',
                         json_format.MessageToJson(message, True, False))
        self.assertEqual('{\n  "repeated_value": []\n}',
                         json_format.MessageToJson(message, True, True))

        # Parsers accept both original proto field names and lowerCamelCase names.
        message = json_format_proto3_pb2.TestMessage()
        json_format.Parse('{"int32Value": 54321}', message)
        self.assertEqual(54321, message.int32_value)
        json_format.Parse('{"int32_value": 12345}', message)
        self.assertEqual(12345, message.int32_value)
Example #10
0
 def testParseEnumValue(self):
     message = json_format_proto3_pb2.TestMessage()
     text = '{"enumValue": 0}'
     json_format.Parse(text, message)
     text = '{"enumValue": 1}'
     json_format.Parse(text, message)
     self.CheckError(
         '{"enumValue": "baz"}',
         'Failed to parse enumValue field: Invalid enum value baz '
         'for enum type proto3.EnumType.')
     # Proto3 accepts numeric unknown enums.
     text = '{"enumValue": 12345}'
     json_format.Parse(text, message)
     # Proto2 does not accept unknown enums.
     message = unittest_pb2.TestAllTypes()
     self.assertRaisesRegex(
         json_format.ParseError,
         'Failed to parse optionalNestedEnum field: Invalid enum value 12345 '
         'for enum type protobuf_unittest.TestAllTypes.NestedEnum.',
         json_format.Parse, '{"optionalNestedEnum": 12345}', message)
Example #11
0
    def testSurrogates(self):
        # Test correct surrogate handling.
        message = json_format_proto3_pb2.TestMessage()
        json_format.Parse('{"stringValue": "\\uD83D\\uDE01"}', message)
        self.assertEqual(message.string_value,
                         b'\xF0\x9F\x98\x81'.decode('utf-8', 'strict'))

        # Error case: unpaired high surrogate.
        self.CheckError('{"stringValue": "\\uD83D"}',
                        r'Invalid \\uXXXX escape|Unpaired.*surrogate')

        # Unpaired low surrogate.
        self.CheckError('{"stringValue": "\\uDE01"}',
                        r'Invalid \\uXXXX escape|Unpaired.*surrogate')
Example #12
0
 def testJsonEscapeString(self):
     message = json_format_proto3_pb2.TestMessage()
     if sys.version_info[0] < 3:
         message.string_value = '&\n<\"\r>\b\t\f\\\001/\xe2\x80\xa8\xe2\x80\xa9'
     else:
         message.string_value = '&\n<\"\r>\b\t\f\\\001/'
         message.string_value += (
             b'\xe2\x80\xa8\xe2\x80\xa9').decode('utf-8')
     self.assertEqual(
         json_format.MessageToJson(message), '{\n  "stringValue": '
         '"&\\n<\\\"\\r>\\b\\t\\f\\\\\\u0001/\\u2028\\u2029"\n}')
     parsed_message = json_format_proto3_pb2.TestMessage()
     self.CheckParseBack(message, parsed_message)
     text = '{"int32Value": "\u0031"}'
     json_format.Parse(text, message)
     self.assertEqual(message.int32_value, 1)
Example #13
0
 def testInvalidAny(self):
     message = any_pb2.Any()
     text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
     self.assertRaisesRegex(KeyError, 'value', json_format.Parse, text,
                            message)
     text = '{"value": 1234}'
     self.assertRaisesRegex(json_format.ParseError,
                            '@type is missing when parsing any message.',
                            json_format.Parse, text, message)
     text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
     self.assertRaisesRegex(
         TypeError, 'Can not find message descriptor by type_url: '
         'type.googleapis.com/MessageNotExist.', json_format.Parse, text,
         message)
     # Only last part is to be used: b/25630112
     text = (
         r'{"@type": "incorrect.googleapis.com/google.protobuf.Int32Value",'
         r'"value": 1234}')
     json_format.Parse(text, message)
Example #14
0
 def testTimestampMessage(self):
     message = json_format_proto3_pb2.TestTimestamp()
     message.value.seconds = 0
     message.value.nanos = 0
     message.repeated_value.add().seconds = 20
     message.repeated_value[0].nanos = 1
     message.repeated_value.add().seconds = 0
     message.repeated_value[1].nanos = 10000
     message.repeated_value.add().seconds = 100000000
     message.repeated_value[2].nanos = 0
     # Maximum time
     message.repeated_value.add().seconds = 253402300799
     message.repeated_value[3].nanos = 999999999
     # Minimum time
     message.repeated_value.add().seconds = -62135596800
     message.repeated_value[4].nanos = 0
     self.assertEqual(
         json.loads(json_format.MessageToJson(message, True)),
         json.loads('{'
                    '"value": "1970-01-01T00:00:00Z",'
                    '"repeatedValue": ['
                    '  "1970-01-01T00:00:20.000000001Z",'
                    '  "1970-01-01T00:00:00.000010Z",'
                    '  "1973-03-03T09:46:40Z",'
                    '  "9999-12-31T23:59:59.999999999Z",'
                    '  "0001-01-01T00:00:00Z"'
                    ']'
                    '}'))
     parsed_message = json_format_proto3_pb2.TestTimestamp()
     self.CheckParseBack(message, parsed_message)
     text = (r'{"value": "1970-01-01T00:00:00.01+08:00",'
             r'"repeatedValue":['
             r'  "1970-01-01T00:00:00.01+08:30",'
             r'  "1970-01-01T00:00:00.01-01:23"]}')
     json_format.Parse(text, parsed_message)
     self.assertEqual(parsed_message.value.seconds, -8 * 3600)
     self.assertEqual(parsed_message.value.nanos, 10000000)
     self.assertEqual(parsed_message.repeated_value[0].seconds, -8.5 * 3600)
     self.assertEqual(parsed_message.repeated_value[1].seconds,
                      3600 + 23 * 60)
Example #15
0
 def CheckParseBack(self, message, parsed_message):
     json_format.Parse(json_format.MessageToJson(message), parsed_message)
     self.assertEqual(message, parsed_message)