Python google.protobuf.internal.api_implementation.Type() Examples
The following are 30
code examples of google.protobuf.internal.api_implementation.Type().
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.internal.api_implementation
, or try the search function
.
Example #1
Source File: reflection_test.py From coremltools with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #2
Source File: reflection_test.py From lambda-packs with MIT License | 6 votes |
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 #3
Source File: descriptor_pool_test.py From lambda-packs with MIT License | 6 votes |
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 #4
Source File: descriptor_pool_test.py From lambda-packs with MIT License | 6 votes |
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 #5
Source File: descriptor_pool_test.py From lambda-packs with MIT License | 6 votes |
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 #6
Source File: descriptor_pool_test.py From lambda-packs with MIT License | 6 votes |
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 #7
Source File: message_test.py From lambda-packs with MIT License | 6 votes |
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
Source File: message_test.py From lambda-packs with MIT License | 6 votes |
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
Source File: descriptor_test.py From lambda-packs with MIT License | 6 votes |
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
Source File: descriptor.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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
Source File: descriptor.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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
Source File: reflection_test.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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
Source File: descriptor.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #14
Source File: descriptor.py From lambda-packs with MIT License | 6 votes |
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
Source File: descriptor.py From coremltools with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #16
Source File: descriptor.py From coremltools with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #17
Source File: reflection_test.py From botchallenge with MIT License | 6 votes |
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 #18
Source File: descriptor.py From botchallenge with MIT License | 6 votes |
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 #19
Source File: descriptor.py From botchallenge with MIT License | 6 votes |
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
Source File: unknown_fields_test.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #21
Source File: reflection_test.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #22
Source File: reflection_test.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #23
Source File: descriptor.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #24
Source File: reflection_test.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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 #25
Source File: descriptor_python_test.py From botchallenge with MIT License | 5 votes |
def testImplementationSetting(self): self.assertEqual('python', api_implementation.Type())
Example #26
Source File: reflection_test.py From botchallenge with MIT License | 5 votes |
def testCopyFromBadType(self): # The python implementation doesn't raise an exception in this # case. In theory it should. if api_implementation.Type() == 'python': return proto1 = unittest_pb2.TestAllTypes() proto2 = unittest_pb2.TestAllExtensions() self.assertRaises(TypeError, proto1.CopyFrom, proto2)
Example #27
Source File: descriptor_pool_test.py From lambda-packs with MIT License | 5 votes |
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
Source File: descriptor_pool_test.py From lambda-packs with MIT License | 5 votes |
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
Source File: unknown_fields_test.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 5 votes |
def setUp(self): self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR self.all_fields = unittest_pb2.TestAllTypes() test_util.SetAllFields(self.all_fields) self.all_fields_data = self.all_fields.SerializeToString() self.empty_message = unittest_pb2.TestEmptyMessage() self.empty_message.ParseFromString(self.all_fields_data) if api_implementation.Type() != 'cpp': # _unknown_fields is an implementation detail. self.unknown_fields = self.empty_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 #30
Source File: reflection_test.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testParseTruncated(self): # This test is only applicable for the Python implementation of the API. if api_implementation.Type() != 'python': return first_proto = unittest_pb2.TestAllTypes() test_util.SetAllFields(first_proto) serialized = first_proto.SerializeToString() for truncation_point in range(len(serialized) + 1): try: second_proto = unittest_pb2.TestAllTypes() unknown_fields = unittest_pb2.TestEmptyMessage() pos = second_proto._InternalParse(serialized, 0, truncation_point) # If we didn't raise an error then we read exactly the amount expected. self.assertEqual(truncation_point, pos) # Parsing to unknown fields should not throw if parsing to known fields # did not. try: pos2 = unknown_fields._InternalParse(serialized, 0, truncation_point) self.assertEqual(truncation_point, pos2) except message.DecodeError: self.fail('Parsing unknown fields failed when parsing known fields ' 'did not.') except message.DecodeError: # Parsing unknown fields should also fail. self.assertRaises(message.DecodeError, unknown_fields._InternalParse, serialized, 0, truncation_point)