Python google.protobuf.internal.api_implementation.Type() Examples

The following are 30 code examples for showing how to use google.protobuf.internal.api_implementation.Type(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module google.protobuf.internal.api_implementation , or try the search function .

Example 1
Project: lambda-packs   Author: ryfeus   File: descriptor.py    License: MIT License 6 votes vote down vote up
def ProtoTypeToCppProtoType(proto_type):
    """Converts from a Python proto type to a C++ Proto Type.

    The Python ProtocolBuffer classes specify both the 'Python' datatype and the
    'C++' datatype - and they're not the same. This helper method should
    translate from one to another.

    Args:
      proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
    Returns:
      descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
    Raises:
      TypeTransformationError: when the Python proto type isn't known.
    """
    try:
      return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
    except KeyError:
      raise TypeTransformationError('Unknown proto_type: %s' % proto_type) 
Example 2
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 6 votes vote down vote up
def testFindTypeErrors(self):
    self.assertRaises(TypeError, self.pool.FindExtensionByNumber, '')

    # TODO(jieluo): Fix python to raise correct errors.
    if api_implementation.Type() == 'cpp':
      self.assertRaises(TypeError, self.pool.FindMethodByName, 0)
      self.assertRaises(KeyError, self.pool.FindMethodByName, '')
      error_type = TypeError
    else:
      error_type = AttributeError
    self.assertRaises(error_type, self.pool.FindMessageTypeByName, 0)
    self.assertRaises(error_type, self.pool.FindFieldByName, 0)
    self.assertRaises(error_type, self.pool.FindExtensionByName, 0)
    self.assertRaises(error_type, self.pool.FindEnumTypeByName, 0)
    self.assertRaises(error_type, self.pool.FindOneofByName, 0)
    self.assertRaises(error_type, self.pool.FindServiceByName, 0)
    self.assertRaises(error_type, self.pool.FindFileContainingSymbol, 0)
    if api_implementation.Type() == 'python':
      error_type = KeyError
    self.assertRaises(error_type, self.pool.FindFileByName, 0) 
Example 3
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 6 votes vote down vote up
def testFindExtensionByName(self):
    if isinstance(self, SecondaryDescriptorFromDescriptorDB):
      if api_implementation.Type() == 'cpp':
        # TODO(jieluo): Fix cpp extension to find extension correctly
        # when descriptor pool is using an underlying database.
        return
    # An extension defined in a message.
    extension = self.pool.FindExtensionByName(
        'google.protobuf.python.internal.Factory2Message.one_more_field')
    self.assertEqual(extension.name, 'one_more_field')
    # An extension defined at file scope.
    extension = self.pool.FindExtensionByName(
        'google.protobuf.python.internal.another_field')
    self.assertEqual(extension.name, 'another_field')
    self.assertEqual(extension.number, 1002)
    with self.assertRaises(KeyError):
      self.pool.FindFieldByName('Does not exist') 
Example 4
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 6 votes vote down vote up
def testComplexNesting(self):
    if isinstance(self, SecondaryDescriptorFromDescriptorDB):
      if api_implementation.Type() == 'cpp':
        # Cpp extension cannot call Add on a DescriptorPool
        # that uses a DescriptorDatabase.
        # TODO(jieluo): Fix python and cpp extension diff.
        return
    more_messages_desc = descriptor_pb2.FileDescriptorProto.FromString(
        more_messages_pb2.DESCRIPTOR.serialized_pb)
    test1_desc = descriptor_pb2.FileDescriptorProto.FromString(
        descriptor_pool_test1_pb2.DESCRIPTOR.serialized_pb)
    test2_desc = descriptor_pb2.FileDescriptorProto.FromString(
        descriptor_pool_test2_pb2.DESCRIPTOR.serialized_pb)
    self.pool.Add(more_messages_desc)
    self.pool.Add(test1_desc)
    self.pool.Add(test2_desc)
    TEST1_FILE.CheckFile(self, self.pool)
    TEST2_FILE.CheckFile(self, self.pool) 
Example 5
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 6 votes vote down vote up
def CheckField(self, test, msg_desc, name, index, file_desc):
    field_desc = msg_desc.fields_by_name[name]
    field_type_desc = msg_desc.nested_types_by_name[self.type_name]
    test.assertEqual(name, field_desc.name)
    expected_field_full_name = '.'.join([msg_desc.full_name, name])
    test.assertEqual(expected_field_full_name, field_desc.full_name)
    test.assertEqual(index, field_desc.index)
    test.assertEqual(self.number, field_desc.number)
    test.assertEqual(descriptor.FieldDescriptor.TYPE_MESSAGE, field_desc.type)
    test.assertEqual(descriptor.FieldDescriptor.CPPTYPE_MESSAGE,
                     field_desc.cpp_type)
    test.assertFalse(field_desc.has_default_value)
    test.assertEqual(msg_desc, field_desc.containing_type)
    test.assertEqual(field_type_desc, field_desc.message_type)
    test.assertEqual(file_desc, field_desc.file)
    # TODO(jieluo): Fix python and cpp extension diff for message field
    # default value.
    if api_implementation.Type() == 'cpp':
      test.assertRaises(
          NotImplementedError, getattr, field_desc, 'default_value') 
Example 6
Project: lambda-packs   Author: ryfeus   File: reflection_test.py    License: MIT License 6 votes vote down vote up
def testClear(self):
    proto = unittest_pb2.TestAllTypes()
    # C++ implementation does not support lazy fields right now so leave it
    # out for now.
    if api_implementation.Type() == 'python':
      test_util.SetAllFields(proto)
    else:
      test_util.SetAllNonLazyFields(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllTypes()
    self.assertEqual(proto, empty_proto)

    # Test if extensions which were set are cleared.
    proto = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllExtensions()
    self.assertEqual(proto, empty_proto) 
Example 7
Project: lambda-packs   Author: ryfeus   File: message_test.py    License: MIT License 6 votes vote down vote up
def testParseErrors(self, message_module):
    msg = message_module.TestAllTypes()
    self.assertRaises(TypeError, msg.FromString, 0)
    self.assertRaises(Exception, msg.FromString, '0')
    # TODO(jieluo): Fix cpp extension to raise error instead of warning.
    # b/27494216
    end_tag = encoder.TagBytes(1, 4)
    if api_implementation.Type() == 'python':
      with self.assertRaises(message.DecodeError) as context:
        msg.FromString(end_tag)
      self.assertEqual('Unexpected end-group tag.', str(context.exception))
    else:
      with warnings.catch_warnings(record=True) as w:
        # Cause all warnings to always be triggered.
        warnings.simplefilter('always')
        msg.FromString(end_tag)
        assert len(w) == 1
        assert issubclass(w[-1].category, RuntimeWarning)
        self.assertEqual('Unexpected end-group tag: Not all data was converted',
                         str(w[-1].message)) 
Example 8
Project: lambda-packs   Author: ryfeus   File: message_test.py    License: MIT License 6 votes vote down vote up
def testSetRepeatedComposite(self, message_module):
    m = message_module.TestAllTypes()
    with self.assertRaises(AttributeError):
      m.repeated_int32 = []
    m.repeated_int32.append(1)
    if api_implementation.Type() == 'cpp':
      # For test coverage: cpp has a different path if composite
      # field is in cache
      with self.assertRaises(TypeError):
        m.repeated_int32 = []
    else:
      with self.assertRaises(AttributeError):
        m.repeated_int32 = []


# Class to test proto2-only features (required, extensions, etc.) 
Example 9
Project: lambda-packs   Author: ryfeus   File: descriptor_test.py    License: MIT License 6 votes vote down vote up
def CheckFieldDescriptor(self, field_descriptor):
    # Basic properties
    self.assertEqual(field_descriptor.name, 'optional_int32')
    self.assertEqual(field_descriptor.camelcase_name, 'optionalInt32')
    self.assertEqual(field_descriptor.full_name,
                     'protobuf_unittest.TestAllTypes.optional_int32')
    self.assertEqual(field_descriptor.containing_type.name, 'TestAllTypes')
    self.assertEqual(field_descriptor.file, unittest_pb2.DESCRIPTOR)
    # Test equality and hashability
    self.assertEqual(field_descriptor, field_descriptor)
    self.assertEqual(
        field_descriptor.containing_type.fields_by_name['optional_int32'],
        field_descriptor)
    self.assertEqual(
        field_descriptor.containing_type.fields_by_camelcase_name[
            'optionalInt32'],
        field_descriptor)
    self.assertIn(field_descriptor, [field_descriptor])
    self.assertIn(field_descriptor, {field_descriptor: None})
    self.assertEqual(None, field_descriptor.extension_scope)
    self.assertEqual(None, field_descriptor.enum_type)
    if api_implementation.Type() == 'cpp':
      # For test coverage only
      self.assertEqual(field_descriptor.id, field_descriptor.id) 
Example 10
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: descriptor.py    License: MIT License 6 votes vote down vote up
def ProtoTypeToCppProtoType(proto_type):
    """Converts from a Python proto type to a C++ Proto Type.

    The Python ProtocolBuffer classes specify both the 'Python' datatype and the
    'C++' datatype - and they're not the same. This helper method should
    translate from one to another.

    Args:
      proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
    Returns:
      descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
    Raises:
      TypeTransformationError: when the Python proto type isn't known.
    """
    try:
      return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
    except KeyError:
      raise TypeTransformationError('Unknown proto_type: %s' % proto_type) 
Example 11
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: descriptor.py    License: MIT License 6 votes vote down vote up
def __init__(self, name, package, options=None, serialized_pb=None,
               dependencies=None, public_dependencies=None,
               syntax=None, pool=None):
    """Constructor."""
    super(FileDescriptor, self).__init__(options, 'FileOptions')

    if pool is None:
      from google.protobuf import descriptor_pool
      pool = descriptor_pool.Default()
    self.pool = pool
    self.message_types_by_name = {}
    self.name = name
    self.package = package
    self.syntax = syntax or "proto2"
    self.serialized_pb = serialized_pb

    self.enum_types_by_name = {}
    self.extensions_by_name = {}
    self.services_by_name = {}
    self.dependencies = (dependencies or [])
    self.public_dependencies = (public_dependencies or [])

    if (api_implementation.Type() == 'cpp' and
        self.serialized_pb is not None):
      _message.default_pool.AddSerializedFile(self.serialized_pb) 
Example 12
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: reflection_test.py    License: MIT License 6 votes vote down vote up
def testClear(self):
    proto = unittest_pb2.TestAllTypes()
    # C++ implementation does not support lazy fields right now so leave it
    # out for now.
    if api_implementation.Type() == 'python':
      test_util.SetAllFields(proto)
    else:
      test_util.SetAllNonLazyFields(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllTypes()
    self.assertEqual(proto, empty_proto)

    # Test if extensions which were set are cleared.
    proto = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllExtensions()
    self.assertEqual(proto, empty_proto) 
Example 13
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: reflection_test.py    License: MIT License 6 votes vote down vote up
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
Example 14
Project: sklearn-theano   Author: sklearn-theano   File: descriptor.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ProtoTypeToCppProtoType(proto_type):
    """Converts from a Python proto type to a C++ Proto Type.

    The Python ProtocolBuffer classes specify both the 'Python' datatype and the
    'C++' datatype - and they're not the same. This helper method should
    translate from one to another.

    Args:
      proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
    Returns:
      descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
    Raises:
      TypeTransformationError: when the Python proto type isn't known.
    """
    try:
      return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
    except KeyError:
      raise TypeTransformationError('Unknown proto_type: %s' % proto_type) 
Example 15
Project: sklearn-theano   Author: sklearn-theano   File: descriptor.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, name, package, options=None, serialized_pb=None,
               dependencies=None, syntax=None):
    """Constructor."""
    super(FileDescriptor, self).__init__(options, 'FileOptions')

    self.message_types_by_name = {}
    self.name = name
    self.package = package
    self.syntax = syntax or "proto2"
    self.serialized_pb = serialized_pb

    self.enum_types_by_name = {}
    self.extensions_by_name = {}
    self.dependencies = (dependencies or [])

    if (api_implementation.Type() == 'cpp' and
        self.serialized_pb is not None):
      _message.default_pool.AddSerializedFile(self.serialized_pb) 
Example 16
Project: sklearn-theano   Author: sklearn-theano   File: reflection_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testClear(self):
    proto = unittest_pb2.TestAllTypes()
    # C++ implementation does not support lazy fields right now so leave it
    # out for now.
    if api_implementation.Type() == 'python':
      test_util.SetAllFields(proto)
    else:
      test_util.SetAllNonLazyFields(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllTypes()
    self.assertEqual(proto, empty_proto)

    # Test if extensions which were set are cleared.
    proto = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllExtensions()
    self.assertEqual(proto, empty_proto) 
Example 17
Project: sklearn-theano   Author: sklearn-theano   File: reflection_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
Example 18
Project: sklearn-theano   Author: sklearn-theano   File: unknown_fields_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
    self.descriptor = missing_enum_values_pb2.TestEnumValues.DESCRIPTOR

    self.message = missing_enum_values_pb2.TestEnumValues()
    self.message.optional_nested_enum = (
      missing_enum_values_pb2.TestEnumValues.ZERO)
    self.message.repeated_nested_enum.extend([
      missing_enum_values_pb2.TestEnumValues.ZERO,
      missing_enum_values_pb2.TestEnumValues.ONE,
      ])
    self.message.packed_nested_enum.extend([
      missing_enum_values_pb2.TestEnumValues.ZERO,
      missing_enum_values_pb2.TestEnumValues.ONE,
      ])
    self.message_data = self.message.SerializeToString()
    self.missing_message = missing_enum_values_pb2.TestMissingEnumValues()
    self.missing_message.ParseFromString(self.message_data)
    if api_implementation.Type() != 'cpp':
      # _unknown_fields is an implementation detail.
      self.unknown_fields = self.missing_message._unknown_fields

  # All the tests that use GetField() check an implementation detail of the
  # Python implementation, which stores unknown fields as serialized strings.
  # These tests are skipped by the C++ implementation: it's enough to check that
  # the message is correctly serialized. 
Example 19
Project: botchallenge   Author: katharosada   File: descriptor.py    License: MIT License 6 votes vote down vote up
def ProtoTypeToCppProtoType(proto_type):
    """Converts from a Python proto type to a C++ Proto Type.

    The Python ProtocolBuffer classes specify both the 'Python' datatype and the
    'C++' datatype - and they're not the same. This helper method should
    translate from one to another.

    Args:
      proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
    Returns:
      descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
    Raises:
      TypeTransformationError: when the Python proto type isn't known.
    """
    try:
      return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
    except KeyError:
      raise TypeTransformationError('Unknown proto_type: %s' % proto_type) 
Example 20
Project: botchallenge   Author: katharosada   File: descriptor.py    License: MIT License 6 votes vote down vote up
def __init__(self, name, package, options=None, serialized_pb=None,
               dependencies=None):
    """Constructor."""
    super(FileDescriptor, self).__init__(options, 'FileOptions')

    self.message_types_by_name = {}
    self.name = name
    self.package = package
    self.serialized_pb = serialized_pb

    self.enum_types_by_name = {}
    self.extensions_by_name = {}
    self.dependencies = (dependencies or [])

    if (api_implementation.Type() == 'cpp' and
        self.serialized_pb is not None):
      if api_implementation.Version() == 2:
        # pylint: disable=protected-access
        _message.Message._BuildFile(self.serialized_pb)
        # pylint: enable=protected-access
      else:
        cpp_message.BuildFile(self.serialized_pb) 
Example 21
Project: botchallenge   Author: katharosada   File: reflection_test.py    License: MIT License 6 votes vote down vote up
def testClear(self):
    proto = unittest_pb2.TestAllTypes()
    # C++ implementation does not support lazy fields right now so leave it
    # out for now.
    if api_implementation.Type() == 'python':
      test_util.SetAllFields(proto)
    else:
      test_util.SetAllNonLazyFields(proto)
    # Clear the message.
    proto.Clear()
    self.assertEquals(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllTypes()
    self.assertEquals(proto, empty_proto)

    # Test if extensions which were set are cleared.
    proto = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(proto)
    # Clear the message.
    proto.Clear()
    self.assertEquals(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllExtensions()
    self.assertEquals(proto, empty_proto) 
Example 22
Project: coremltools   Author: apple   File: descriptor.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ProtoTypeToCppProtoType(proto_type):
    """Converts from a Python proto type to a C++ Proto Type.

    The Python ProtocolBuffer classes specify both the 'Python' datatype and the
    'C++' datatype - and they're not the same. This helper method should
    translate from one to another.

    Args:
      proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
    Returns:
      descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
    Raises:
      TypeTransformationError: when the Python proto type isn't known.
    """
    try:
      return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]
    except KeyError:
      raise TypeTransformationError('Unknown proto_type: %s' % proto_type) 
Example 23
Project: coremltools   Author: apple   File: descriptor.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, name, package, options=None, serialized_pb=None,
               dependencies=None, public_dependencies=None,
               syntax=None, pool=None):
    """Constructor."""
    super(FileDescriptor, self).__init__(options, 'FileOptions')

    if pool is None:
      from google.protobuf import descriptor_pool
      pool = descriptor_pool.Default()
    self.pool = pool
    self.message_types_by_name = {}
    self.name = name
    self.package = package
    self.syntax = syntax or "proto2"
    self.serialized_pb = serialized_pb

    self.enum_types_by_name = {}
    self.extensions_by_name = {}
    self.services_by_name = {}
    self.dependencies = (dependencies or [])
    self.public_dependencies = (public_dependencies or [])

    if (api_implementation.Type() == 'cpp' and
        self.serialized_pb is not None):
      _message.default_pool.AddSerializedFile(self.serialized_pb) 
Example 24
Project: coremltools   Author: apple   File: reflection_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testClear(self):
    proto = unittest_pb2.TestAllTypes()
    # C++ implementation does not support lazy fields right now so leave it
    # out for now.
    if api_implementation.Type() == 'python':
      test_util.SetAllFields(proto)
    else:
      test_util.SetAllNonLazyFields(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllTypes()
    self.assertEqual(proto, empty_proto)

    # Test if extensions which were set are cleared.
    proto = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(proto)
    # Clear the message.
    proto.Clear()
    self.assertEqual(proto.ByteSize(), 0)
    empty_proto = unittest_pb2.TestAllExtensions()
    self.assertEqual(proto, empty_proto) 
Example 25
Project: lambda-packs   Author: ryfeus   File: descriptor.py    License: MIT License 5 votes vote down vote up
def __init__(self, name, package, options=None,
               serialized_options=None, serialized_pb=None,
               dependencies=None, public_dependencies=None,
               syntax=None, pool=None):
    """Constructor."""
    super(FileDescriptor, self).__init__(
        options, serialized_options, 'FileOptions')

    if pool is None:
      from google.protobuf import descriptor_pool
      pool = descriptor_pool.Default()
    self.pool = pool
    self.message_types_by_name = {}
    self.name = name
    self.package = package
    self.syntax = syntax or "proto2"
    self.serialized_pb = serialized_pb

    self.enum_types_by_name = {}
    self.extensions_by_name = {}
    self.services_by_name = {}
    self.dependencies = (dependencies or [])
    self.public_dependencies = (public_dependencies or [])

    if (api_implementation.Type() == 'cpp' and
        self.serialized_pb is not None):
      _message.default_pool.AddSerializedFile(self.serialized_pb) 
Example 26
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 5 votes vote down vote up
def testFindFieldByName(self):
    if isinstance(self, SecondaryDescriptorFromDescriptorDB):
      if api_implementation.Type() == 'cpp':
        # TODO(jieluo): Fix cpp extension to find field correctly
        # when descriptor pool is using an underlying database.
        return
    field = self.pool.FindFieldByName(
        'google.protobuf.python.internal.Factory1Message.list_value')
    self.assertEqual(field.name, 'list_value')
    self.assertEqual(field.label, field.LABEL_REPEATED)
    self.assertFalse(field.has_options)

    with self.assertRaises(KeyError):
      self.pool.FindFieldByName('Does not exist') 
Example 27
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 5 votes vote down vote up
def testAddSerializedFile(self):
    if isinstance(self, SecondaryDescriptorFromDescriptorDB):
      if api_implementation.Type() == 'cpp':
        # Cpp extension cannot call Add on a DescriptorPool
        # that uses a DescriptorDatabase.
        # TODO(jieluo): Fix python and cpp extension diff.
        return
    self.pool = descriptor_pool.DescriptorPool()
    self.pool.AddSerializedFile(self.factory_test1_fd.SerializeToString())
    self.pool.AddSerializedFile(self.factory_test2_fd.SerializeToString())
    self.testFindMessageTypeByName() 
Example 28
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 5 votes vote down vote up
def testEnumDefaultValue(self):
    """Test the default value of enums which don't start at zero."""
    def _CheckDefaultValue(file_descriptor):
      default_value = (file_descriptor
                       .message_types_by_name['DescriptorPoolTest1']
                       .fields_by_name['nested_enum']
                       .default_value)
      self.assertEqual(default_value,
                       descriptor_pool_test1_pb2.DescriptorPoolTest1.BETA)
    # First check what the generated descriptor contains.
    _CheckDefaultValue(descriptor_pool_test1_pb2.DESCRIPTOR)
    # Then check the generated pool. Normally this is the same descriptor.
    file_descriptor = symbol_database.Default().pool.FindFileByName(
        'google/protobuf/internal/descriptor_pool_test1.proto')
    self.assertIs(file_descriptor, descriptor_pool_test1_pb2.DESCRIPTOR)
    _CheckDefaultValue(file_descriptor)

    if isinstance(self, SecondaryDescriptorFromDescriptorDB):
      if api_implementation.Type() == 'cpp':
        # Cpp extension cannot call Add on a DescriptorPool
        # that uses a DescriptorDatabase.
        # TODO(jieluo): Fix python and cpp extension diff.
        return
    # Then check the dynamic pool and its internal DescriptorDatabase.
    descriptor_proto = descriptor_pb2.FileDescriptorProto.FromString(
        descriptor_pool_test1_pb2.DESCRIPTOR.serialized_pb)
    self.pool.Add(descriptor_proto)
    # And do the same check as above
    file_descriptor = self.pool.FindFileByName(
        'google/protobuf/internal/descriptor_pool_test1.proto')
    _CheckDefaultValue(file_descriptor) 
Example 29
Project: lambda-packs   Author: ryfeus   File: descriptor_pool_test.py    License: MIT License 5 votes vote down vote up
def testAddFileDescriptor(self):
    if isinstance(self, SecondaryDescriptorFromDescriptorDB):
      if api_implementation.Type() == 'cpp':
        # Cpp extension cannot call Add on a DescriptorPool
        # that uses a DescriptorDatabase.
        # TODO(jieluo): Fix python and cpp extension diff.
        return
    file_desc = descriptor_pb2.FileDescriptorProto(name='some/file.proto')
    self.pool.Add(file_desc)
    self.pool.AddSerializedFile(file_desc.SerializeToString()) 
Example 30
Project: lambda-packs   Author: ryfeus   File: reflection_test.py    License: MIT License 5 votes vote down vote up
def testDisconnectingLazyNestedMessage(self):
    # This test exercises releasing a nested message that is lazy. This test
    # only exercises real code in the C++ implementation as Python does not
    # support lazy parsing, but the current C++ implementation results in
    # memory corruption and a crash.
    if api_implementation.Type() != 'python':
      return
    proto = unittest_pb2.TestAllTypes()
    proto.optional_lazy_message.bb = 5
    proto.ClearField('optional_lazy_message')
    del proto
    gc.collect()