Python google.protobuf.json_format.ParseError() Examples

The following are 30 code examples of google.protobuf.json_format.ParseError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google.protobuf.json_format , or try the search function .
Example #1
Source File: plugin.py    From fairness-indicators with Apache License 2.0 6 votes vote down vote up
def _get_evaluation_result(self, request):
    run = request.args.get('run')
    try:
      run = six.ensure_text(run)
    except (UnicodeDecodeError, AttributeError):
      pass

    data = []
    try:
      eval_result_output_dir = six.ensure_text(
          self._multiplexer.Tensors(run, FairnessIndicatorsPlugin.plugin_name)
          [0].tensor_proto.string_val[0])
      eval_result = tfma.load_eval_result(output_path=eval_result_output_dir)
      # TODO(b/141283811): Allow users to choose different model output names
      # and class keys in case of multi-output and multi-class model.
      data = widget_view.convert_slicing_metrics_to_ui_input(
          eval_result.slicing_metrics)
    except (KeyError, json_format.ParseError) as error:
      logging.info('Error while fetching evaluation data, %s', error)
    return http_util.Respond(request, data, content_type='application/json') 
Example #2
Source File: predictor.py    From sagemaker-python-sdk with Apache License 2.0 6 votes vote down vote up
def __call__(self, stream, content_type):
        """
        Args:
            stream:
            content_type:
        """
        try:
            data = stream.read()
        finally:
            stream.close()

        for possible_response in _possible_responses():
            try:
                return protobuf_to_dict(json_format.Parse(data, possible_response()))
            except (UnicodeDecodeError, DecodeError, json_format.ParseError):
                # given that the payload does not have the response type, there no way to infer
                # the response without keeping state, so I'm iterating all the options.
                pass
        return json.loads(data.decode()) 
Example #3
Source File: json_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testInvalidIntegerValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"int32Value": 0x12345}'
    self.assertRaises(json_format.ParseError,
                      json_format.Parse, text, message)
    self.CheckError('{"int32Value": 1.5}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: 1.5.')
    self.CheckError('{"int32Value": 012345}',
                    (r'Failed to load JSON: Expecting \'?,\'? delimiter: '
                     r'line 1.'))
    self.CheckError('{"int32Value": " 1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: " 1 ".')
    self.CheckError('{"int32Value": "1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: "1 ".')
    self.CheckError('{"int32Value": 12345678901234567890}',
                    'Failed to parse int32Value field: Value out of range: '
                    '12345678901234567890.')
    self.CheckError('{"uint32Value": -1}',
                    'Failed to parse uint32Value field: '
                    'Value out of range: -1.') 
Example #4
Source File: json_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testInvalidMap(self):
    message = json_format_proto3_pb2.TestMap()
    text = '{"int32Map": {"null": 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse int32Map field: invalid literal',
        json_format.Parse, text, message)
    text = '{"int32Map": {1: 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        (r'Failed to load JSON: Expecting property name'
         r'( enclosed in double quotes)?: line 1'),
        json_format.Parse, text, message)
    text = '{"boolMap": {"null": 1}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse boolMap field: Expected "true" or "false", not null.',
        json_format.Parse, text, message)
    if sys.version_info < (2, 7):
      return
    text = r'{"stringMap": {"a": 3, "\u0061": 2}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to load JSON: duplicate key a',
        json_format.Parse, text, message) 
Example #5
Source File: json_format_test.py    From coremltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testInvalidAny(self):
    message = any_pb2.Any()
    text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
    self.assertRaisesRegexp(
        KeyError,
        'value',
        json_format.Parse, text, message)
    text = '{"value": 1234}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        '@type is missing when parsing any message.',
        json_format.Parse, text, message)
    text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
    self.assertRaisesRegexp(
        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 #6
Source File: loader.py    From artman with Apache License 2.0 6 votes vote down vote up
def read_user_config(artman_user_config_path):
    """Parse and return artman config"""
    config_pb = UserConfig()
    artman_user_config_path = os.path.expanduser(artman_user_config_path)
    if not os.path.isfile(artman_user_config_path):
      logger.warn(
          'No artman user config defined. Use the default one for this '
          'execution. Run `configure-artman` to set up user config.')
      return config_pb

    try:
        with io.open(artman_user_config_path, 'r', encoding='UTF-8') as f:
            # Convert yaml into json file as protobuf python load support
            # parsing of protobuf in json or text format, not yaml.
            json_string = json.dumps(yaml.load(f, Loader=yaml.FullLoader))
        json_format.Parse(json_string, config_pb)
    except (json_format.ParseError, yaml.parser.ParserError):
        logger.error(INVALID_USER_CONFIG_ERROR_MESSAGE_FORMAT % artman_user_config_path)
        raise

    return config_pb 
Example #7
Source File: json_format_test.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def testInvalidIntegerValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"int32Value": 0x12345}'
    self.assertRaises(json_format.ParseError,
                      json_format.Parse, text, message)
    self.CheckError('{"int32Value": 1.5}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: 1.5.')
    self.CheckError('{"int32Value": 012345}',
                    (r'Failed to load JSON: Expecting \'?,\'? delimiter: '
                     r'line 1.'))
    self.CheckError('{"int32Value": " 1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: " 1 ".')
    self.CheckError('{"int32Value": "1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: "1 ".')
    self.CheckError('{"int32Value": 12345678901234567890}',
                    'Failed to parse int32Value field: Value out of range: '
                    '12345678901234567890.')
    self.CheckError('{"uint32Value": -1}',
                    'Failed to parse uint32Value field: '
                    'Value out of range: -1.') 
Example #8
Source File: json_format_test.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def testInvalidMap(self):
    message = json_format_proto3_pb2.TestMap()
    text = '{"int32Map": {"null": 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse int32Map field: invalid literal',
        json_format.Parse, text, message)
    text = '{"int32Map": {1: 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        (r'Failed to load JSON: Expecting property name'
         r'( enclosed in double quotes)?: line 1'),
        json_format.Parse, text, message)
    text = '{"boolMap": {"null": 1}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse boolMap field: Expected "true" or "false", not null.',
        json_format.Parse, text, message)
    if sys.version_info < (2, 7):
      return
    text = r'{"stringMap": {"a": 3, "\u0061": 2}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to load JSON: duplicate key a',
        json_format.Parse, text, message) 
Example #9
Source File: json_format_test.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def testInvalidAny(self):
    message = any_pb2.Any()
    text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
    self.assertRaisesRegexp(
        KeyError,
        'value',
        json_format.Parse, text, message)
    text = '{"value": 1234}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        '@type is missing when parsing any message.',
        json_format.Parse, text, message)
    text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
    self.assertRaisesRegexp(
        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 #10
Source File: loader.py    From artman with Apache License 2.0 6 votes vote down vote up
def _parse(artman_yaml_path):
    """Parse artman yaml config into corresponding protobuf."""
    if not os.path.exists(artman_yaml_path):
        raise ValueError(CONFIG_NOT_FOUND_ERROR_MESSAGE_FORMAT % artman_yaml_path)

    try:
        with io.open(artman_yaml_path, 'r', encoding='UTF-8') as f:
            # Convert yaml into json file as protobuf python load support paring of
            # protobuf in json or text format, not yaml.
            artman_config_json_string = json.dumps(yaml.load(f, Loader=yaml.FullLoader))
        config_pb = Config()
        json_format.Parse(artman_config_json_string, config_pb)
    except (json_format.ParseError, yaml.parser.ParserError):
        logger.error(INVALID_CONFIG_ERROR_MESSAGE_FORMAT % artman_yaml_path)
        raise

    return config_pb 
Example #11
Source File: plugin.py    From fairness-indicators with Apache License 2.0 6 votes vote down vote up
def _get_evaluation_result_from_remote_path(self, request):
    evaluation_output_path = request.args.get('evaluation_output_path')
    try:
      evaluation_output_path = six.ensure_text(evaluation_output_path)
    except (UnicodeDecodeError, AttributeError):
      pass
    try:
      eval_result = tfma.load_eval_result(
          os.path.dirname(evaluation_output_path),
          output_file_format=self._get_output_file_format(
              evaluation_output_path))
      data = widget_view.convert_slicing_metrics_to_ui_input(
          eval_result.slicing_metrics)
    except (KeyError, json_format.ParseError) as error:
      logging.info('Error while fetching evaluation data, %s', error)
      data = []
    return http_util.Respond(request, data, content_type='application/json') 
Example #12
Source File: json_format_test.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
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 #13
Source File: json_format_test.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def testInvalidIntegerValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"int32Value": 0x12345}'
    self.assertRaises(json_format.ParseError,
                      json_format.Parse, text, message)
    self.CheckError('{"int32Value": 1.5}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: 1.5.')
    self.CheckError('{"int32Value": 012345}',
                    (r'Failed to load JSON: Expecting \'?,\'? delimiter: '
                     r'line 1.'))
    self.CheckError('{"int32Value": " 1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: " 1 ".')
    self.CheckError('{"int32Value": "1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: "1 ".')
    self.CheckError('{"int32Value": 12345678901234567890}',
                    'Failed to parse int32Value field: Value out of range: '
                    '12345678901234567890.')
    self.CheckError('{"uint32Value": -1}',
                    'Failed to parse uint32Value field: '
                    'Value out of range: -1.') 
Example #14
Source File: json_format_test.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
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 #15
Source File: json_format_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testInvalidIntegerValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"int32Value": 0x12345}'
    self.assertRaises(json_format.ParseError,
                      json_format.Parse, text, message)
    self.CheckError('{"int32Value": 1.5}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: 1.5.')
    self.CheckError('{"int32Value": 012345}',
                    (r'Failed to load JSON: Expecting \'?,\'? delimiter: '
                     r'line 1.'))
    self.CheckError('{"int32Value": " 1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: " 1 ".')
    self.CheckError('{"int32Value": "1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: "1 ".')
    self.CheckError('{"int32Value": 12345678901234567890}',
                    'Failed to parse int32Value field: Value out of range: '
                    '12345678901234567890.')
    self.CheckError('{"uint32Value": -1}',
                    'Failed to parse uint32Value field: '
                    'Value out of range: -1.') 
Example #16
Source File: json_format_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testInvalidMap(self):
    message = json_format_proto3_pb2.TestMap()
    text = '{"int32Map": {"null": 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse int32Map field: invalid literal',
        json_format.Parse, text, message)
    text = '{"int32Map": {1: 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        (r'Failed to load JSON: Expecting property name'
         r'( enclosed in double quotes)?: line 1'),
        json_format.Parse, text, message)
    text = '{"boolMap": {"null": 1}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse boolMap field: Expected "true" or "false", not null.',
        json_format.Parse, text, message)
    if sys.version_info < (2, 7):
      return
    text = r'{"stringMap": {"a": 3, "\u0061": 2}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to load JSON: duplicate key a',
        json_format.Parse, text, message) 
Example #17
Source File: json_format_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testInvalidAny(self):
    message = any_pb2.Any()
    text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
    self.assertRaisesRegexp(
        KeyError,
        'value',
        json_format.Parse, text, message)
    text = '{"value": 1234}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        '@type is missing when parsing any message.',
        json_format.Parse, text, message)
    text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
    self.assertRaisesRegexp(
        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 #18
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testInvalidIntegerValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"int32Value": 0x12345}'
    self.assertRaises(json_format.ParseError,
                      json_format.Parse, text, message)
    self.CheckError('{"int32Value": 1.5}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: 1.5.')
    self.CheckError('{"int32Value": 012345}',
                    (r'Failed to load JSON: Expecting \'?,\'? delimiter: '
                     r'line 1.'))
    self.CheckError('{"int32Value": " 1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: " 1 ".')
    self.CheckError('{"int32Value": "1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: "1 ".')
    self.CheckError('{"int32Value": 12345678901234567890}',
                    'Failed to parse int32Value field: Value out of range: '
                    '12345678901234567890.')
    self.CheckError('{"uint32Value": -1}',
                    'Failed to parse uint32Value field: '
                    'Value out of range: -1.') 
Example #19
Source File: json_format_test.py    From lambda-packs with MIT License 6 votes vote down vote up
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 #20
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testInvalidMap(self):
    message = json_format_proto3_pb2.TestMap()
    text = '{"int32Map": {"null": 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse int32Map field: invalid literal',
        json_format.Parse, text, message)
    text = '{"int32Map": {1: 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        (r'Failed to load JSON: Expecting property name'
         r'( enclosed in double quotes)?: line 1'),
        json_format.Parse, text, message)
    text = '{"boolMap": {"null": 1}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse boolMap field: Expected "true" or "false", not null.',
        json_format.Parse, text, message)
    if sys.version_info < (2, 7):
      return
    text = r'{"stringMap": {"a": 3, "\u0061": 2}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to load JSON: duplicate key a',
        json_format.Parse, text, message) 
Example #21
Source File: json_format_test.py    From lambda-packs with MIT License 6 votes vote down vote up
def testInvalidIntegerValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"int32Value": 0x12345}'
    self.assertRaises(json_format.ParseError,
                      json_format.Parse, text, message)
    self.CheckError('{"int32Value": 1.5}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: 1.5.')
    self.CheckError('{"int32Value": 012345}',
                    (r'Failed to load JSON: Expecting \'?,\'? delimiter: '
                     r'line 1.'))
    self.CheckError('{"int32Value": " 1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: " 1 ".')
    self.CheckError('{"int32Value": "1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: "1 ".')
    self.CheckError('{"int32Value": 12345678901234567890}',
                    'Failed to parse int32Value field: Value out of range: '
                    '12345678901234567890.')
    self.CheckError('{"uint32Value": -1}',
                    'Failed to parse uint32Value field: '
                    'Value out of range: -1.') 
Example #22
Source File: json_format_test.py    From lambda-packs with MIT License 6 votes vote down vote up
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 #23
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testInvalidAny(self):
    message = any_pb2.Any()
    text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
    self.assertRaisesRegexp(
        KeyError,
        'value',
        json_format.Parse, text, message)
    text = '{"value": 1234}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        '@type is missing when parsing any message.',
        json_format.Parse, text, message)
    text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
    self.assertRaisesRegexp(
        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 #24
Source File: json_format_test.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def testInvalidOneof(self):
    message = json_format_proto3_pb2.TestOneof()
    text = '{"oneofInt32Value": 1, "oneofStringValue": "2"}'
    self.assertRaisesRegex(
        json_format.ParseError,
        'Message type "proto3.TestOneof"'
        ' should not have multiple "oneof_value" oneof fields.',
        json_format.Parse, text, message) 
Example #25
Source File: config.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def validate_with_proto(self, resource: ACResource, protoclass: Any) -> RichStatus:
        # This is... a little odd.
        #
        # First, protobuf works with JSON, not dictionaries. Second, by the time we get here,
        # the metadata has been folded in, and our *Spec protos (HostSpec, etc) don't include
        # the metadata (by design).
        #
        # So. We make a copy, strip the metadata fields, serialize, and _then_ see if  we can
        # parse it. Yuck.

        rdict = resource.as_dict()
        rdict.pop('apiVersion', None)
        rdict.pop('kind', None)

        name = rdict.pop('name', None)
        namespace = rdict.pop('namespace', None)
        metadata_labels = rdict.pop('metadata_labels', None)
        generation = rdict.pop('generation', None)

        serialized = json.dumps(rdict)

        try:
            json_format.Parse(serialized, protoclass())
        except json_format.ParseError as e:
            return RichStatus.fromError(str(e))

        return RichStatus.OK(msg=f"good {resource.kind}") 
Example #26
Source File: json_format_test.py    From lambda-packs with MIT License 5 votes vote down vote up
def testInvalidStruct(self):
    message = json_format_proto3_pb2.TestStruct()
    text = '{"value": 1234}'
    self.assertRaisesRegex(
        json_format.ParseError,
        'Failed to parse value field: Struct must be in a dict which is 1234',
        json_format.Parse, text, message) 
Example #27
Source File: json_format_test.py    From lambda-packs with MIT License 5 votes vote down vote up
def testInvalidListValue(self):
    message = json_format_proto3_pb2.TestListValue()
    text = '{"value": 1234}'
    self.assertRaisesRegex(
        json_format.ParseError,
        r'Failed to parse value field: ListValue must be in \[\] which is 1234',
        json_format.Parse, text, message) 
Example #28
Source File: json_format_test.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def CheckError(self, text, error_message):
    message = json_format_proto3_pb2.TestMessage()
    self.assertRaisesRegex(
        json_format.ParseError,
        error_message,
        json_format.Parse, text, message) 
Example #29
Source File: json_format_test.py    From lambda-packs with MIT License 5 votes vote down vote up
def testInvalidOneof(self):
    message = json_format_proto3_pb2.TestOneof()
    text = '{"oneofInt32Value": 1, "oneofStringValue": "2"}'
    self.assertRaisesRegex(
        json_format.ParseError,
        'Message type "proto3.TestOneof"'
        ' should not have multiple "oneof_value" oneof fields.',
        json_format.Parse, text, message) 
Example #30
Source File: json_format_test.py    From lambda-packs with MIT License 5 votes vote down vote up
def testInvalidMap(self):
    message = json_format_proto3_pb2.TestMap()
    text = '{"int32Map": {"null": 2, "2": 3}}'
    self.assertRaisesRegex(
        json_format.ParseError,
        'Failed to parse int32Map field: invalid literal',
        json_format.Parse, text, message)
    text = '{"int32Map": {1: 2, "2": 3}}'
    self.assertRaisesRegex(
        json_format.ParseError,
        (r'Failed to load JSON: Expecting property name'
         r'( enclosed in double quotes)?: line 1'),
        json_format.Parse, text, message)
    text = '{"boolMap": {"null": 1}}'
    self.assertRaisesRegex(
        json_format.ParseError,
        'Failed to parse boolMap field: Expected "true" or "false", not null.',
        json_format.Parse, text, message)
    if sys.version_info < (2, 7):
      return
    text = r'{"stringMap": {"a": 3, "\u0061": 2}}'
    self.assertRaisesRegex(
        json_format.ParseError,
        'Failed to load JSON: duplicate key a',
        json_format.Parse, text, message)
    text = r'{"stringMap": 0}'
    self.assertRaisesRegex(
        json_format.ParseError,
        'Failed to parse stringMap field: Map field string_map must be '
        'in a dict which is 0.',
        json_format.Parse, text, message)