Upgrade linux protobuf from 3.19.1 -> 21.12

This commit is contained in:
John Colvin committed 2023-03-18 15:31:41 -04:00
1 parent 4a3e40193e
commit 01a4bb004a
554 files changed
+34981 -37969

No files matched your search

+1 -1
View File
@@ -30,4 +30,4 @@
# Copyright 2007 Google Inc. All Rights Reserved.
__version__ = '3.19.1'
__version__ = '4.21.12'
+3 -12
View File
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/any.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,16 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/any.proto\x12\x0fgoogle.protobuf\"&\n\x03\x41ny\x12\x10\n\x08type_url\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c\x42v\n\x13\x63om.google.protobufB\x08\x41nyProtoP\x01Z,google.golang.org/protobuf/types/known/anypb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
_ANY = DESCRIPTOR.message_types_by_name['Any']
Any = _reflection.GeneratedProtocolMessageType('Any', (_message.Message,), {
'DESCRIPTOR' : _ANY,
'__module__' : 'google.protobuf.any_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.Any)
})
_sym_db.RegisterMessage(Any)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.any_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
+3 -12
View File
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/any_test.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -17,16 +16,8 @@ from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1egoogle/protobuf/any_test.proto\x12\x11protobuf_unittest\x1a\x19google/protobuf/any.proto\"\x87\x01\n\x07TestAny\x12\x13\n\x0bint32_value\x18\x01 \x01(\x05\x12\'\n\tany_value\x18\x02 \x01(\x0b\x32\x14.google.protobuf.Any\x12\x30\n\x12repeated_any_value\x18\x03 \x03(\x0b\x32\x14.google.protobuf.Any\x12\x0c\n\x04text\x18\x04 \x01(\tB\x0e\x42\x0cTestAnyProtob\x06proto3')
_TESTANY = DESCRIPTOR.message_types_by_name['TestAny']
TestAny = _reflection.GeneratedProtocolMessageType('TestAny', (_message.Message,), {
'DESCRIPTOR' : _TESTANY,
'__module__' : 'google.protobuf.any_test_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestAny)
})
_sym_db.RegisterMessage(TestAny)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.any_test_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
+3 -28
View File
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/api.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -18,32 +17,8 @@ from google.protobuf import type_pb2 as google_dot_protobuf_dot_type__pb2
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/api.proto\x12\x0fgoogle.protobuf\x1a$google/protobuf/source_context.proto\x1a\x1agoogle/protobuf/type.proto\"\x81\x02\n\x03\x41pi\x12\x0c\n\x04name\x18\x01 \x01(\t\x12(\n\x07methods\x18\x02 \x03(\x0b\x32\x17.google.protobuf.Method\x12(\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.Option\x12\x0f\n\x07version\x18\x04 \x01(\t\x12\x36\n\x0esource_context\x18\x05 \x01(\x0b\x32\x1e.google.protobuf.SourceContext\x12&\n\x06mixins\x18\x06 \x03(\x0b\x32\x16.google.protobuf.Mixin\x12\'\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.Syntax\"\xd5\x01\n\x06Method\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x18\n\x10request_type_url\x18\x02 \x01(\t\x12\x19\n\x11request_streaming\x18\x03 \x01(\x08\x12\x19\n\x11response_type_url\x18\x04 \x01(\t\x12\x1a\n\x12response_streaming\x18\x05 \x01(\x08\x12(\n\x07options\x18\x06 \x03(\x0b\x32\x17.google.protobuf.Option\x12\'\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.Syntax\"#\n\x05Mixin\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04root\x18\x02 \x01(\tBv\n\x13\x63om.google.protobufB\x08\x41piProtoP\x01Z,google.golang.org/protobuf/types/known/apipb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
_API = DESCRIPTOR.message_types_by_name['Api']
_METHOD = DESCRIPTOR.message_types_by_name['Method']
_MIXIN = DESCRIPTOR.message_types_by_name['Mixin']
Api = _reflection.GeneratedProtocolMessageType('Api', (_message.Message,), {
'DESCRIPTOR' : _API,
'__module__' : 'google.protobuf.api_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.Api)
})
_sym_db.RegisterMessage(Api)
Method = _reflection.GeneratedProtocolMessageType('Method', (_message.Message,), {
'DESCRIPTOR' : _METHOD,
'__module__' : 'google.protobuf.api_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.Method)
})
_sym_db.RegisterMessage(Method)
Mixin = _reflection.GeneratedProtocolMessageType('Mixin', (_message.Message,), {
'DESCRIPTOR' : _MIXIN,
'__module__' : 'google.protobuf.api_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.Mixin)
})
_sym_db.RegisterMessage(Mixin)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.api_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/compiler/plugin.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -17,42 +16,8 @@ from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%google/protobuf/compiler/plugin.proto\x12\x18google.protobuf.compiler\x1a google/protobuf/descriptor.proto\"F\n\x07Version\x12\r\n\x05major\x18\x01 \x01(\x05\x12\r\n\x05minor\x18\x02 \x01(\x05\x12\r\n\x05patch\x18\x03 \x01(\x05\x12\x0e\n\x06suffix\x18\x04 \x01(\t\"\xba\x01\n\x14\x43odeGeneratorRequest\x12\x18\n\x10\x66ile_to_generate\x18\x01 \x03(\t\x12\x11\n\tparameter\x18\x02 \x01(\t\x12\x38\n\nproto_file\x18\x0f \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\x12;\n\x10\x63ompiler_version\x18\x03 \x01(\x0b\x32!.google.protobuf.compiler.Version\"\xc1\x02\n\x15\x43odeGeneratorResponse\x12\r\n\x05\x65rror\x18\x01 \x01(\t\x12\x1a\n\x12supported_features\x18\x02 \x01(\x04\x12\x42\n\x04\x66ile\x18\x0f \x03(\x0b\x32\x34.google.protobuf.compiler.CodeGeneratorResponse.File\x1a\x7f\n\x04\x46ile\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0finsertion_point\x18\x02 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x0f \x01(\t\x12?\n\x13generated_code_info\x18\x10 \x01(\x0b\x32\".google.protobuf.GeneratedCodeInfo\"8\n\x07\x46\x65\x61ture\x12\x10\n\x0c\x46\x45\x41TURE_NONE\x10\x00\x12\x1b\n\x17\x46\x45\x41TURE_PROTO3_OPTIONAL\x10\x01\x42W\n\x1c\x63om.google.protobuf.compilerB\x0cPluginProtosZ)google.golang.org/protobuf/types/pluginpb')
_VERSION = DESCRIPTOR.message_types_by_name['Version']
_CODEGENERATORREQUEST = DESCRIPTOR.message_types_by_name['CodeGeneratorRequest']
_CODEGENERATORRESPONSE = DESCRIPTOR.message_types_by_name['CodeGeneratorResponse']
_CODEGENERATORRESPONSE_FILE = _CODEGENERATORRESPONSE.nested_types_by_name['File']
_CODEGENERATORRESPONSE_FEATURE = _CODEGENERATORRESPONSE.enum_types_by_name['Feature']
Version = _reflection.GeneratedProtocolMessageType('Version', (_message.Message,), {
'DESCRIPTOR' : _VERSION,
'__module__' : 'google.protobuf.compiler.plugin_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.compiler.Version)
})
_sym_db.RegisterMessage(Version)
CodeGeneratorRequest = _reflection.GeneratedProtocolMessageType('CodeGeneratorRequest', (_message.Message,), {
'DESCRIPTOR' : _CODEGENERATORREQUEST,
'__module__' : 'google.protobuf.compiler.plugin_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorRequest)
})
_sym_db.RegisterMessage(CodeGeneratorRequest)
CodeGeneratorResponse = _reflection.GeneratedProtocolMessageType('CodeGeneratorResponse', (_message.Message,), {
'File' : _reflection.GeneratedProtocolMessageType('File', (_message.Message,), {
'DESCRIPTOR' : _CODEGENERATORRESPONSE_FILE,
'__module__' : 'google.protobuf.compiler.plugin_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse.File)
})
,
'DESCRIPTOR' : _CODEGENERATORRESPONSE,
'__module__' : 'google.protobuf.compiler.plugin_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse)
})
_sym_db.RegisterMessage(CodeGeneratorResponse)
_sym_db.RegisterMessage(CodeGeneratorResponse.File)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.compiler.plugin_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
+57 -11
View File
@@ -40,11 +40,15 @@ import warnings
from google.protobuf.internal import api_implementation
_USE_C_DESCRIPTORS = False
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
# Used by MakeDescriptor in cpp mode
import binascii
import os
from google.protobuf.pyext import _message
# pylint: disable=protected-access
_message = api_implementation._c_module
# TODO(jieluo): Remove this import after fix api_implementation
if _message is None:
from google.protobuf.pyext import _message
_USE_C_DESCRIPTORS = True
@@ -598,13 +602,13 @@ class FieldDescriptor(DescriptorBase):
self.is_extension = is_extension
self.extension_scope = extension_scope
self.containing_oneof = containing_oneof
if api_implementation.Type() == 'cpp':
if api_implementation.Type() == 'python':
self._cdescriptor = None
else:
if is_extension:
self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
else:
self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
else:
self._cdescriptor = None
@property
def camelcase_name(self):
@@ -617,6 +621,26 @@ class FieldDescriptor(DescriptorBase):
self._camelcase_name = _ToCamelCase(self.name)
return self._camelcase_name
@property
def has_presence(self):
"""Whether the field distinguishes between unpopulated and default values.
Raises:
RuntimeError: singular field that is not linked with message nor file.
"""
if self.label == FieldDescriptor.LABEL_REPEATED:
return False
if (self.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE or
self.containing_oneof):
return True
if hasattr(self.file, 'syntax'):
return self.file.syntax == 'proto2'
if hasattr(self.message_type, 'syntax'):
return self.message_type.syntax == 'proto2'
raise RuntimeError(
'has_presence is not ready to use because field %s is not'
' linked with message type nor file' % self.full_name)
@staticmethod
def ProtoTypeToCppProtoType(proto_type):
"""Converts from a Python proto type to a C++ Proto Type.
@@ -647,7 +671,7 @@ class EnumDescriptor(_NestedDescriptorBase):
full_name (str): Full name of the type, including package name
and any enclosing type(s).
values (list[EnumValueDescriptors]): List of the values
values (list[EnumValueDescriptor]): List of the values
in this enum.
values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`,
but indexed by the "name" field of each EnumValueDescriptor.
@@ -879,6 +903,8 @@ class MethodDescriptor(DescriptorBase):
accepts.
output_type (Descriptor): The descriptor of the message that this method
returns.
client_streaming (bool): Whether this method uses client streaming.
server_streaming (bool): Whether this method uses server streaming.
options (descriptor_pb2.MethodOptions or None): Method options message, or
None to use default method options.
"""
@@ -886,14 +912,32 @@ class MethodDescriptor(DescriptorBase):
if _USE_C_DESCRIPTORS:
_C_DESCRIPTOR_CLASS = _message.MethodDescriptor
def __new__(cls, name, full_name, index, containing_service,
input_type, output_type, options=None, serialized_options=None,
def __new__(cls,
name,
full_name,
index,
containing_service,
input_type,
output_type,
client_streaming=False,
server_streaming=False,
options=None,
serialized_options=None,
create_key=None):
_message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access
return _message.default_pool.FindMethodByName(full_name)
def __init__(self, name, full_name, index, containing_service,
input_type, output_type, options=None, serialized_options=None,
def __init__(self,
name,
full_name,
index,
containing_service,
input_type,
output_type,
client_streaming=False,
server_streaming=False,
options=None,
serialized_options=None,
create_key=None):
"""The arguments are as described in the description of MethodDescriptor
attributes above.
@@ -911,6 +955,8 @@ class MethodDescriptor(DescriptorBase):
self.containing_service = containing_service
self.input_type = input_type
self.output_type = output_type
self.client_streaming = client_streaming
self.server_streaming = server_streaming
def CopyToProto(self, proto):
"""Copies this to a descriptor_pb2.MethodDescriptorProto.
@@ -1093,7 +1139,7 @@ def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
Returns:
A Descriptor for protobuf messages.
"""
if api_implementation.Type() == 'cpp' and build_file_if_cpp:
if api_implementation.Type() != 'python' and build_file_if_cpp:
# The C++ implementation requires all descriptors to be backed by the same
# definition in the C++ descriptor pool. To do this, we build a
# FileDescriptorProto with the same definition as this descriptor and build
+44 -266
View File
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/descriptor.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -21,12 +20,10 @@ if _descriptor._USE_C_DESCRIPTORS == False:
syntax='proto2',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"G\n\x11\x46ileDescriptorSet\x12\x32\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xdb\x03\n\x13\x46ileDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07package\x18\x02 \x01(\t\x12\x12\n\ndependency\x18\x03 \x03(\t\x12\x19\n\x11public_dependency\x18\n \x03(\x05\x12\x17\n\x0fweak_dependency\x18\x0b \x03(\x05\x12\x36\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12\x38\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProto\x12\x38\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12-\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x39\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfo\x12\x0e\n\x06syntax\x18\x0c \x01(\t\"\xa9\x05\n\x0f\x44\x65scriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x38\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x35\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12H\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRange\x12\x39\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProto\x12\x30\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptions\x12\x46\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRange\x12\x15\n\rreserved_name\x18\n \x03(\t\x1a\x65\n\x0e\x45xtensionRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\x12\x37\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptions\x1a+\n\rReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"g\n\x15\x45xtensionRangeOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x05\n\x14\x46ieldDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12:\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.Label\x12\x38\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.Type\x12\x11\n\ttype_name\x18\x06 \x01(\t\x12\x10\n\x08\x65xtendee\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x07 \x01(\t\x12\x13\n\x0boneof_index\x18\t \x01(\x05\x12\x11\n\tjson_name\x18\n \x01(\t\x12.\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptions\x12\x17\n\x0fproto3_optional\x18\x11 \x01(\x08\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\x12\x12\n\x0eLABEL_REPEATED\x10\x03\"T\n\x14OneofDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12.\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptions\"\xa4\x02\n\x13\x45numDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProto\x12-\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptions\x12N\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRange\x12\x15\n\rreserved_name\x18\x05 \x03(\t\x1a/\n\x11\x45numReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"l\n\x18\x45numValueDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12\x32\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptions\"\x90\x01\n\x16ServiceDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProto\x12\x30\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptions\"\xc1\x01\n\x15MethodDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ninput_type\x18\x02 \x01(\t\x12\x13\n\x0boutput_type\x18\x03 \x01(\t\x12/\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptions\x12\x1f\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lse\"\xa5\x06\n\x0b\x46ileOptions\x12\x14\n\x0cjava_package\x18\x01 \x01(\t\x12\x1c\n\x14java_outer_classname\x18\x08 \x01(\t\x12\"\n\x13Line truncated
serialized_pb=b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"G\n\x11\x46ileDescriptorSet\x12\x32\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xdb\x03\n\x13\x46ileDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07package\x18\x02 \x01(\t\x12\x12\n\ndependency\x18\x03 \x03(\t\x12\x19\n\x11public_dependency\x18\n \x03(\x05\x12\x17\n\x0fweak_dependency\x18\x0b \x03(\x05\x12\x36\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12\x38\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProto\x12\x38\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12-\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x39\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfo\x12\x0e\n\x06syntax\x18\x0c \x01(\t\"\xa9\x05\n\x0f\x44\x65scriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x38\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x35\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12H\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRange\x12\x39\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProto\x12\x30\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptions\x12\x46\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRange\x12\x15\n\rreserved_name\x18\n \x03(\t\x1a\x65\n\x0e\x45xtensionRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\x12\x37\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptions\x1a+\n\rReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"g\n\x15\x45xtensionRangeOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x05\n\x14\x46ieldDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12:\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.Label\x12\x38\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.Type\x12\x11\n\ttype_name\x18\x06 \x01(\t\x12\x10\n\x08\x65xtendee\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x07 \x01(\t\x12\x13\n\x0boneof_index\x18\t \x01(\x05\x12\x11\n\tjson_name\x18\n \x01(\t\x12.\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptions\x12\x17\n\x0fproto3_optional\x18\x11 \x01(\x08\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\x12\x12\n\x0eLABEL_REPEATED\x10\x03\"T\n\x14OneofDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12.\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptions\"\xa4\x02\n\x13\x45numDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProto\x12-\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptions\x12N\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRange\x12\x15\n\rreserved_name\x18\x05 \x03(\t\x1a/\n\x11\x45numReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"l\n\x18\x45numValueDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12\x32\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptions\"\x90\x01\n\x16ServiceDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProto\x12\x30\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptions\"\xc1\x01\n\x15MethodDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ninput_type\x18\x02 \x01(\t\x12\x13\n\x0boutput_type\x18\x03 \x01(\t\x12/\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptions\x12\x1f\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lse\"\xa5\x06\n\x0b\x46ileOptions\x12\x14\n\x0cjava_package\x18\x01 \x01(\t\x12\x1c\n\x14java_outer_classname\x18\x08 \x01(\t\x12\"\n\x13Line truncated
)
else:
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"G\n\x11\x46ileDescriptorSet\x12\x32\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xdb\x03\n\x13\x46ileDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07package\x18\x02 \x01(\t\x12\x12\n\ndependency\x18\x03 \x03(\t\x12\x19\n\x11public_dependency\x18\n \x03(\x05\x12\x17\n\x0fweak_dependency\x18\x0b \x03(\x05\x12\x36\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12\x38\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProto\x12\x38\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12-\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x39\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfo\x12\x0e\n\x06syntax\x18\x0c \x01(\t\"\xa9\x05\n\x0f\x44\x65scriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x38\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x35\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12H\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRange\x12\x39\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProto\x12\x30\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptions\x12\x46\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRange\x12\x15\n\rreserved_name\x18\n \x03(\t\x1a\x65\n\x0e\x45xtensionRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\x12\x37\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptions\x1a+\n\rReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"g\n\x15\x45xtensionRangeOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x05\n\x14\x46ieldDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12:\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.Label\x12\x38\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.Type\x12\x11\n\ttype_name\x18\x06 \x01(\t\x12\x10\n\x08\x65xtendee\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x07 \x01(\t\x12\x13\n\x0boneof_index\x18\t \x01(\x05\x12\x11\n\tjson_name\x18\n \x01(\t\x12.\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptions\x12\x17\n\x0fproto3_optional\x18\x11 \x01(\x08\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\x12\x12\n\x0eLABEL_REPEATED\x10\x03\"T\n\x14OneofDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12.\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptions\"\xa4\x02\n\x13\x45numDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProto\x12-\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptions\x12N\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRange\x12\x15\n\rreserved_name\x18\x05 \x03(\t\x1a/\n\x11\x45numReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"l\n\x18\x45numValueDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12\x32\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptions\"\x90\x01\n\x16ServiceDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProto\x12\x30\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptions\"\xc1\x01\n\x15MethodDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ninput_type\x18\x02 \x01(\t\x12\x13\n\x0boutput_type\x18\x03 \x01(\t\x12/\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptions\x12\x1f\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lse\"\xa5\x06\n\x0b\x46ileOptions\x12\x14\n\x0cjava_package\x18\x01 \x01(\t\x12\x1c\n\x14java_oLine truncated
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"G\n\x11\x46ileDescriptorSet\x12\x32\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xdb\x03\n\x13\x46ileDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07package\x18\x02 \x01(\t\x12\x12\n\ndependency\x18\x03 \x03(\t\x12\x19\n\x11public_dependency\x18\n \x03(\x05\x12\x17\n\x0fweak_dependency\x18\x0b \x03(\x05\x12\x36\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12\x38\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProto\x12\x38\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12-\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x39\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfo\x12\x0e\n\x06syntax\x18\x0c \x01(\t\"\xa9\x05\n\x0f\x44\x65scriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x38\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x35\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12H\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRange\x12\x39\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProto\x12\x30\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptions\x12\x46\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRange\x12\x15\n\rreserved_name\x18\n \x03(\t\x1a\x65\n\x0e\x45xtensionRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\x12\x37\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptions\x1a+\n\rReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"g\n\x15\x45xtensionRangeOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x05\n\x14\x46ieldDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12:\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.Label\x12\x38\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.Type\x12\x11\n\ttype_name\x18\x06 \x01(\t\x12\x10\n\x08\x65xtendee\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x07 \x01(\t\x12\x13\n\x0boneof_index\x18\t \x01(\x05\x12\x11\n\tjson_name\x18\n \x01(\t\x12.\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptions\x12\x17\n\x0fproto3_optional\x18\x11 \x01(\x08\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\x12\x12\n\x0eLABEL_REPEATED\x10\x03\"T\n\x14OneofDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12.\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptions\"\xa4\x02\n\x13\x45numDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProto\x12-\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptions\x12N\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRange\x12\x15\n\rreserved_name\x18\x05 \x03(\t\x1a/\n\x11\x45numReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"l\n\x18\x45numValueDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12\x32\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptions\"\x90\x01\n\x16ServiceDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProto\x12\x30\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptions\"\xc1\x01\n\x15MethodDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ninput_type\x18\x02 \x01(\t\x12\x13\n\x0boutput_type\x18\x03 \x01(\t\x12/\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptions\x12\x1f\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lse\"\xa5\x06\n\x0b\x46ileOptions\x12\x14\n\x0cjava_package\x18\x01 \x01(\t\x12\x1c\n\x14java_oLine truncated
if _descriptor._USE_C_DESCRIPTORS == False:
_FIELDDESCRIPTORPROTO_TYPE = _descriptor.EnumDescriptor(
@@ -1264,21 +1261,28 @@ if _descriptor._USE_C_DESCRIPTORS == False:
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deprecated', full_name='google.protobuf.FieldOptions.deprecated', index=4,
name='unverified_lazy', full_name='google.protobuf.FieldOptions.unverified_lazy', index=4,
number=15, type=8, cpp_type=7, label=1,
has_default_value=True, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='deprecated', full_name='google.protobuf.FieldOptions.deprecated', index=5,
number=3, type=8, cpp_type=7, label=1,
has_default_value=True, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='weak', full_name='google.protobuf.FieldOptions.weak', index=5,
name='weak', full_name='google.protobuf.FieldOptions.weak', index=6,
number=10, type=8, cpp_type=7, label=1,
has_default_value=True, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='uninterpreted_option', full_name='google.protobuf.FieldOptions.uninterpreted_option', index=6,
name='uninterpreted_option', full_name='google.protobuf.FieldOptions.uninterpreted_option', index=7,
number=999, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
@@ -1847,234 +1851,8 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
else:
_FILEDESCRIPTORSET = DESCRIPTOR.message_types_by_name['FileDescriptorSet']
_FILEDESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['FileDescriptorProto']
_DESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['DescriptorProto']
_DESCRIPTORPROTO_EXTENSIONRANGE = _DESCRIPTORPROTO.nested_types_by_name['ExtensionRange']
_DESCRIPTORPROTO_RESERVEDRANGE = _DESCRIPTORPROTO.nested_types_by_name['ReservedRange']
_EXTENSIONRANGEOPTIONS = DESCRIPTOR.message_types_by_name['ExtensionRangeOptions']
_FIELDDESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['FieldDescriptorProto']
_ONEOFDESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['OneofDescriptorProto']
_ENUMDESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['EnumDescriptorProto']
_ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE = _ENUMDESCRIPTORPROTO.nested_types_by_name['EnumReservedRange']
_ENUMVALUEDESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['EnumValueDescriptorProto']
_SERVICEDESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['ServiceDescriptorProto']
_METHODDESCRIPTORPROTO = DESCRIPTOR.message_types_by_name['MethodDescriptorProto']
_FILEOPTIONS = DESCRIPTOR.message_types_by_name['FileOptions']
_MESSAGEOPTIONS = DESCRIPTOR.message_types_by_name['MessageOptions']
_FIELDOPTIONS = DESCRIPTOR.message_types_by_name['FieldOptions']
_ONEOFOPTIONS = DESCRIPTOR.message_types_by_name['OneofOptions']
_ENUMOPTIONS = DESCRIPTOR.message_types_by_name['EnumOptions']
_ENUMVALUEOPTIONS = DESCRIPTOR.message_types_by_name['EnumValueOptions']
_SERVICEOPTIONS = DESCRIPTOR.message_types_by_name['ServiceOptions']
_METHODOPTIONS = DESCRIPTOR.message_types_by_name['MethodOptions']
_UNINTERPRETEDOPTION = DESCRIPTOR.message_types_by_name['UninterpretedOption']
_UNINTERPRETEDOPTION_NAMEPART = _UNINTERPRETEDOPTION.nested_types_by_name['NamePart']
_SOURCECODEINFO = DESCRIPTOR.message_types_by_name['SourceCodeInfo']
_SOURCECODEINFO_LOCATION = _SOURCECODEINFO.nested_types_by_name['Location']
_GENERATEDCODEINFO = DESCRIPTOR.message_types_by_name['GeneratedCodeInfo']
_GENERATEDCODEINFO_ANNOTATION = _GENERATEDCODEINFO.nested_types_by_name['Annotation']
_FIELDDESCRIPTORPROTO_TYPE = _FIELDDESCRIPTORPROTO.enum_types_by_name['Type']
_FIELDDESCRIPTORPROTO_LABEL = _FIELDDESCRIPTORPROTO.enum_types_by_name['Label']
_FILEOPTIONS_OPTIMIZEMODE = _FILEOPTIONS.enum_types_by_name['OptimizeMode']
_FIELDOPTIONS_CTYPE = _FIELDOPTIONS.enum_types_by_name['CType']
_FIELDOPTIONS_JSTYPE = _FIELDOPTIONS.enum_types_by_name['JSType']
_METHODOPTIONS_IDEMPOTENCYLEVEL = _METHODOPTIONS.enum_types_by_name['IdempotencyLevel']
FileDescriptorSet = _reflection.GeneratedProtocolMessageType('FileDescriptorSet', (_message.Message,), {
'DESCRIPTOR' : _FILEDESCRIPTORSET,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorSet)
})
_sym_db.RegisterMessage(FileDescriptorSet)
FileDescriptorProto = _reflection.GeneratedProtocolMessageType('FileDescriptorProto', (_message.Message,), {
'DESCRIPTOR' : _FILEDESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorProto)
})
_sym_db.RegisterMessage(FileDescriptorProto)
DescriptorProto = _reflection.GeneratedProtocolMessageType('DescriptorProto', (_message.Message,), {
'ExtensionRange' : _reflection.GeneratedProtocolMessageType('ExtensionRange', (_message.Message,), {
'DESCRIPTOR' : _DESCRIPTORPROTO_EXTENSIONRANGE,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ExtensionRange)
})
,
'ReservedRange' : _reflection.GeneratedProtocolMessageType('ReservedRange', (_message.Message,), {
'DESCRIPTOR' : _DESCRIPTORPROTO_RESERVEDRANGE,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ReservedRange)
})
,
'DESCRIPTOR' : _DESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto)
})
_sym_db.RegisterMessage(DescriptorProto)
_sym_db.RegisterMessage(DescriptorProto.ExtensionRange)
_sym_db.RegisterMessage(DescriptorProto.ReservedRange)
ExtensionRangeOptions = _reflection.GeneratedProtocolMessageType('ExtensionRangeOptions', (_message.Message,), {
'DESCRIPTOR' : _EXTENSIONRANGEOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.ExtensionRangeOptions)
})
_sym_db.RegisterMessage(ExtensionRangeOptions)
FieldDescriptorProto = _reflection.GeneratedProtocolMessageType('FieldDescriptorProto', (_message.Message,), {
'DESCRIPTOR' : _FIELDDESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.FieldDescriptorProto)
})
_sym_db.RegisterMessage(FieldDescriptorProto)
OneofDescriptorProto = _reflection.GeneratedProtocolMessageType('OneofDescriptorProto', (_message.Message,), {
'DESCRIPTOR' : _ONEOFDESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.OneofDescriptorProto)
})
_sym_db.RegisterMessage(OneofDescriptorProto)
EnumDescriptorProto = _reflection.GeneratedProtocolMessageType('EnumDescriptorProto', (_message.Message,), {
'EnumReservedRange' : _reflection.GeneratedProtocolMessageType('EnumReservedRange', (_message.Message,), {
'DESCRIPTOR' : _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto.EnumReservedRange)
})
,
'DESCRIPTOR' : _ENUMDESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto)
})
_sym_db.RegisterMessage(EnumDescriptorProto)
_sym_db.RegisterMessage(EnumDescriptorProto.EnumReservedRange)
EnumValueDescriptorProto = _reflection.GeneratedProtocolMessageType('EnumValueDescriptorProto', (_message.Message,), {
'DESCRIPTOR' : _ENUMVALUEDESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.EnumValueDescriptorProto)
})
_sym_db.RegisterMessage(EnumValueDescriptorProto)
ServiceDescriptorProto = _reflection.GeneratedProtocolMessageType('ServiceDescriptorProto', (_message.Message,), {
'DESCRIPTOR' : _SERVICEDESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.ServiceDescriptorProto)
})
_sym_db.RegisterMessage(ServiceDescriptorProto)
MethodDescriptorProto = _reflection.GeneratedProtocolMessageType('MethodDescriptorProto', (_message.Message,), {
'DESCRIPTOR' : _METHODDESCRIPTORPROTO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.MethodDescriptorProto)
})
_sym_db.RegisterMessage(MethodDescriptorProto)
FileOptions = _reflection.GeneratedProtocolMessageType('FileOptions', (_message.Message,), {
'DESCRIPTOR' : _FILEOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.FileOptions)
})
_sym_db.RegisterMessage(FileOptions)
MessageOptions = _reflection.GeneratedProtocolMessageType('MessageOptions', (_message.Message,), {
'DESCRIPTOR' : _MESSAGEOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.MessageOptions)
})
_sym_db.RegisterMessage(MessageOptions)
FieldOptions = _reflection.GeneratedProtocolMessageType('FieldOptions', (_message.Message,), {
'DESCRIPTOR' : _FIELDOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.FieldOptions)
})
_sym_db.RegisterMessage(FieldOptions)
OneofOptions = _reflection.GeneratedProtocolMessageType('OneofOptions', (_message.Message,), {
'DESCRIPTOR' : _ONEOFOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.OneofOptions)
})
_sym_db.RegisterMessage(OneofOptions)
EnumOptions = _reflection.GeneratedProtocolMessageType('EnumOptions', (_message.Message,), {
'DESCRIPTOR' : _ENUMOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.EnumOptions)
})
_sym_db.RegisterMessage(EnumOptions)
EnumValueOptions = _reflection.GeneratedProtocolMessageType('EnumValueOptions', (_message.Message,), {
'DESCRIPTOR' : _ENUMVALUEOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.EnumValueOptions)
})
_sym_db.RegisterMessage(EnumValueOptions)
ServiceOptions = _reflection.GeneratedProtocolMessageType('ServiceOptions', (_message.Message,), {
'DESCRIPTOR' : _SERVICEOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.ServiceOptions)
})
_sym_db.RegisterMessage(ServiceOptions)
MethodOptions = _reflection.GeneratedProtocolMessageType('MethodOptions', (_message.Message,), {
'DESCRIPTOR' : _METHODOPTIONS,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.MethodOptions)
})
_sym_db.RegisterMessage(MethodOptions)
UninterpretedOption = _reflection.GeneratedProtocolMessageType('UninterpretedOption', (_message.Message,), {
'NamePart' : _reflection.GeneratedProtocolMessageType('NamePart', (_message.Message,), {
'DESCRIPTOR' : _UNINTERPRETEDOPTION_NAMEPART,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption.NamePart)
})
,
'DESCRIPTOR' : _UNINTERPRETEDOPTION,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption)
})
_sym_db.RegisterMessage(UninterpretedOption)
_sym_db.RegisterMessage(UninterpretedOption.NamePart)
SourceCodeInfo = _reflection.GeneratedProtocolMessageType('SourceCodeInfo', (_message.Message,), {
'Location' : _reflection.GeneratedProtocolMessageType('Location', (_message.Message,), {
'DESCRIPTOR' : _SOURCECODEINFO_LOCATION,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo.Location)
})
,
'DESCRIPTOR' : _SOURCECODEINFO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo)
})
_sym_db.RegisterMessage(SourceCodeInfo)
_sym_db.RegisterMessage(SourceCodeInfo.Location)
GeneratedCodeInfo = _reflection.GeneratedProtocolMessageType('GeneratedCodeInfo', (_message.Message,), {
'Annotation' : _reflection.GeneratedProtocolMessageType('Annotation', (_message.Message,), {
'DESCRIPTOR' : _GENERATEDCODEINFO_ANNOTATION,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.GeneratedCodeInfo.Annotation)
})
,
'DESCRIPTOR' : _GENERATEDCODEINFO,
'__module__' : 'google.protobuf.descriptor_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.GeneratedCodeInfo)
})
_sym_db.RegisterMessage(GeneratedCodeInfo)
_sym_db.RegisterMessage(GeneratedCodeInfo.Annotation)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.descriptor_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -2115,33 +1893,33 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_MESSAGEOPTIONS._serialized_start=3764
_MESSAGEOPTIONS._serialized_end=4024
_FIELDOPTIONS._serialized_start=4027
_FIELDOPTIONS._serialized_end=4441
_FIELDOPTIONS_CTYPE._serialized_start=4322
_FIELDOPTIONS_CTYPE._serialized_end=4369
_FIELDOPTIONS_JSTYPE._serialized_start=4371
_FIELDOPTIONS_JSTYPE._serialized_end=4424
_ONEOFOPTIONS._serialized_start=4443
_ONEOFOPTIONS._serialized_end=4537
_ENUMOPTIONS._serialized_start=4540
_ENUMOPTIONS._serialized_end=4687
_ENUMVALUEOPTIONS._serialized_start=4689
_ENUMVALUEOPTIONS._serialized_end=4814
_SERVICEOPTIONS._serialized_start=4816
_SERVICEOPTIONS._serialized_end=4939
_METHODOPTIONS._serialized_start=4942
_METHODOPTIONS._serialized_end=5243
_METHODOPTIONS_IDEMPOTENCYLEVEL._serialized_start=5152
_METHODOPTIONS_IDEMPOTENCYLEVEL._serialized_end=5232
_UNINTERPRETEDOPTION._serialized_start=5246
_UNINTERPRETEDOPTION._serialized_end=5532
_UNINTERPRETEDOPTION_NAMEPART._serialized_start=5481
_UNINTERPRETEDOPTION_NAMEPART._serialized_end=5532
_SOURCECODEINFO._serialized_start=5535
_SOURCECODEINFO._serialized_end=5748
_SOURCECODEINFO_LOCATION._serialized_start=5614
_SOURCECODEINFO_LOCATION._serialized_end=5748
_GENERATEDCODEINFO._serialized_start=5751
_GENERATEDCODEINFO._serialized_end=5918
_GENERATEDCODEINFO_ANNOTATION._serialized_start=5839
_GENERATEDCODEINFO_ANNOTATION._serialized_end=5918
_FIELDOPTIONS._serialized_end=4473
_FIELDOPTIONS_CTYPE._serialized_start=4354
_FIELDOPTIONS_CTYPE._serialized_end=4401
_FIELDOPTIONS_JSTYPE._serialized_start=4403
_FIELDOPTIONS_JSTYPE._serialized_end=4456
_ONEOFOPTIONS._serialized_start=4475
_ONEOFOPTIONS._serialized_end=4569
_ENUMOPTIONS._serialized_start=4572
_ENUMOPTIONS._serialized_end=4719
_ENUMVALUEOPTIONS._serialized_start=4721
_ENUMVALUEOPTIONS._serialized_end=4846
_SERVICEOPTIONS._serialized_start=4848
_SERVICEOPTIONS._serialized_end=4971
_METHODOPTIONS._serialized_start=4974
_METHODOPTIONS._serialized_end=5275
_METHODOPTIONS_IDEMPOTENCYLEVEL._serialized_start=5184
_METHODOPTIONS_IDEMPOTENCYLEVEL._serialized_end=5264
_UNINTERPRETEDOPTION._serialized_start=5278
_UNINTERPRETEDOPTION._serialized_end=5564
_UNINTERPRETEDOPTION_NAMEPART._serialized_start=5513
_UNINTERPRETEDOPTION_NAMEPART._serialized_end=5564
_SOURCECODEINFO._serialized_start=5567
_SOURCECODEINFO._serialized_end=5780
_SOURCECODEINFO_LOCATION._serialized_start=5646
_SOURCECODEINFO_LOCATION._serialized_end=5780
_GENERATEDCODEINFO._serialized_start=5783
_GENERATEDCODEINFO._serialized_end=5950
_GENERATEDCODEINFO_ANNOTATION._serialized_start=5871
_GENERATEDCODEINFO_ANNOTATION._serialized_end=5950
# @@protoc_insertion_point(module_scope)
@@ -1213,6 +1213,8 @@ class DescriptorPool(object):
containing_service=None,
input_type=input_type,
output_type=output_type,
client_streaming=method_proto.client_streaming,
server_streaming=method_proto.server_streaming,
options=_OptionsOrNone(method_proto),
# pylint: disable=protected-access
create_key=descriptor._internal_create_key)
@@ -1233,21 +1235,25 @@ class DescriptorPool(object):
for enum in desc.enum_types:
yield (_PrefixWithDot(enum.full_name), enum)
def _GetDeps(self, dependencies):
def _GetDeps(self, dependencies, visited=None):
"""Recursively finds dependencies for file protos.
Args:
dependencies: The names of the files being depended on.
visited: The names of files already found.
Yields:
Each direct and indirect dependency.
"""
visited = visited or set()
for dependency in dependencies:
dep_desc = self.FindFileByName(dependency)
yield dep_desc
for parent_dep in dep_desc.dependencies:
yield parent_dep
if dependency not in visited:
visited.add(dependency)
dep_desc = self.FindFileByName(dependency)
yield dep_desc
public_files = [d.name for d in dep_desc.public_dependencies]
yield from self._GetDeps(public_files, visited)
def _GetTypeFromScope(self, package, type_name, scope):
"""Finds a given type name in the current scope.
+3 -12
View File
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/duration.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,16 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1egoogle/protobuf/duration.proto\x12\x0fgoogle.protobuf\"*\n\x08\x44uration\x12\x0f\n\x07seconds\x18\x01 \x01(\x03\x12\r\n\x05nanos\x18\x02 \x01(\x05\x42\x83\x01\n\x13\x63om.google.protobufB\rDurationProtoP\x01Z1google.golang.org/protobuf/types/known/durationpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
_DURATION = DESCRIPTOR.message_types_by_name['Duration']
Duration = _reflection.GeneratedProtocolMessageType('Duration', (_message.Message,), {
'DESCRIPTOR' : _DURATION,
'__module__' : 'google.protobuf.duration_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.Duration)
})
_sym_db.RegisterMessage(Duration)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.duration_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
+3 -12
View File
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/empty.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,16 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1bgoogle/protobuf/empty.proto\x12\x0fgoogle.protobuf\"\x07\n\x05\x45mptyB}\n\x13\x63om.google.protobufB\nEmptyProtoP\x01Z.google.golang.org/protobuf/types/known/emptypb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
_EMPTY = DESCRIPTOR.message_types_by_name['Empty']
Empty = _reflection.GeneratedProtocolMessageType('Empty', (_message.Message,), {
'DESCRIPTOR' : _EMPTY,
'__module__' : 'google.protobuf.empty_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.Empty)
})
_sym_db.RegisterMessage(Empty)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.empty_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
+3 -12
View File
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/field_mask.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,16 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n google/protobuf/field_mask.proto\x12\x0fgoogle.protobuf\"\x1a\n\tFieldMask\x12\r\n\x05paths\x18\x01 \x03(\tB\x85\x01\n\x13\x63om.google.protobufB\x0e\x46ieldMaskProtoP\x01Z2google.golang.org/protobuf/types/known/fieldmaskpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
_FIELDMASK = DESCRIPTOR.message_types_by_name['FieldMask']
FieldMask = _reflection.GeneratedProtocolMessageType('FieldMask', (_message.Message,), {
'DESCRIPTOR' : _FIELDMASK,
'__module__' : 'google.protobuf.field_mask_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.FieldMask)
})
_sym_db.RegisterMessage(FieldMask)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.field_mask_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -148,10 +148,7 @@ __author__ = 'tmarek@google.com (Torsten Marek)'
import functools
import re
import types
try:
import unittest2 as unittest
except ImportError:
import unittest
import unittest
import uuid
try:
@@ -357,7 +354,7 @@ class TestGeneratorMetaclass(type):
def __new__(mcs, class_name, bases, dct):
dct['_id_suffix'] = id_suffix = {}
for name, obj in dct.items():
for name, obj in dct.copy().items():
if (name.startswith(unittest.TestLoader.testMethodPrefix) and
_NonStringIterable(obj)):
iterator = iter(obj)
@@ -389,9 +386,8 @@ def _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator):
id_suffix[new_name] = getattr(func, '__x_extra_id__', '')
class TestCase(unittest.TestCase):
class TestCase(unittest.TestCase, metaclass=TestGeneratorMetaclass):
"""Base class for test cases using the parameters decorator."""
__metaclass__ = TestGeneratorMetaclass
def _OriginalName(self):
return self._testMethodName.split(_SEPARATOR)[0]
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/any_test.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -17,33 +16,8 @@ from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\'google/protobuf/internal/any_test.proto\x12\x18google.protobuf.internal\x1a\x19google/protobuf/any.proto\"\xc0\x01\n\x07TestAny\x12#\n\x05value\x18\x01 \x01(\x0b\x32\x14.google.protobuf.Any\x12\x11\n\tint_value\x18\x02 \x01(\x05\x12\x42\n\tmap_value\x18\x03 \x03(\x0b\x32/.google.protobuf.internal.TestAny.MapValueEntry\x1a/\n\rMapValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01*\x08\x08\n\x10\x80\x80\x80\x80\x02\"\x85\x01\n\x11TestAnyExtension1\x12\t\n\x01i\x18\x0f \x01(\x05\x32\x65\n\nextension1\x12!.google.protobuf.internal.TestAny\x18\xab\xff\xf6. \x01(\x0b\x32+.google.protobuf.internal.TestAnyExtension1')
_TESTANY = DESCRIPTOR.message_types_by_name['TestAny']
_TESTANY_MAPVALUEENTRY = _TESTANY.nested_types_by_name['MapValueEntry']
_TESTANYEXTENSION1 = DESCRIPTOR.message_types_by_name['TestAnyExtension1']
TestAny = _reflection.GeneratedProtocolMessageType('TestAny', (_message.Message,), {
'MapValueEntry' : _reflection.GeneratedProtocolMessageType('MapValueEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTANY_MAPVALUEENTRY,
'__module__' : 'google.protobuf.internal.any_test_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TestAny.MapValueEntry)
})
,
'DESCRIPTOR' : _TESTANY,
'__module__' : 'google.protobuf.internal.any_test_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TestAny)
})
_sym_db.RegisterMessage(TestAny)
_sym_db.RegisterMessage(TestAny.MapValueEntry)
TestAnyExtension1 = _reflection.GeneratedProtocolMessageType('TestAnyExtension1', (_message.Message,), {
'DESCRIPTOR' : _TESTANYEXTENSION1,
'__module__' : 'google.protobuf.internal.any_test_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TestAnyExtension1)
})
_sym_db.RegisterMessage(TestAnyExtension1)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.any_test_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
TestAny.RegisterExtension(_TESTANYEXTENSION1.extensions_by_name['extension1'])
@@ -28,6 +28,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define PY_SSIZE_T_CLEAN
#include <Python.h>
namespace google {
@@ -81,24 +82,24 @@ static struct PyModuleDef _module = {PyModuleDef_HEAD_INIT,
kModuleName,
kModuleDocstring,
-1,
NULL,
NULL,
NULL,
NULL,
NULL};
nullptr,
nullptr,
nullptr,
nullptr,
nullptr};
extern "C" {
PyMODINIT_FUNC PyInit__api_implementation() {
PyObject* module = PyModule_Create(&_module);
if (module == NULL) {
return NULL;
if (module == nullptr) {
return nullptr;
}
// Adds the module variable "api_version".
if (PyModule_AddIntConstant(module, const_cast<char*>(kImplVersionName),
kImplVersion)) {
Py_DECREF(module);
return NULL;
return nullptr;
}
return module;
@@ -31,41 +31,96 @@
"""Determine which implementation of the protobuf API is used in this process.
"""
import importlib
import os
import sys
import warnings
def _ApiVersionToImplementationType(api_version):
if api_version == 2:
return 'cpp'
if api_version == 1:
raise ValueError('api_version=1 is no longer supported.')
if api_version == 0:
return 'python'
return None
_implementation_type = None
try:
# pylint: disable=g-import-not-at-top
from google.protobuf.internal import _api_implementation
# The compile-time constants in the _api_implementation module can be used to
# switch to a certain implementation of the Python API at build time.
_api_version = _api_implementation.api_version
_implementation_type = _ApiVersionToImplementationType(
_api_implementation.api_version)
except ImportError:
_api_version = -1 # Unspecified by compiler flags.
if _api_version == 1:
raise ValueError('api_version=1 is no longer supported.')
pass # Unspecified by compiler flags.
_default_implementation_type = ('cpp' if _api_version > 0 else 'python')
def _CanImport(mod_name):
try:
mod = importlib.import_module(mod_name)
# Work around a known issue in the classic bootstrap .par import hook.
if not mod:
raise ImportError(mod_name + ' import succeeded but was None')
return True
except ImportError:
return False
if _implementation_type is None:
if _CanImport('google._upb._message'):
_implementation_type = 'upb'
elif _CanImport('google.protobuf.pyext._message'):
_implementation_type = 'cpp'
else:
_implementation_type = 'python'
# This environment variable can be used to switch to a certain implementation
# of the Python API, overriding the compile-time constants in the
# _api_implementation module. Right now only 'python' and 'cpp' are valid
# values. Any other value will be ignored.
# _api_implementation module. Right now only 'python', 'cpp' and 'upb' are
# valid values. Any other value will raise error.
_implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION',
_default_implementation_type)
_implementation_type)
if _implementation_type != 'python':
_implementation_type = 'cpp'
if _implementation_type not in ('python', 'cpp', 'upb'):
raise ValueError('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION {0} is not '
'supported. Please set to \'python\', \'cpp\' or '
'\'upb\'.'.format(_implementation_type))
if 'PyPy' in sys.version and _implementation_type == 'cpp':
warnings.warn('PyPy does not work yet with cpp protocol buffers. '
'Falling back to the python implementation.')
_implementation_type = 'python'
_c_module = None
if _implementation_type == 'cpp':
try:
# pylint: disable=g-import-not-at-top
from google.protobuf.pyext import _message
_c_module = _message
del _message
except ImportError:
# TODO(jieluo): fail back to python
warnings.warn(
'Selected implementation cpp is not available.')
pass
if _implementation_type == 'upb':
try:
# pylint: disable=g-import-not-at-top
from google._upb import _message
_c_module = _message
del _message
except ImportError:
warnings.warn('Selected implementation upb is not available. '
'Falling back to the python implementation.')
_implementation_type = 'python'
pass
# Detect if serialization should be deterministic by default
try:
@@ -103,6 +158,7 @@ def _SetType(implementation_type):
# See comment on 'Type' above.
# TODO(jieluo): Remove the API, it returns a constant. b/228102101
def Version():
return 2
@@ -0,0 +1,130 @@
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Builds descriptors, message classes and services for generated _pb2.py.
This file is only called in python generated _pb2.py files. It builds
descriptors, message classes and services that users can directly use
in generated code.
"""
__author__ = 'jieluo@google.com (Jie Luo)'
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
_sym_db = _symbol_database.Default()
def BuildMessageAndEnumDescriptors(file_des, module):
"""Builds message and enum descriptors.
Args:
file_des: FileDescriptor of the .proto file
module: Generated _pb2 module
"""
def BuildNestedDescriptors(msg_des, prefix):
for (name, nested_msg) in msg_des.nested_types_by_name.items():
module_name = prefix + name.upper()
module[module_name] = nested_msg
BuildNestedDescriptors(nested_msg, module_name + '_')
for enum_des in msg_des.enum_types:
module[prefix + enum_des.name.upper()] = enum_des
for (name, msg_des) in file_des.message_types_by_name.items():
module_name = '_' + name.upper()
module[module_name] = msg_des
BuildNestedDescriptors(msg_des, module_name + '_')
def BuildTopDescriptorsAndMessages(file_des, module_name, module):
"""Builds top level descriptors and message classes.
Args:
file_des: FileDescriptor of the .proto file
module_name: str, the name of generated _pb2 module
module: Generated _pb2 module
"""
def BuildMessage(msg_des):
create_dict = {}
for (name, nested_msg) in msg_des.nested_types_by_name.items():
create_dict[name] = BuildMessage(nested_msg)
create_dict['DESCRIPTOR'] = msg_des
create_dict['__module__'] = module_name
message_class = _reflection.GeneratedProtocolMessageType(
msg_des.name, (_message.Message,), create_dict)
_sym_db.RegisterMessage(message_class)
return message_class
# top level enums
for (name, enum_des) in file_des.enum_types_by_name.items():
module['_' + name.upper()] = enum_des
module[name] = enum_type_wrapper.EnumTypeWrapper(enum_des)
for enum_value in enum_des.values:
module[enum_value.name] = enum_value.number
# top level extensions
for (name, extension_des) in file_des.extensions_by_name.items():
module[name.upper() + '_FIELD_NUMBER'] = extension_des.number
module[name] = extension_des
# services
for (name, service) in file_des.services_by_name.items():
module['_' + name.upper()] = service
# Build messages.
for (name, msg_des) in file_des.message_types_by_name.items():
module[name] = BuildMessage(msg_des)
def BuildServices(file_des, module_name, module):
"""Builds services classes and services stub class.
Args:
file_des: FileDescriptor of the .proto file
module_name: str, the name of generated _pb2 module
module: Generated _pb2 module
"""
# pylint: disable=g-import-not-at-top
from google.protobuf import service as _service
from google.protobuf import service_reflection
# pylint: enable=g-import-not-at-top
for (name, service) in file_des.services_by_name.items():
module[name] = service_reflection.GeneratedServiceType(
name, (_service.Service,),
dict(DESCRIPTOR=service, __module__=module_name))
stub_name = name + '_Stub'
module[stub_name] = service_reflection.GeneratedServiceStubType(
stub_name, (module[name],),
dict(DESCRIPTOR=service, __module__=module_name))
@@ -40,19 +40,37 @@ are:
includes groups and nested messages.
"""
__author__ = 'petar@google.com (Petar Petrov)'
import collections.abc
import copy
import pickle
from typing import (
Any,
Iterable,
Iterator,
List,
MutableMapping,
MutableSequence,
NoReturn,
Optional,
Sequence,
TypeVar,
Union,
overload,
)
class BaseContainer(object):
_T = TypeVar('_T')
_K = TypeVar('_K')
_V = TypeVar('_V')
class BaseContainer(Sequence[_T]):
"""Base container class."""
# Minimizes memory usage and disallows assignment to other attributes.
__slots__ = ['_message_listener', '_values']
def __init__(self, message_listener):
def __init__(self, message_listener: Any) -> None:
"""
Args:
message_listener: A MessageListener implementation.
@@ -62,26 +80,33 @@ class BaseContainer(object):
self._message_listener = message_listener
self._values = []
@overload
def __getitem__(self, key: int) -> _T:
...
@overload
def __getitem__(self, key: slice) -> List[_T]:
...
def __getitem__(self, key):
"""Retrieves item by the specified key."""
return self._values[key]
def __len__(self):
def __len__(self) -> int:
"""Returns the number of elements in the container."""
return len(self._values)
def __ne__(self, other):
def __ne__(self, other: Any) -> bool:
"""Checks if another instance isn't equal to this one."""
# The concrete classes should define __eq__.
return not self == other
def __hash__(self):
raise TypeError('unhashable object')
__hash__ = None
def __repr__(self):
def __repr__(self) -> str:
return repr(self._values)
def sort(self, *args, **kwargs):
def sort(self, *args, **kwargs) -> None:
# Continue to support the old sort_function keyword argument.
# This is expected to be a rare occurrence, so use LBYL to avoid
# the overhead of actually catching KeyError.
@@ -89,20 +114,26 @@ class BaseContainer(object):
kwargs['cmp'] = kwargs.pop('sort_function')
self._values.sort(*args, **kwargs)
def reverse(self):
def reverse(self) -> None:
self._values.reverse()
# TODO(slebedev): Remove this. BaseContainer does *not* conform to
# MutableSequence, only its subclasses do.
collections.abc.MutableSequence.register(BaseContainer)
class RepeatedScalarFieldContainer(BaseContainer):
class RepeatedScalarFieldContainer(BaseContainer[_T], MutableSequence[_T]):
"""Simple, type-checked, list-like container for holding repeated scalars."""
# Disallows assignment to other attributes.
__slots__ = ['_type_checker']
def __init__(self, message_listener, type_checker):
def __init__(
self,
message_listener: Any,
type_checker: Any,
) -> None:
"""Args:
message_listener: A MessageListener implementation. The
@@ -111,24 +142,23 @@ class RepeatedScalarFieldContainer(BaseContainer):
type_checker: A type_checkers.ValueChecker instance to run on elements
inserted into this container.
"""
super(RepeatedScalarFieldContainer, self).__init__(message_listener)
super().__init__(message_listener)
self._type_checker = type_checker
def append(self, value):
def append(self, value: _T) -> None:
"""Appends an item to the list. Similar to list.append()."""
self._values.append(self._type_checker.CheckValue(value))
if not self._message_listener.dirty:
self._message_listener.Modified()
def insert(self, key, value):
def insert(self, key: int, value: _T) -> None:
"""Inserts the item at the specified position. Similar to list.insert()."""
self._values.insert(key, self._type_checker.CheckValue(value))
if not self._message_listener.dirty:
self._message_listener.Modified()
def extend(self, elem_seq):
def extend(self, elem_seq: Iterable[_T]) -> None:
"""Extends by appending the given iterable. Similar to list.extend()."""
if elem_seq is None:
return
try:
@@ -145,57 +175,52 @@ class RepeatedScalarFieldContainer(BaseContainer):
self._values.extend(new_values)
self._message_listener.Modified()
def MergeFrom(self, other):
def MergeFrom(
self,
other: Union['RepeatedScalarFieldContainer[_T]', Iterable[_T]],
) -> None:
"""Appends the contents of another repeated field of the same type to this
one. We do not check the types of the individual fields.
"""
self._values.extend(other._values)
self._values.extend(other)
self._message_listener.Modified()
def remove(self, elem):
def remove(self, elem: _T):
"""Removes an item from the list. Similar to list.remove()."""
self._values.remove(elem)
self._message_listener.Modified()
def pop(self, key=-1):
def pop(self, key: Optional[int] = -1) -> _T:
"""Removes and returns an item at a given index. Similar to list.pop()."""
value = self._values[key]
self.__delitem__(key)
return value
def __setitem__(self, key, value):
@overload
def __setitem__(self, key: int, value: _T) -> None:
...
@overload
def __setitem__(self, key: slice, value: Iterable[_T]) -> None:
...
def __setitem__(self, key, value) -> None:
"""Sets the item on the specified position."""
if isinstance(key, slice): # PY3
if isinstance(key, slice):
if key.step is not None:
raise ValueError('Extended slices not supported')
self.__setslice__(key.start, key.stop, value)
self._values[key] = map(self._type_checker.CheckValue, value)
self._message_listener.Modified()
else:
self._values[key] = self._type_checker.CheckValue(value)
self._message_listener.Modified()
def __getslice__(self, start, stop):
"""Retrieves the subset of items from between the specified indices."""
return self._values[start:stop]
def __setslice__(self, start, stop, values):
"""Sets the subset of items from between the specified indices."""
new_values = []
for value in values:
new_values.append(self._type_checker.CheckValue(value))
self._values[start:stop] = new_values
self._message_listener.Modified()
def __delitem__(self, key):
def __delitem__(self, key: Union[int, slice]) -> None:
"""Deletes the item at the specified position."""
del self._values[key]
self._message_listener.Modified()
def __delslice__(self, start, stop):
"""Deletes the subset of items from between the specified indices."""
del self._values[start:stop]
self._message_listener.Modified()
def __eq__(self, other):
def __eq__(self, other: Any) -> bool:
"""Compares the current instance with another one."""
if self is other:
return True
@@ -205,15 +230,28 @@ class RepeatedScalarFieldContainer(BaseContainer):
# We are presumably comparing against some other sequence type.
return other == self._values
def __deepcopy__(
self,
unused_memo: Any = None,
) -> 'RepeatedScalarFieldContainer[_T]':
clone = RepeatedScalarFieldContainer(
copy.deepcopy(self._message_listener), self._type_checker)
clone.MergeFrom(self)
return clone
class RepeatedCompositeFieldContainer(BaseContainer):
def __reduce__(self, **kwargs) -> NoReturn:
raise pickle.PickleError(
"Can't pickle repeated scalar fields, convert to list first")
# TODO(slebedev): Constrain T to be a subtype of Message.
class RepeatedCompositeFieldContainer(BaseContainer[_T], MutableSequence[_T]):
"""Simple, list-like container for holding repeated composite fields."""
# Disallows assignment to other attributes.
__slots__ = ['_message_descriptor']
def __init__(self, message_listener, message_descriptor):
def __init__(self, message_listener: Any, message_descriptor: Any) -> None:
"""
Note that we pass in a descriptor instead of the generated directly,
since at the time we construct a _RepeatedCompositeFieldContainer we
@@ -228,10 +266,10 @@ class RepeatedCompositeFieldContainer(BaseContainer):
that should be present in this container. We'll use the
_concrete_class field of this descriptor when the client calls add().
"""
super(RepeatedCompositeFieldContainer, self).__init__(message_listener)
super().__init__(message_listener)
self._message_descriptor = message_descriptor
def add(self, **kwargs):
def add(self, **kwargs: Any) -> _T:
"""Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element.
"""
@@ -242,7 +280,7 @@ class RepeatedCompositeFieldContainer(BaseContainer):
self._message_listener.Modified()
return new_element
def append(self, value):
def append(self, value: _T) -> None:
"""Appends one element by copying the message."""
new_element = self._message_descriptor._concrete_class()
new_element._SetListener(self._message_listener)
@@ -251,7 +289,7 @@ class RepeatedCompositeFieldContainer(BaseContainer):
if not self._message_listener.dirty:
self._message_listener.Modified()
def insert(self, key, value):
def insert(self, key: int, value: _T) -> None:
"""Inserts the item at the specified position by copying."""
new_element = self._message_descriptor._concrete_class()
new_element._SetListener(self._message_listener)
@@ -260,7 +298,7 @@ class RepeatedCompositeFieldContainer(BaseContainer):
if not self._message_listener.dirty:
self._message_listener.Modified()
def extend(self, elem_seq):
def extend(self, elem_seq: Iterable[_T]) -> None:
"""Extends by appending the given sequence of elements of the same type
as this one, copying each individual message.
@@ -275,38 +313,47 @@ class RepeatedCompositeFieldContainer(BaseContainer):
values.append(new_element)
listener.Modified()
def MergeFrom(self, other):
def MergeFrom(
self,
other: Union['RepeatedCompositeFieldContainer[_T]', Iterable[_T]],
) -> None:
"""Appends the contents of another repeated field of the same type to this
one, copying each individual message.
"""
self.extend(other._values)
self.extend(other)
def remove(self, elem):
def remove(self, elem: _T) -> None:
"""Removes an item from the list. Similar to list.remove()."""
self._values.remove(elem)
self._message_listener.Modified()
def pop(self, key=-1):
def pop(self, key: Optional[int] = -1) -> _T:
"""Removes and returns an item at a given index. Similar to list.pop()."""
value = self._values[key]
self.__delitem__(key)
return value
def __getslice__(self, start, stop):
"""Retrieves the subset of items from between the specified indices."""
return self._values[start:stop]
@overload
def __setitem__(self, key: int, value: _T) -> None:
...
def __delitem__(self, key):
@overload
def __setitem__(self, key: slice, value: Iterable[_T]) -> None:
...
def __setitem__(self, key, value):
# This method is implemented to make RepeatedCompositeFieldContainer
# structurally compatible with typing.MutableSequence. It is
# otherwise unsupported and will always raise an error.
raise TypeError(
f'{self.__class__.__name__} object does not support item assignment')
def __delitem__(self, key: Union[int, slice]) -> None:
"""Deletes the item at the specified position."""
del self._values[key]
self._message_listener.Modified()
def __delslice__(self, start, stop):
"""Deletes the subset of items from between the specified indices."""
del self._values[start:stop]
self._message_listener.Modified()
def __eq__(self, other):
def __eq__(self, other: Any) -> bool:
"""Compares the current instance with another one."""
if self is other:
return True
@@ -316,16 +363,20 @@ class RepeatedCompositeFieldContainer(BaseContainer):
return self._values == other._values
class ScalarMap(collections.abc.MutableMapping):
class ScalarMap(MutableMapping[_K, _V]):
"""Simple, type-checked, dict-like container for holding repeated scalars."""
# Disallows assignment to other attributes.
__slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener',
'_entry_descriptor']
def __init__(self, message_listener, key_checker, value_checker,
entry_descriptor):
def __init__(
self,
message_listener: Any,
key_checker: Any,
value_checker: Any,
entry_descriptor: Any,
) -> None:
"""
Args:
message_listener: A MessageListener implementation.
@@ -343,7 +394,7 @@ class ScalarMap(collections.abc.MutableMapping):
self._entry_descriptor = entry_descriptor
self._values = {}
def __getitem__(self, key):
def __getitem__(self, key: _K) -> _V:
try:
return self._values[key]
except KeyError:
@@ -352,12 +403,20 @@ class ScalarMap(collections.abc.MutableMapping):
self._values[key] = val
return val
def __contains__(self, item):
def __contains__(self, item: _K) -> bool:
# We check the key's type to match the strong-typing flavor of the API.
# Also this makes it easier to match the behavior of the C++ implementation.
self._key_checker.CheckValue(item)
return item in self._values
@overload
def get(self, key: _K) -> Optional[_V]:
...
@overload
def get(self, key: _K, default: _T) -> Union[_V, _T]:
...
# We need to override this explicitly, because our defaultdict-like behavior
# will make the default implementation (from our base class) always insert
# the key.
@@ -367,30 +426,30 @@ class ScalarMap(collections.abc.MutableMapping):
else:
return default
def __setitem__(self, key, value):
def __setitem__(self, key: _K, value: _V) -> _T:
checked_key = self._key_checker.CheckValue(key)
checked_value = self._value_checker.CheckValue(value)
self._values[checked_key] = checked_value
self._message_listener.Modified()
def __delitem__(self, key):
def __delitem__(self, key: _K) -> None:
del self._values[key]
self._message_listener.Modified()
def __len__(self):
def __len__(self) -> int:
return len(self._values)
def __iter__(self):
def __iter__(self) -> Iterator[_K]:
return iter(self._values)
def __repr__(self):
def __repr__(self) -> str:
return repr(self._values)
def MergeFrom(self, other):
def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None:
self._values.update(other._values)
self._message_listener.Modified()
def InvalidateIterators(self):
def InvalidateIterators(self) -> None:
# It appears that the only way to reliably invalidate iterators to
# self._values is to ensure that its size changes.
original = self._values
@@ -398,24 +457,28 @@ class ScalarMap(collections.abc.MutableMapping):
original[None] = None
# This is defined in the abstract base, but we can do it much more cheaply.
def clear(self):
def clear(self) -> None:
self._values.clear()
self._message_listener.Modified()
def GetEntryClass(self):
def GetEntryClass(self) -> Any:
return self._entry_descriptor._concrete_class
class MessageMap(collections.abc.MutableMapping):
class MessageMap(MutableMapping[_K, _V]):
"""Simple, type-checked, dict-like container for with submessage values."""
# Disallows assignment to other attributes.
__slots__ = ['_key_checker', '_values', '_message_listener',
'_message_descriptor', '_entry_descriptor']
def __init__(self, message_listener, message_descriptor, key_checker,
entry_descriptor):
def __init__(
self,
message_listener: Any,
message_descriptor: Any,
key_checker: Any,
entry_descriptor: Any,
) -> None:
"""
Args:
message_listener: A MessageListener implementation.
@@ -433,7 +496,7 @@ class MessageMap(collections.abc.MutableMapping):
self._entry_descriptor = entry_descriptor
self._values = {}
def __getitem__(self, key):
def __getitem__(self, key: _K) -> _V:
key = self._key_checker.CheckValue(key)
try:
return self._values[key]
@@ -442,10 +505,9 @@ class MessageMap(collections.abc.MutableMapping):
new_element._SetListener(self._message_listener)
self._values[key] = new_element
self._message_listener.Modified()
return new_element
def get_or_create(self, key):
def get_or_create(self, key: _K) -> _V:
"""get_or_create() is an alias for getitem (ie. map[key]).
Args:
@@ -459,6 +521,14 @@ class MessageMap(collections.abc.MutableMapping):
"""
return self[key]
@overload
def get(self, key: _K) -> Optional[_V]:
...
@overload
def get(self, key: _K, default: _T) -> Union[_V, _T]:
...
# We need to override this explicitly, because our defaultdict-like behavior
# will make the default implementation (from our base class) always insert
# the key.
@@ -468,28 +538,28 @@ class MessageMap(collections.abc.MutableMapping):
else:
return default
def __contains__(self, item):
def __contains__(self, item: _K) -> bool:
item = self._key_checker.CheckValue(item)
return item in self._values
def __setitem__(self, key, value):
def __setitem__(self, key: _K, value: _V) -> NoReturn:
raise ValueError('May not set values directly, call my_map[key].foo = 5')
def __delitem__(self, key):
def __delitem__(self, key: _K) -> None:
key = self._key_checker.CheckValue(key)
del self._values[key]
self._message_listener.Modified()
def __len__(self):
def __len__(self) -> int:
return len(self._values)
def __iter__(self):
def __iter__(self) -> Iterator[_K]:
return iter(self._values)
def __repr__(self):
def __repr__(self) -> str:
return repr(self._values)
def MergeFrom(self, other):
def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None:
# pylint: disable=protected-access
for key in other._values:
# According to documentation: "When parsing from the wire or when merging,
@@ -500,7 +570,7 @@ class MessageMap(collections.abc.MutableMapping):
# self._message_listener.Modified() not required here, because
# mutations to submessages already propagate.
def InvalidateIterators(self):
def InvalidateIterators(self) -> None:
# It appears that the only way to reliably invalidate iterators to
# self._values is to ensure that its size changes.
original = self._values
@@ -508,16 +578,15 @@ class MessageMap(collections.abc.MutableMapping):
original[None] = None
# This is defined in the abstract base, but we can do it much more cheaply.
def clear(self):
def clear(self) -> None:
self._values.clear()
self._message_listener.Modified()
def GetEntryClass(self):
def GetEntryClass(self) -> Any:
return self._entry_descriptor._concrete_class
class _UnknownField(object):
class _UnknownField:
"""A parsed unknown field."""
# Disallows assignment to other attributes.
@@ -542,12 +611,11 @@ class _UnknownField(object):
self._data == other._data)
class UnknownFieldRef(object):
class UnknownFieldRef: # pylint: disable=missing-class-docstring
def __init__(self, parent, index):
self._parent = parent
self._index = index
return
def _check_valid(self):
if not self._parent:
@@ -576,8 +644,7 @@ class UnknownFieldRef(object):
return self._parent._internal_get(self._index)._data
class UnknownFieldSet(object):
class UnknownFieldSet:
"""UnknownField container"""
# Disallows assignment to other attributes.
@@ -831,6 +831,45 @@ def MessageSetItemDecoder(descriptor):
return DecodeItem
def UnknownMessageSetItemDecoder():
"""Returns a decoder for a Unknown MessageSet item."""
type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)
message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)
item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)
def DecodeUnknownItem(buffer):
pos = 0
end = len(buffer)
message_start = -1
message_end = -1
while 1:
(tag_bytes, pos) = ReadTag(buffer, pos)
if tag_bytes == type_id_tag_bytes:
(type_id, pos) = _DecodeVarint(buffer, pos)
elif tag_bytes == message_tag_bytes:
(size, message_start) = _DecodeVarint(buffer, pos)
pos = message_end = message_start + size
elif tag_bytes == item_end_tag_bytes:
break
else:
pos = SkipField(buffer, pos, end, tag_bytes)
if pos == -1:
raise _DecodeError('Missing group end tag.')
if pos > end:
raise _DecodeError('Truncated message.')
if type_id == -1:
raise _DecodeError('MessageSet item missing type_id.')
if message_start == -1:
raise _DecodeError('MessageSet item missing message.')
return (type_id, buffer[message_start:message_end].tobytes())
return DecodeUnknownItem
# --------------------------------------------------------------------
def MapDecoder(field_descriptor, new_default, is_message_map):
@@ -100,7 +100,7 @@ class DescriptorDatabaseTest(unittest.TestCase):
self.assertEqual(file_desc_proto2, db.FindFileContainingSymbol(
'protobuf_unittest.TestAllTypes.none_field'))
with self.assertRaisesRegexp(KeyError, r'\'protobuf_unittest\.NoneMessage\''):
with self.assertRaisesRegex(KeyError, r'\'protobuf_unittest\.NoneMessage\''):
db.FindFileContainingSymbol('protobuf_unittest.NoneMessage')
def testConflictRegister(self):
@@ -243,10 +243,10 @@ class DescriptorPoolTestBase(object):
self.assertRaises(KeyError, self.pool.FindMethodByName, '')
# TODO(jieluo): Fix python to raise correct errors.
if api_implementation.Type() == 'cpp':
error_type = TypeError
else:
if api_implementation.Type() == 'python':
error_type = AttributeError
else:
error_type = TypeError
self.assertRaises(error_type, self.pool.FindMessageTypeByName, 0)
self.assertRaises(error_type, self.pool.FindFieldByName, 0)
self.assertRaises(error_type, self.pool.FindExtensionByName, 0)
@@ -395,7 +395,7 @@ class DescriptorPoolTestBase(object):
def testAddSerializedFile(self):
if isinstance(self, SecondaryDescriptorFromDescriptorDB):
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
# Cpp extension cannot call Add on a DescriptorPool
# that uses a DescriptorDatabase.
# TODO(jieluo): Fix python and cpp extension diff.
@@ -434,7 +434,7 @@ class DescriptorPoolTestBase(object):
_CheckDefaultValue(file_descriptor)
if isinstance(self, SecondaryDescriptorFromDescriptorDB):
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
# Cpp extension cannot call Add on a DescriptorPool
# that uses a DescriptorDatabase.
# TODO(jieluo): Fix python and cpp extension diff.
@@ -488,7 +488,7 @@ class DescriptorPoolTestBase(object):
def testAddFileDescriptor(self):
if isinstance(self, SecondaryDescriptorFromDescriptorDB):
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
# Cpp extension cannot call Add on a DescriptorPool
# that uses a DescriptorDatabase.
# TODO(jieluo): Fix python and cpp extension diff.
@@ -499,7 +499,7 @@ class DescriptorPoolTestBase(object):
def testComplexNesting(self):
if isinstance(self, SecondaryDescriptorFromDescriptorDB):
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
# Cpp extension cannot call Add on a DescriptorPool
# that uses a DescriptorDatabase.
# TODO(jieluo): Fix python and cpp extension diff.
@@ -518,7 +518,7 @@ class DescriptorPoolTestBase(object):
def testConflictRegister(self):
if isinstance(self, SecondaryDescriptorFromDescriptorDB):
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
# Cpp extension cannot call Add on a DescriptorPool
# that uses a DescriptorDatabase.
# TODO(jieluo): Fix python and cpp extension diff.
@@ -527,7 +527,7 @@ class DescriptorPoolTestBase(object):
unittest_pb2.DESCRIPTOR.serialized_pb)
conflict_fd = copy.deepcopy(unittest_fd)
conflict_fd.name = 'other_file'
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
pass
else:
pool = copy.deepcopy(self.pool)
@@ -541,7 +541,13 @@ class DescriptorPoolTestBase(object):
pool._AddExtensionDescriptor(
file_descriptor.extensions_by_name['optional_int32_extension'])
pool.Add(unittest_fd)
pool.Add(conflict_fd)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
pool.Add(conflict_fd)
self.assertTrue(len(w))
self.assertIs(w[0].category, RuntimeWarning)
self.assertIn('Conflict register for file "other_file": ',
str(w[0].message))
pool.FindFileByName(unittest_fd.name)
with self.assertRaises(TypeError):
pool.FindFileByName(conflict_fd.name)
@@ -648,11 +654,11 @@ class SecondaryDescriptorFromDescriptorDB(DescriptorPoolTestBase,
enum_value.number = 0
self.db.Add(file_proto)
self.assertRaisesRegexp(KeyError, 'SubMessage',
self.pool.FindMessageTypeByName,
'collector.ErrorMessage')
self.assertRaisesRegexp(KeyError, 'SubMessage',
self.pool.FindFileByName, 'error_file')
self.assertRaisesRegex(KeyError, 'SubMessage',
self.pool.FindMessageTypeByName,
'collector.ErrorMessage')
self.assertRaisesRegex(KeyError, 'SubMessage', self.pool.FindFileByName,
'error_file')
with self.assertRaises(KeyError) as exc:
self.pool.FindFileByName('none_file')
self.assertIn(str(exc.exception), ('\'none_file\'',
@@ -664,7 +670,7 @@ class SecondaryDescriptorFromDescriptorDB(DescriptorPoolTestBase,
# called the first time, a KeyError will be raised but call the find
# method later will return a descriptor which is not build.
# TODO(jieluo): fix pure python to revert the load if file can not be build
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
error_msg = ('Invalid proto descriptor for file "error_file":\\n '
'collector.ErrorMessage.nested_message_field: "SubMessage" '
'is not defined.\\n collector.ErrorMessage.MyOneof: Oneof '
@@ -900,8 +906,8 @@ class AddDescriptorTest(unittest.TestCase):
pool.FindFileContainingSymbol(
prefix + 'protobuf_unittest.TestAllTypes.NestedMessage').name)
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
@unittest.skipIf(api_implementation.Type() != 'python',
'Only pure python allows _Add*()')
def testMessage(self):
self._TestMessage('')
self._TestMessage('.')
@@ -942,14 +948,14 @@ class AddDescriptorTest(unittest.TestCase):
pool.FindFileContainingSymbol(
prefix + 'protobuf_unittest.TestAllTypes.NestedEnum').name)
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
@unittest.skipIf(api_implementation.Type() != 'python',
'Only pure python allows _Add*()')
def testEnum(self):
self._TestEnum('')
self._TestEnum('.')
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
@unittest.skipIf(api_implementation.Type() != 'python',
'Only pure python allows _Add*()')
def testService(self):
pool = descriptor_pool.DescriptorPool()
with self.assertRaises(KeyError):
@@ -959,8 +965,8 @@ class AddDescriptorTest(unittest.TestCase):
'protobuf_unittest.TestService',
pool.FindServiceByName('protobuf_unittest.TestService').full_name)
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
@unittest.skipIf(api_implementation.Type() != 'python',
'Only pure python allows _Add*()')
def testFile(self):
pool = descriptor_pool.DescriptorPool()
pool._AddFileDescriptor(unittest_pb2.DESCRIPTOR)
@@ -1037,7 +1043,7 @@ class AddDescriptorTest(unittest.TestCase):
def testAddTypeError(self):
pool = descriptor_pool.DescriptorPool()
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
with self.assertRaises(TypeError):
pool.AddDescriptor(0)
with self.assertRaises(TypeError):
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/descriptor_pool_test1.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,66 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n4google/protobuf/internal/descriptor_pool_test1.proto\x12\x1fgoogle.protobuf.python.internal\"\xfb\x05\n\x13\x44\x65scriptorPoolTest1\x12Z\n\x0bnested_enum\x18\x01 \x01(\x0e\x32?.google.protobuf.python.internal.DescriptorPoolTest1.NestedEnum:\x04\x42\x45TA\x12Z\n\x0enested_message\x18\x02 \x01(\x0b\x32\x42.google.protobuf.python.internal.DescriptorPoolTest1.NestedMessage\x1a\xfd\x03\n\rNestedMessage\x12h\n\x0bnested_enum\x18\x01 \x01(\x0e\x32M.google.protobuf.python.internal.DescriptorPoolTest1.NestedMessage.NestedEnum:\x04ZETA\x12\x1a\n\x0cnested_field\x18\x02 \x01(\t:\x04\x62\x65ta\x12q\n\x13\x64\x65\x65p_nested_message\x18\x03 \x01(\x0b\x32T.google.protobuf.python.internal.DescriptorPoolTest1.NestedMessage.DeepNestedMessage\x1a\xcd\x01\n\x11\x44\x65\x65pNestedMessage\x12y\n\x0bnested_enum\x18\x01 \x01(\x0e\x32_.google.protobuf.python.internal.DescriptorPoolTest1.NestedMessage.DeepNestedMessage.NestedEnum:\x03\x45TA\x12\x1b\n\x0cnested_field\x18\x02 \x01(\t:\x05theta\" \n\nNestedEnum\x12\x07\n\x03\x45TA\x10\x07\x12\t\n\x05THETA\x10\x08\"#\n\nNestedEnum\x12\x0b\n\x07\x45PSILON\x10\x05\x12\x08\n\x04ZETA\x10\x06\"!\n\nNestedEnum\x12\t\n\x05\x41LPHA\x10\x01\x12\x08\n\x04\x42\x45TA\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xf1\x05\n\x13\x44\x65scriptorPoolTest2\x12[\n\x0bnested_enum\x18\x01 \x01(\x0e\x32?.google.protobuf.python.internal.DescriptorPoolTest2.NestedEnum:\x05GAMMA\x12Z\n\x0enested_message\x18\x02 \x01(\x0b\x32\x42.google.protobuf.python.internal.DescriptorPoolTest2.NestedMessage\x1a\xfc\x03\n\rNestedMessage\x12h\n\x0bnested_enum\x18\x01 \x01(\x0e\x32M.google.protobuf.python.internal.DescriptorPoolTest2.NestedMessage.NestedEnum:\x04IOTA\x12\x1b\n\x0cnested_field\x18\x02 \x01(\t:\x05\x64\x65lta\x12q\n\x13\x64\x65\x65p_nested_message\x18\x03 \x01(\x0b\x32T.google.protobuf.python.internal.DescriptorPoolTest2.NestedMessage.DeepNestedMessage\x1a\xcd\x01\n\x11\x44\x65\x65pNestedMessage\x12x\n\x0bnested_enum\x18\x01 \x01(\x0e\x32_.google.protobuf.python.internal.DescriptorPoolTest2.NestedMessage.DeepNestedMessage.NestedEnum:\x02MU\x12\x1c\n\x0cnested_field\x18\x02 \x01(\t:\x06lambda\" \n\nNestedEnum\x12\n\n\x06LAMBDA\x10\x0b\x12\x06\n\x02MU\x10\x0c\"!\n\nNestedEnum\x12\x08\n\x04IOTA\x10\t\x12\t\n\x05KAPPA\x10\n\"\"\n\nNestedEnum\x12\t\n\x05GAMMA\x10\x03\x12\t\n\x05\x44\x45LTA\x10\x04')
_DESCRIPTORPOOLTEST1 = DESCRIPTOR.message_types_by_name['DescriptorPoolTest1']
_DESCRIPTORPOOLTEST1_NESTEDMESSAGE = _DESCRIPTORPOOLTEST1.nested_types_by_name['NestedMessage']
_DESCRIPTORPOOLTEST1_NESTEDMESSAGE_DEEPNESTEDMESSAGE = _DESCRIPTORPOOLTEST1_NESTEDMESSAGE.nested_types_by_name['DeepNestedMessage']
_DESCRIPTORPOOLTEST2 = DESCRIPTOR.message_types_by_name['DescriptorPoolTest2']
_DESCRIPTORPOOLTEST2_NESTEDMESSAGE = _DESCRIPTORPOOLTEST2.nested_types_by_name['NestedMessage']
_DESCRIPTORPOOLTEST2_NESTEDMESSAGE_DEEPNESTEDMESSAGE = _DESCRIPTORPOOLTEST2_NESTEDMESSAGE.nested_types_by_name['DeepNestedMessage']
_DESCRIPTORPOOLTEST1_NESTEDMESSAGE_DEEPNESTEDMESSAGE_NESTEDENUM = _DESCRIPTORPOOLTEST1_NESTEDMESSAGE_DEEPNESTEDMESSAGE.enum_types_by_name['NestedEnum']
_DESCRIPTORPOOLTEST1_NESTEDMESSAGE_NESTEDENUM = _DESCRIPTORPOOLTEST1_NESTEDMESSAGE.enum_types_by_name['NestedEnum']
_DESCRIPTORPOOLTEST1_NESTEDENUM = _DESCRIPTORPOOLTEST1.enum_types_by_name['NestedEnum']
_DESCRIPTORPOOLTEST2_NESTEDMESSAGE_DEEPNESTEDMESSAGE_NESTEDENUM = _DESCRIPTORPOOLTEST2_NESTEDMESSAGE_DEEPNESTEDMESSAGE.enum_types_by_name['NestedEnum']
_DESCRIPTORPOOLTEST2_NESTEDMESSAGE_NESTEDENUM = _DESCRIPTORPOOLTEST2_NESTEDMESSAGE.enum_types_by_name['NestedEnum']
_DESCRIPTORPOOLTEST2_NESTEDENUM = _DESCRIPTORPOOLTEST2.enum_types_by_name['NestedEnum']
DescriptorPoolTest1 = _reflection.GeneratedProtocolMessageType('DescriptorPoolTest1', (_message.Message,), {
'NestedMessage' : _reflection.GeneratedProtocolMessageType('NestedMessage', (_message.Message,), {
'DeepNestedMessage' : _reflection.GeneratedProtocolMessageType('DeepNestedMessage', (_message.Message,), {
'DESCRIPTOR' : _DESCRIPTORPOOLTEST1_NESTEDMESSAGE_DEEPNESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.descriptor_pool_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest1.NestedMessage.DeepNestedMessage)
})
,
'DESCRIPTOR' : _DESCRIPTORPOOLTEST1_NESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.descriptor_pool_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest1.NestedMessage)
})
,
'DESCRIPTOR' : _DESCRIPTORPOOLTEST1,
'__module__' : 'google.protobuf.internal.descriptor_pool_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest1)
})
_sym_db.RegisterMessage(DescriptorPoolTest1)
_sym_db.RegisterMessage(DescriptorPoolTest1.NestedMessage)
_sym_db.RegisterMessage(DescriptorPoolTest1.NestedMessage.DeepNestedMessage)
DescriptorPoolTest2 = _reflection.GeneratedProtocolMessageType('DescriptorPoolTest2', (_message.Message,), {
'NestedMessage' : _reflection.GeneratedProtocolMessageType('NestedMessage', (_message.Message,), {
'DeepNestedMessage' : _reflection.GeneratedProtocolMessageType('DeepNestedMessage', (_message.Message,), {
'DESCRIPTOR' : _DESCRIPTORPOOLTEST2_NESTEDMESSAGE_DEEPNESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.descriptor_pool_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest2.NestedMessage.DeepNestedMessage)
})
,
'DESCRIPTOR' : _DESCRIPTORPOOLTEST2_NESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.descriptor_pool_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest2.NestedMessage)
})
,
'DESCRIPTOR' : _DESCRIPTORPOOLTEST2,
'__module__' : 'google.protobuf.internal.descriptor_pool_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest2)
})
_sym_db.RegisterMessage(DescriptorPoolTest2)
_sym_db.RegisterMessage(DescriptorPoolTest2.NestedMessage)
_sym_db.RegisterMessage(DescriptorPoolTest2.NestedMessage.DeepNestedMessage)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.descriptor_pool_test1_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/descriptor_pool_test2.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -19,37 +18,8 @@ from google.protobuf.internal.more_messages_pb2 import *
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n4google/protobuf/internal/descriptor_pool_test2.proto\x12\x1fgoogle.protobuf.python.internal\x1a\x34google/protobuf/internal/descriptor_pool_test1.proto\x1a,google/protobuf/internal/more_messages.proto\"\xef\x06\n\x13\x44\x65scriptorPoolTest3\x12X\n\x0bnested_enum\x18\x01 \x01(\x0e\x32?.google.protobuf.python.internal.DescriptorPoolTest3.NestedEnum:\x02XI\x12Z\n\x0enested_message\x18\x02 \x01(\x0b\x32\x42.google.protobuf.python.internal.DescriptorPoolTest3.NestedMessage\x1a\xf7\x03\n\rNestedMessage\x12\x66\n\x0bnested_enum\x18\x01 \x01(\x0e\x32M.google.protobuf.python.internal.DescriptorPoolTest3.NestedMessage.NestedEnum:\x02PI\x12\x18\n\x0cnested_field\x18\x02 \x01(\t:\x02nu\x12q\n\x13\x64\x65\x65p_nested_message\x18\x03 \x01(\x0b\x32T.google.protobuf.python.internal.DescriptorPoolTest3.NestedMessage.DeepNestedMessage\x1a\xcd\x01\n\x11\x44\x65\x65pNestedMessage\x12y\n\x0bnested_enum\x18\x01 \x01(\x0e\x32_.google.protobuf.python.internal.DescriptorPoolTest3.NestedMessage.DeepNestedMessage.NestedEnum:\x03RHO\x12\x1b\n\x0cnested_field\x18\x02 \x01(\t:\x05sigma\" \n\nNestedEnum\x12\x07\n\x03RHO\x10\x11\x12\t\n\x05SIGMA\x10\x12\"!\n\nNestedEnum\x12\x0b\n\x07OMICRON\x10\x0f\x12\x06\n\x02PI\x10\x10\"\x1c\n\nNestedEnum\x12\x06\n\x02NU\x10\r\x12\x06\n\x02XI\x10\x0e\x32\x89\x01\n\x14\x64\x65scriptor_pool_test\x12\x34.google.protobuf.python.internal.DescriptorPoolTest1\x18\xe9\x07 \x01(\x0b\x32\x34.google.protobuf.python.internal.DescriptorPoolTest3P\x01')
_DESCRIPTORPOOLTEST3 = DESCRIPTOR.message_types_by_name['DescriptorPoolTest3']
_DESCRIPTORPOOLTEST3_NESTEDMESSAGE = _DESCRIPTORPOOLTEST3.nested_types_by_name['NestedMessage']
_DESCRIPTORPOOLTEST3_NESTEDMESSAGE_DEEPNESTEDMESSAGE = _DESCRIPTORPOOLTEST3_NESTEDMESSAGE.nested_types_by_name['DeepNestedMessage']
_DESCRIPTORPOOLTEST3_NESTEDMESSAGE_DEEPNESTEDMESSAGE_NESTEDENUM = _DESCRIPTORPOOLTEST3_NESTEDMESSAGE_DEEPNESTEDMESSAGE.enum_types_by_name['NestedEnum']
_DESCRIPTORPOOLTEST3_NESTEDMESSAGE_NESTEDENUM = _DESCRIPTORPOOLTEST3_NESTEDMESSAGE.enum_types_by_name['NestedEnum']
_DESCRIPTORPOOLTEST3_NESTEDENUM = _DESCRIPTORPOOLTEST3.enum_types_by_name['NestedEnum']
DescriptorPoolTest3 = _reflection.GeneratedProtocolMessageType('DescriptorPoolTest3', (_message.Message,), {
'NestedMessage' : _reflection.GeneratedProtocolMessageType('NestedMessage', (_message.Message,), {
'DeepNestedMessage' : _reflection.GeneratedProtocolMessageType('DeepNestedMessage', (_message.Message,), {
'DESCRIPTOR' : _DESCRIPTORPOOLTEST3_NESTEDMESSAGE_DEEPNESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.descriptor_pool_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest3.NestedMessage.DeepNestedMessage)
})
,
'DESCRIPTOR' : _DESCRIPTORPOOLTEST3_NESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.descriptor_pool_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest3.NestedMessage)
})
,
'DESCRIPTOR' : _DESCRIPTORPOOLTEST3,
'__module__' : 'google.protobuf.internal.descriptor_pool_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.DescriptorPoolTest3)
})
_sym_db.RegisterMessage(DescriptorPoolTest3)
_sym_db.RegisterMessage(DescriptorPoolTest3.NestedMessage)
_sym_db.RegisterMessage(DescriptorPoolTest3.NestedMessage.DeepNestedMessage)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.descriptor_pool_test2_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
google_dot_protobuf_dot_internal_dot_descriptor__pool__test1__pb2.DescriptorPoolTest1.RegisterExtension(_DESCRIPTORPOOLTEST3.extensions_by_name['descriptor_pool_test'])
@@ -51,6 +51,28 @@ TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII = """
name: 'TestEmptyMessage'
"""
TEST_FILE_DESCRIPTOR_DEBUG = """syntax = "proto2";
package protobuf_unittest;
message NestedMessage {
enum ForeignEnum {
FOREIGN_FOO = 4;
FOREIGN_BAR = 5;
FOREIGN_BAZ = 6;
}
optional int32 bb = 1;
}
message ResponseMessage {
}
service Service {
rpc CallMethod(.protobuf_unittest.NestedMessage) returns (.protobuf_unittest.ResponseMessage);
}
"""
warnings.simplefilter('error', DeprecationWarning)
@@ -121,6 +143,13 @@ class DescriptorTest(unittest.TestCase):
def testContainingServiceFixups(self):
self.assertEqual(self.my_service, self.my_method.containing_service)
@unittest.skipIf(
api_implementation.Type() == 'python',
'GetDebugString is only available with the cpp implementation',
)
def testGetDebugString(self):
self.assertEqual(self.my_file.GetDebugString(), TEST_FILE_DESCRIPTOR_DEBUG)
def testGetOptions(self):
self.assertEqual(self.my_enum.GetOptions(),
descriptor_pb2.EnumOptions())
@@ -299,10 +328,10 @@ class DescriptorTest(unittest.TestCase):
unittest_custom_options_pb2.complex_opt1].foo)
self.assertEqual(324, options.Extensions[
unittest_custom_options_pb2.complex_opt1].Extensions[
unittest_custom_options_pb2.quux])
unittest_custom_options_pb2.mooo])
self.assertEqual(876, options.Extensions[
unittest_custom_options_pb2.complex_opt1].Extensions[
unittest_custom_options_pb2.corge].qux)
unittest_custom_options_pb2.corge].moo)
self.assertEqual(987, options.Extensions[
unittest_custom_options_pb2.complex_opt2].baz)
self.assertEqual(654, options.Extensions[
@@ -312,28 +341,28 @@ class DescriptorTest(unittest.TestCase):
unittest_custom_options_pb2.complex_opt2].bar.foo)
self.assertEqual(1999, options.Extensions[
unittest_custom_options_pb2.complex_opt2].bar.Extensions[
unittest_custom_options_pb2.quux])
unittest_custom_options_pb2.mooo])
self.assertEqual(2008, options.Extensions[
unittest_custom_options_pb2.complex_opt2].bar.Extensions[
unittest_custom_options_pb2.corge].qux)
unittest_custom_options_pb2.corge].moo)
self.assertEqual(741, options.Extensions[
unittest_custom_options_pb2.complex_opt2].Extensions[
unittest_custom_options_pb2.garply].foo)
self.assertEqual(1998, options.Extensions[
unittest_custom_options_pb2.complex_opt2].Extensions[
unittest_custom_options_pb2.garply].Extensions[
unittest_custom_options_pb2.quux])
unittest_custom_options_pb2.mooo])
self.assertEqual(2121, options.Extensions[
unittest_custom_options_pb2.complex_opt2].Extensions[
unittest_custom_options_pb2.garply].Extensions[
unittest_custom_options_pb2.corge].qux)
unittest_custom_options_pb2.corge].moo)
self.assertEqual(1971, options.Extensions[
unittest_custom_options_pb2.ComplexOptionType2
.ComplexOptionType4.complex_opt4].waldo)
self.assertEqual(321, options.Extensions[
unittest_custom_options_pb2.complex_opt2].fred.waldo)
self.assertEqual(9, options.Extensions[
unittest_custom_options_pb2.complex_opt3].qux)
unittest_custom_options_pb2.complex_opt3].moo)
self.assertEqual(22, options.Extensions[
unittest_custom_options_pb2.complex_opt3].complexoptiontype5.plugh)
self.assertEqual(24, options.Extensions[
@@ -428,7 +457,7 @@ class DescriptorTest(unittest.TestCase):
self.assertEqual(unittest_pb2.DESCRIPTOR.pool, descriptor_pool.Default())
@unittest.skipIf(
api_implementation.Type() != 'cpp' or api_implementation.Version() != 2,
api_implementation.Type() == 'python',
'Immutability of descriptors is only enforced in v2 implementation')
def testImmutableCppDescriptor(self):
file_descriptor = unittest_pb2.DESCRIPTOR
@@ -523,6 +552,7 @@ class GeneratedDescriptorTest(unittest.TestCase):
self.assertIn(field_descriptor, {field_descriptor: None})
self.assertEqual(None, field_descriptor.extension_scope)
self.assertEqual(None, field_descriptor.enum_type)
self.assertTrue(field_descriptor.has_presence)
if api_implementation.Type() == 'cpp':
# For test coverage only
self.assertEqual(field_descriptor.id, field_descriptor.id)
@@ -43,6 +43,15 @@ class EnumTypeWrapper(object):
DESCRIPTOR = None
# This is a type alias, which mypy typing stubs can type as
# a genericized parameter constrained to an int, allowing subclasses
# to be typed with more constraint in .pyi stubs
# Eg.
# def MyGeneratedEnum(Message):
# ValueType = NewType('ValueType', int)
# def Name(self, number: MyGeneratedEnum.ValueType) -> str
ValueType = int
def __init__(self, enum_type):
"""Inits EnumTypeWrapper with an EnumDescriptor."""
self._enum_type = enum_type
@@ -2,11 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/factory_test1.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -17,47 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n,google/protobuf/internal/factory_test1.proto\x12\x1fgoogle.protobuf.python.internal\"\xd5\x03\n\x0f\x46\x61\x63tory1Message\x12\x45\n\x0e\x66\x61\x63tory_1_enum\x18\x01 \x01(\x0e\x32-.google.protobuf.python.internal.Factory1Enum\x12\x62\n\x15nested_factory_1_enum\x18\x02 \x01(\x0e\x32\x43.google.protobuf.python.internal.Factory1Message.NestedFactory1Enum\x12h\n\x18nested_factory_1_message\x18\x03 \x01(\x0b\x32\x46.google.protobuf.python.internal.Factory1Message.NestedFactory1Message\x12\x14\n\x0cscalar_value\x18\x04 \x01(\x05\x12\x12\n\nlist_value\x18\x05 \x03(\t\x1a&\n\x15NestedFactory1Message\x12\r\n\x05value\x18\x01 \x01(\t\"P\n\x12NestedFactory1Enum\x12\x1c\n\x18NESTED_FACTORY_1_VALUE_0\x10\x00\x12\x1c\n\x18NESTED_FACTORY_1_VALUE_1\x10\x01*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\")\n\x15\x46\x61\x63tory1MethodRequest\x12\x10\n\x08\x61rgument\x18\x01 \x01(\t\"(\n\x16\x46\x61\x63tory1MethodResponse\x12\x0e\n\x06result\x18\x01 \x01(\t*<\n\x0c\x46\x61\x63tory1Enum\x12\x15\n\x11\x46\x41\x43TORY_1_VALUE_0\x10\x00\x12\x15\n\x11\x46\x41\x43TORY_1_VALUE_1\x10\x01\x32\x97\x01\n\x0f\x46\x61\x63tory1Service\x12\x83\x01\n\x0e\x46\x61\x63tory1Method\x12\x36.google.protobuf.python.internal.Factory1MethodRequest\x1a\x37.google.protobuf.python.internal.Factory1MethodResponse\"\x00')
_FACTORY1ENUM = DESCRIPTOR.enum_types_by_name['Factory1Enum']
Factory1Enum = enum_type_wrapper.EnumTypeWrapper(_FACTORY1ENUM)
FACTORY_1_VALUE_0 = 0
FACTORY_1_VALUE_1 = 1
_FACTORY1MESSAGE = DESCRIPTOR.message_types_by_name['Factory1Message']
_FACTORY1MESSAGE_NESTEDFACTORY1MESSAGE = _FACTORY1MESSAGE.nested_types_by_name['NestedFactory1Message']
_FACTORY1METHODREQUEST = DESCRIPTOR.message_types_by_name['Factory1MethodRequest']
_FACTORY1METHODRESPONSE = DESCRIPTOR.message_types_by_name['Factory1MethodResponse']
_FACTORY1MESSAGE_NESTEDFACTORY1ENUM = _FACTORY1MESSAGE.enum_types_by_name['NestedFactory1Enum']
Factory1Message = _reflection.GeneratedProtocolMessageType('Factory1Message', (_message.Message,), {
'NestedFactory1Message' : _reflection.GeneratedProtocolMessageType('NestedFactory1Message', (_message.Message,), {
'DESCRIPTOR' : _FACTORY1MESSAGE_NESTEDFACTORY1MESSAGE,
'__module__' : 'google.protobuf.internal.factory_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.Factory1Message.NestedFactory1Message)
})
,
'DESCRIPTOR' : _FACTORY1MESSAGE,
'__module__' : 'google.protobuf.internal.factory_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.Factory1Message)
})
_sym_db.RegisterMessage(Factory1Message)
_sym_db.RegisterMessage(Factory1Message.NestedFactory1Message)
Factory1MethodRequest = _reflection.GeneratedProtocolMessageType('Factory1MethodRequest', (_message.Message,), {
'DESCRIPTOR' : _FACTORY1METHODREQUEST,
'__module__' : 'google.protobuf.internal.factory_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.Factory1MethodRequest)
})
_sym_db.RegisterMessage(Factory1MethodRequest)
Factory1MethodResponse = _reflection.GeneratedProtocolMessageType('Factory1MethodResponse', (_message.Message,), {
'DESCRIPTOR' : _FACTORY1METHODRESPONSE,
'__module__' : 'google.protobuf.internal.factory_test1_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.Factory1MethodResponse)
})
_sym_db.RegisterMessage(Factory1MethodResponse)
_FACTORY1SERVICE = DESCRIPTOR.services_by_name['Factory1Service']
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.factory_test1_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -2,11 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/factory_test2.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -18,66 +16,8 @@ from google.protobuf.internal import factory_test1_pb2 as google_dot_protobuf_do
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n,google/protobuf/internal/factory_test2.proto\x12\x1fgoogle.protobuf.python.internal\x1a,google/protobuf/internal/factory_test1.proto\"\xd8\x0b\n\x0f\x46\x61\x63tory2Message\x12\x11\n\tmandatory\x18\x01 \x02(\x05\x12\x45\n\x0e\x66\x61\x63tory_2_enum\x18\x02 \x01(\x0e\x32-.google.protobuf.python.internal.Factory2Enum\x12\x62\n\x15nested_factory_2_enum\x18\x03 \x01(\x0e\x32\x43.google.protobuf.python.internal.Factory2Message.NestedFactory2Enum\x12h\n\x18nested_factory_2_message\x18\x04 \x01(\x0b\x32\x46.google.protobuf.python.internal.Factory2Message.NestedFactory2Message\x12K\n\x11\x66\x61\x63tory_1_message\x18\x05 \x01(\x0b\x32\x30.google.protobuf.python.internal.Factory1Message\x12\x45\n\x0e\x66\x61\x63tory_1_enum\x18\x06 \x01(\x0e\x32-.google.protobuf.python.internal.Factory1Enum\x12\x62\n\x15nested_factory_1_enum\x18\x07 \x01(\x0e\x32\x43.google.protobuf.python.internal.Factory1Message.NestedFactory1Enum\x12h\n\x18nested_factory_1_message\x18\x08 \x01(\x0b\x32\x46.google.protobuf.python.internal.Factory1Message.NestedFactory1Message\x12J\n\x10\x63ircular_message\x18\t \x01(\x0b\x32\x30.google.protobuf.python.internal.Factory2Message\x12\x14\n\x0cscalar_value\x18\n \x01(\t\x12\x12\n\nlist_value\x18\x0b \x03(\t\x12I\n\x07grouped\x18\x0c \x03(\n28.google.protobuf.python.internal.Factory2Message.Grouped\x12:\n\x04loop\x18\x0f \x01(\x0b\x32,.google.protobuf.python.internal.LoopMessage\x12\x1e\n\x10int_with_default\x18\x10 \x01(\x05:\x04\x31\x37\x37\x36\x12!\n\x13\x64ouble_with_default\x18\x11 \x01(\x01:\x04\x39.99\x12(\n\x13string_with_default\x18\x12 \x01(\t:\x0bhello world\x12 \n\x11\x62ool_with_default\x18\x13 \x01(\x08:\x05\x66\x61lse\x12[\n\x11\x65num_with_default\x18\x14 \x01(\x0e\x32-.google.protobuf.python.internal.Factory2Enum:\x11\x46\x41\x43TORY_2_VALUE_1\x12&\n\x12\x62ytes_with_default\x18\x15 \x01(\x0c:\na\\373\\000c\x12\x13\n\toneof_int\x18\x16 \x01(\x05H\x00\x12\x16\n\x0coneof_string\x18\x17 \x01(\tH\x00\x1a&\n\x15NestedFactory2Message\x12\r\n\x05value\x18\x01 \x01(\t\x1a)\n\x07Grouped\x12\x0e\n\x06part_1\x18\r \x01(\t\x12\x0e\n\x06part_2\x18\x0e \x01(\t\"P\n\x12NestedFactory2Enum\x12\x1c\n\x18NESTED_FACTORY_2_VALUE_0\x10\x00\x12\x1c\n\x18NESTED_FACTORY_2_VALUE_1\x10\x01\x32I\n\x0eone_more_field\x12\x30.google.protobuf.python.internal.Factory1Message\x18\xe9\x07 \x01(\tB\r\n\x0boneof_field\"M\n\x0bLoopMessage\x12>\n\x04loop\x18\x01 \x01(\x0b\x32\x30.google.protobuf.python.internal.Factory2Message\"D\n\x19MessageWithNestedEnumOnly\"\'\n\nNestedEnum\x12\x19\n\x15NESTED_MESSAGE_ENUM_0\x10\x00\"\'\n\x11MessageWithOption\x12\x0e\n\x06\x66ield1\x18\x01 \x01(\x05:\x02\x10\x01*<\n\x0c\x46\x61\x63tory2Enum\x12\x15\n\x11\x46\x41\x43TORY_2_VALUE_0\x10\x00\x12\x15\n\x11\x46\x41\x43TORY_2_VALUE_1\x10\x01:H\n\ranother_field\x12\x30.google.protobuf.python.internal.Factory1Message\x18\xea\x07 \x01(\t')
_FACTORY2ENUM = DESCRIPTOR.enum_types_by_name['Factory2Enum']
Factory2Enum = enum_type_wrapper.EnumTypeWrapper(_FACTORY2ENUM)
FACTORY_2_VALUE_0 = 0
FACTORY_2_VALUE_1 = 1
ANOTHER_FIELD_FIELD_NUMBER = 1002
another_field = DESCRIPTOR.extensions_by_name['another_field']
_FACTORY2MESSAGE = DESCRIPTOR.message_types_by_name['Factory2Message']
_FACTORY2MESSAGE_NESTEDFACTORY2MESSAGE = _FACTORY2MESSAGE.nested_types_by_name['NestedFactory2Message']
_FACTORY2MESSAGE_GROUPED = _FACTORY2MESSAGE.nested_types_by_name['Grouped']
_LOOPMESSAGE = DESCRIPTOR.message_types_by_name['LoopMessage']
_MESSAGEWITHNESTEDENUMONLY = DESCRIPTOR.message_types_by_name['MessageWithNestedEnumOnly']
_MESSAGEWITHOPTION = DESCRIPTOR.message_types_by_name['MessageWithOption']
_FACTORY2MESSAGE_NESTEDFACTORY2ENUM = _FACTORY2MESSAGE.enum_types_by_name['NestedFactory2Enum']
_MESSAGEWITHNESTEDENUMONLY_NESTEDENUM = _MESSAGEWITHNESTEDENUMONLY.enum_types_by_name['NestedEnum']
Factory2Message = _reflection.GeneratedProtocolMessageType('Factory2Message', (_message.Message,), {
'NestedFactory2Message' : _reflection.GeneratedProtocolMessageType('NestedFactory2Message', (_message.Message,), {
'DESCRIPTOR' : _FACTORY2MESSAGE_NESTEDFACTORY2MESSAGE,
'__module__' : 'google.protobuf.internal.factory_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.Factory2Message.NestedFactory2Message)
})
,
'Grouped' : _reflection.GeneratedProtocolMessageType('Grouped', (_message.Message,), {
'DESCRIPTOR' : _FACTORY2MESSAGE_GROUPED,
'__module__' : 'google.protobuf.internal.factory_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.Factory2Message.Grouped)
})
,
'DESCRIPTOR' : _FACTORY2MESSAGE,
'__module__' : 'google.protobuf.internal.factory_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.Factory2Message)
})
_sym_db.RegisterMessage(Factory2Message)
_sym_db.RegisterMessage(Factory2Message.NestedFactory2Message)
_sym_db.RegisterMessage(Factory2Message.Grouped)
LoopMessage = _reflection.GeneratedProtocolMessageType('LoopMessage', (_message.Message,), {
'DESCRIPTOR' : _LOOPMESSAGE,
'__module__' : 'google.protobuf.internal.factory_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.LoopMessage)
})
_sym_db.RegisterMessage(LoopMessage)
MessageWithNestedEnumOnly = _reflection.GeneratedProtocolMessageType('MessageWithNestedEnumOnly', (_message.Message,), {
'DESCRIPTOR' : _MESSAGEWITHNESTEDENUMONLY,
'__module__' : 'google.protobuf.internal.factory_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.MessageWithNestedEnumOnly)
})
_sym_db.RegisterMessage(MessageWithNestedEnumOnly)
MessageWithOption = _reflection.GeneratedProtocolMessageType('MessageWithOption', (_message.Message,), {
'DESCRIPTOR' : _MESSAGEWITHOPTION,
'__module__' : 'google.protobuf.internal.factory_test2_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.MessageWithOption)
})
_sym_db.RegisterMessage(MessageWithOption)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.factory_test2_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
google_dot_protobuf_dot_internal_dot_factory__test1__pb2.Factory1Message.RegisterExtension(another_field)
google_dot_protobuf_dot_internal_dot_factory__test1__pb2.Factory1Message.RegisterExtension(_FACTORY2MESSAGE.extensions_by_name['one_more_field'])
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/file_options_test.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -17,18 +16,8 @@ from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n0google/protobuf/internal/file_options_test.proto\x12\x1fgoogle.protobuf.python.internal\x1a google/protobuf/descriptor.proto\"\x1e\n\nFooOptions\x12\x10\n\x08\x66oo_name\x18\x01 \x01(\t:a\n\x0b\x66oo_options\x12\x1c.google.protobuf.FileOptions\x18\xac\xec\xb6\x39 \x01(\x0b\x32+.google.protobuf.python.internal.FooOptions')
FOO_OPTIONS_FIELD_NUMBER = 120436268
foo_options = DESCRIPTOR.extensions_by_name['foo_options']
_FOOOPTIONS = DESCRIPTOR.message_types_by_name['FooOptions']
FooOptions = _reflection.GeneratedProtocolMessageType('FooOptions', (_message.Message,), {
'DESCRIPTOR' : _FOOOPTIONS,
'__module__' : 'google.protobuf.internal.file_options_test_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.FooOptions)
})
_sym_db.RegisterMessage(FooOptions)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.file_options_test_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
google_dot_protobuf_dot_descriptor__pb2.FileOptions.RegisterExtension(foo_options)
@@ -39,10 +39,7 @@ further ensures that we can use Python protocol message objects as we expect.
__author__ = 'robinson@google.com (Will Robinson)'
try:
import unittest2 as unittest #PY26
except ImportError:
import unittest
import unittest
from google.protobuf.internal import test_bad_identifiers_pb2
from google.protobuf import unittest_custom_options_pb2
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unittest for nested public imports."""
import unittest
from google.protobuf.internal.import_test_package import outer_pb2
class ImportTest(unittest.TestCase):
def testPackageInitializationImport(self):
"""Test that we can import nested import public messages."""
msg = outer_pb2.Outer()
self.assertEqual(58, msg.import_public_nested.value)
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,40 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A proto file which is imported by inner.proto to test public importing.
syntax = "proto2";
package google.protobuf.python.internal.import_test_package;
option optimize_for = SPEED;
// Test nested public import
import public "google/protobuf/internal/import_test_package/import_public_nested.proto";
@@ -0,0 +1,40 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A proto file which is imported by import_public.proto to test nested public
// importing.
syntax = "proto2";
package google.protobuf.python.internal.import_test_package;
message ImportPublicNestedMessage {
optional int32 value = 1 [default = 58];
}
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/import_test_package/import_public_nested.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\nGgoogle/protobuf/internal/import_test_package/import_public_nested.proto\x12\x33google.protobuf.python.internal.import_test_package\".\n\x19ImportPublicNestedMessage\x12\x11\n\x05value\x18\x01 \x01(\x05:\x02\x35\x38')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.import_test_package.import_public_nested_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_IMPORTPUBLICNESTEDMESSAGE._serialized_start=128
_IMPORTPUBLICNESTEDMESSAGE._serialized_end=174
# @@protoc_insertion_point(module_scope)
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/import_test_package/import_public.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf.internal.import_test_package import import_public_nested_pb2 as google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__nested__pb2
from google.protobuf.internal.import_test_package.import_public_nested_pb2 import *
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n@google/protobuf/internal/import_test_package/import_public.proto\x12\x33google.protobuf.python.internal.import_test_package\x1aGgoogle/protobuf/internal/import_test_package/import_public_nested.protoB\x02H\x01P\x00')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.import_test_package.import_public_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
DESCRIPTOR._serialized_options = b'H\001'
# @@protoc_insertion_point(module_scope)
@@ -32,6 +32,9 @@ syntax = "proto2";
package google.protobuf.python.internal.import_test_package;
// Test public import
import public "google/protobuf/internal/import_test_package/import_public.proto";
message Inner {
optional int32 value = 1 [default = 57];
}
@@ -2,33 +2,30 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/import_test_package/inner.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf.internal.import_test_package import import_public_pb2 as google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__pb2
try:
google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__nested__pb2 = google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__pb2.google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__nested__pb2
except AttributeError:
google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__nested__pb2 = google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__pb2.google.protobuf.internal.import_test_package.import_public_nested_pb2
from google.protobuf.internal.import_test_package.import_public_pb2 import *
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n8google/protobuf/internal/import_test_package/inner.proto\x12\x33google.protobuf.python.internal.import_test_package\"\x1a\n\x05Inner\x12\x11\n\x05value\x18\x01 \x01(\x05:\x02\x35\x37')
_INNER = DESCRIPTOR.message_types_by_name['Inner']
Inner = _reflection.GeneratedProtocolMessageType('Inner', (_message.Message,), {
'DESCRIPTOR' : _INNER,
'__module__' : 'google.protobuf.internal.import_test_package.inner_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.import_test_package.Inner)
})
_sym_db.RegisterMessage(Inner)
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n8google/protobuf/internal/import_test_package/inner.proto\x12\x33google.protobuf.python.internal.import_test_package\x1a@google/protobuf/internal/import_test_package/import_public.proto\"\x1a\n\x05Inner\x12\x11\n\x05value\x18\x01 \x01(\x05:\x02\x35\x37P\x00')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.import_test_package.inner_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_INNER._serialized_start=113
_INNER._serialized_end=139
_INNER._serialized_start=179
_INNER._serialized_end=205
# @@protoc_insertion_point(module_scope)
@@ -36,4 +36,5 @@ import "google/protobuf/internal/import_test_package/inner.proto";
message Outer {
optional Inner inner = 1;
optional ImportPublicNestedMessage import_public_nested = 2;
}
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/import_test_package/outer.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -13,23 +12,23 @@ _sym_db = _symbol_database.Default()
from google.protobuf.internal.import_test_package import inner_pb2 as google_dot_protobuf_dot_internal_dot_import__test__package_dot_inner__pb2
try:
google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__pb2 = google_dot_protobuf_dot_internal_dot_import__test__package_dot_inner__pb2.google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__pb2
except AttributeError:
google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__pb2 = google_dot_protobuf_dot_internal_dot_import__test__package_dot_inner__pb2.google.protobuf.internal.import_test_package.import_public_pb2
try:
google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__nested__pb2 = google_dot_protobuf_dot_internal_dot_import__test__package_dot_inner__pb2.google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__nested__pb2
except AttributeError:
google_dot_protobuf_dot_internal_dot_import__test__package_dot_import__public__nested__pb2 = google_dot_protobuf_dot_internal_dot_import__test__package_dot_inner__pb2.google.protobuf.internal.import_test_package.import_public_nested_pb2
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n8google/protobuf/internal/import_test_package/outer.proto\x12\x33google.protobuf.python.internal.import_test_package\x1a\x38google/protobuf/internal/import_test_package/inner.proto\"R\n\x05Outer\x12I\n\x05inner\x18\x01 \x01(\x0b\x32:.google.protobuf.python.internal.import_test_package.Inner')
_OUTER = DESCRIPTOR.message_types_by_name['Outer']
Outer = _reflection.GeneratedProtocolMessageType('Outer', (_message.Message,), {
'DESCRIPTOR' : _OUTER,
'__module__' : 'google.protobuf.internal.import_test_package.outer_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.import_test_package.Outer)
})
_sym_db.RegisterMessage(Outer)
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n8google/protobuf/internal/import_test_package/outer.proto\x12\x33google.protobuf.python.internal.import_test_package\x1a\x38google/protobuf/internal/import_test_package/inner.proto\"\xc0\x01\n\x05Outer\x12I\n\x05inner\x18\x01 \x01(\x0b\x32:.google.protobuf.python.internal.import_test_package.Inner\x12l\n\x14import_public_nested\x18\x02 \x01(\x0b\x32N.google.protobuf.python.internal.import_test_package.ImportPublicNestedMessage')
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.import_test_package.outer_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
_OUTER._serialized_start=171
_OUTER._serialized_end=253
_OUTER._serialized_start=172
_OUTER._serialized_end=364
# @@protoc_insertion_point(module_scope)
@@ -100,10 +100,8 @@ class JsonFormatBase(unittest.TestCase):
def CheckError(self, text, error_message):
message = json_format_proto3_pb2.TestMessage()
self.assertRaisesRegexp(
json_format.ParseError,
error_message,
json_format.Parse, text, message)
self.assertRaisesRegex(json_format.ParseError, error_message,
json_format.Parse, text, message)
class JsonFormatTest(JsonFormatBase):
@@ -697,8 +695,7 @@ class JsonFormatTest(JsonFormatBase):
json_format.MessageToJson(message, True, descriptor_pool=empty_pool)
self.assertEqual(
'Can not find message descriptor by type_url:'
' type.googleapis.com/protobuf_unittest.OneString.',
str(cm.exception))
' type.googleapis.com/protobuf_unittest.OneString', str(cm.exception))
def testWellKnownInAnyMessage(self):
message = any_pb2.Any()
@@ -813,16 +810,16 @@ class JsonFormatTest(JsonFormatBase):
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.assertRaisesRegexp(
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.')
self.assertRaisesRegex(
json_format.ParseError, r'Failed to parse repeatedInt32Value field: '
r'null is not allowed to be used as an element in a repeated field '
r'at TestMessage.repeatedInt32Value\[1\].', json_format.Parse,
'{"repeatedInt32Value":[1, null]}', parsed_message)
self.CheckError(
'{"repeatedMessageValue":[null]}',
r'Failed to parse repeatedMessageValue field: null is not'
r' allowed to be used as an element in a repeated field '
r'at TestMessage.repeatedMessageValue\[0\].')
def testNanFloat(self):
message = json_format_proto3_pb2.TestMessage()
@@ -840,9 +837,9 @@ class JsonFormatTest(JsonFormatBase):
self.assertEqual(message.repeated_double_value[0], 3.4028235e+39)
self.assertEqual(message.repeated_double_value[1], 1.4028235e-39)
text = ('{"repeatedFloatValue": [3.4028235e+39, 1.4028235e-39]\n}')
self.CheckError(text,
'Failed to parse repeatedFloatValue field: '
'Float value too large.')
self.CheckError(
text, r'Failed to parse repeatedFloatValue field: '
r'Float value too large at TestMessage.repeatedFloatValue\[0\].')
def testFloatPrecision(self):
message = json_format_proto3_pb2.TestMessage()
@@ -895,17 +892,18 @@ class JsonFormatTest(JsonFormatBase):
self.CheckError(
'{"enumValue": "baz"}',
'Failed to parse enumValue field: Invalid enum value baz '
'for enum type proto3.EnumType.')
'for enum type proto3.EnumType at TestMessage.enumValue.')
# Proto3 accepts numeric unknown enums.
text = '{"enumValue": 12345}'
json_format.Parse(text, message)
# Proto2 does not accept unknown enums.
message = unittest_pb2.TestAllTypes()
self.assertRaisesRegexp(
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)
'for enum type protobuf_unittest.TestAllTypes.NestedEnum at '
'TestAllTypes.optionalNestedEnum.', json_format.Parse,
'{"optionalNestedEnum": 12345}', message)
def testBytes(self):
message = json_format_proto3_pb2.TestMessage()
@@ -928,9 +926,10 @@ class JsonFormatTest(JsonFormatBase):
self.CheckError('{int32Value: 1}',
(r'Failed to load JSON: Expecting property name'
r'( enclosed in double quotes)?: line 1'))
self.CheckError('{"unknownName": 1}',
'Message type "proto3.TestMessage" has no field named '
'"unknownName".')
self.CheckError(
'{"unknownName": 1}',
'Message type "proto3.TestMessage" has no field named '
'"unknownName" at "TestMessage".')
def testIgnoreUnknownField(self):
text = '{"unknownName": 1}'
@@ -950,33 +949,34 @@ class JsonFormatTest(JsonFormatBase):
'Failed to load JSON: duplicate key int32Value.')
def testInvalidBoolValue(self):
self.CheckError('{"boolValue": 1}',
'Failed to parse boolValue field: '
'Expected true or false without quotes.')
self.CheckError('{"boolValue": "true"}',
'Failed to parse boolValue field: '
'Expected true or false without quotes.')
self.CheckError(
'{"boolValue": 1}', 'Failed to parse boolValue field: '
'Expected true or false without quotes at TestMessage.boolValue.')
self.CheckError(
'{"boolValue": "true"}', 'Failed to parse boolValue field: '
'Expected true or false without quotes at TestMessage.boolValue.')
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": 1.5}', 'Failed to parse int32Value field: '
'Couldn\'t parse integer: 1.5 at TestMessage.int32Value.')
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": false}',
'Failed to parse int32Value field: Bool value False '
'is not acceptable for integer field.')
self.CheckError(
'{"int32Value": " 1 "}', 'Failed to parse int32Value field: '
'Couldn\'t parse integer: " 1 " at TestMessage.int32Value.')
self.CheckError(
'{"int32Value": "1 "}', 'Failed to parse int32Value field: '
'Couldn\'t parse integer: "1 " at TestMessage.int32Value.')
self.CheckError(
'{"int32Value": false}',
'Failed to parse int32Value field: Bool value False '
'is not acceptable for integer field at TestMessage.int32Value.')
self.CheckError('{"int32Value": 12345678901234567890}',
'Failed to parse int32Value field: Value out of range: '
'12345678901234567890.')
@@ -985,9 +985,9 @@ class JsonFormatTest(JsonFormatBase):
'Value out of range: -1.')
def testInvalidFloatValue(self):
self.CheckError('{"floatValue": "nan"}',
'Failed to parse floatValue field: Couldn\'t '
'parse float "nan", use "NaN" instead.')
self.CheckError(
'{"floatValue": "nan"}', 'Failed to parse floatValue field: Couldn\'t '
'parse float "nan", use "NaN" instead at TestMessage.floatValue.')
self.CheckError('{"floatValue": NaN}',
'Failed to parse floatValue field: Couldn\'t '
'parse NaN, use quoted "NaN" instead.')
@@ -1008,71 +1008,65 @@ class JsonFormatTest(JsonFormatBase):
'Failed to parse floatValue field: Float value too small.')
def testInvalidRepeated(self):
self.CheckError('{"repeatedInt32Value": 12345}',
(r'Failed to parse repeatedInt32Value field: repeated field'
r' repeatedInt32Value must be in \[\] which is 12345.'))
self.CheckError(
'{"repeatedInt32Value": 12345}',
(r'Failed to parse repeatedInt32Value field: repeated field'
r' repeatedInt32Value must be in \[\] which is 12345 at TestMessage.'))
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)
self.assertRaisesRegex(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)
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.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
'Failed to parse boolMap field: Expected "true" or "false", not null.',
json_format.Parse, text, message)
'Failed to parse boolMap field: Expected "true" or "false", not null at '
'TestMap.boolMap.key', json_format.Parse, text, message)
text = r'{"stringMap": {"a": 3, "\u0061": 2}}'
self.assertRaisesRegexp(
json_format.ParseError,
'Failed to load JSON: duplicate key a',
json_format.Parse, text, message)
self.assertRaisesRegex(json_format.ParseError,
'Failed to load JSON: duplicate key a',
json_format.Parse, text, message)
text = r'{"stringMap": 0}'
self.assertRaisesRegexp(
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)
'in a dict which is 0 at TestMap.stringMap.', json_format.Parse, text,
message)
def testInvalidTimestamp(self):
message = json_format_proto3_pb2.TestTimestamp()
text = '{"value": "10000-01-01T00:00:00.00Z"}'
self.assertRaisesRegexp(
json_format.ParseError,
'Failed to parse value field: '
json_format.ParseError, 'Failed to parse value field: '
'time data \'10000-01-01T00:00:00\' does not match'
' format \'%Y-%m-%dT%H:%M:%S\'.',
' format \'%Y-%m-%dT%H:%M:%S\' at TestTimestamp.value.',
json_format.Parse, text, message)
text = '{"value": "1970-01-01T00:00:00.0123456789012Z"}'
self.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
'nanos 0123456789012 more than 9 fractional digits.',
json_format.Parse, text, message)
'nanos 0123456789012 more than 9 fractional digits.', json_format.Parse,
text, message)
text = '{"value": "1972-01-01T01:00:00.01+08"}'
self.assertRaisesRegexp(
json_format.ParseError,
(r'Invalid timezone offset value: \+08.'),
json_format.Parse, text, message)
self.assertRaisesRegex(json_format.ParseError,
(r'Invalid timezone offset value: \+08.'),
json_format.Parse, text, message)
# Time smaller than minimum time.
text = '{"value": "0000-01-01T00:00:00Z"}'
self.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
'Failed to parse value field: year (0 )?is out of range.',
json_format.Parse, text, message)
# Time bigger than maximum time.
message.value.seconds = 253402300800
self.assertRaisesRegexp(
OverflowError,
'date value out of range',
json_format.MessageToJson, message)
self.assertRaisesRegex(OverflowError, 'date value out of range',
json_format.MessageToJson, message)
# Lower case t does not accept.
text = '{"value": "0001-01-01t00:00:00Z"}'
with self.assertRaises(json_format.ParseError) as e:
@@ -1080,38 +1074,47 @@ class JsonFormatTest(JsonFormatBase):
self.assertEqual(
'Failed to parse value field: '
'time data \'0001-01-01t00:00:00\' does not match format '
'\'%Y-%m-%dT%H:%M:%S\', lowercase \'t\' is not accepted.',
str(e.exception))
'\'%Y-%m-%dT%H:%M:%S\', lowercase \'t\' is not accepted '
'at TestTimestamp.value.', str(e.exception))
def testInvalidOneof(self):
message = json_format_proto3_pb2.TestOneof()
text = '{"oneofInt32Value": 1, "oneofStringValue": "2"}'
self.assertRaisesRegexp(
json_format.ParseError,
'Message type "proto3.TestOneof"'
' should not have multiple "oneof_value" oneof fields.',
json_format.ParseError, 'Message type "proto3.TestOneof"'
' should not have multiple "oneof_value" oneof fields at "TestOneof".',
json_format.Parse, text, message)
def testInvalidListValue(self):
message = json_format_proto3_pb2.TestListValue()
text = '{"value": 1234}'
self.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
r'Failed to parse value field: ListValue must be in \[\] which is 1234',
json_format.Parse, text, message)
r'Failed to parse value field: ListValue must be in \[\] which is '
'1234 at TestListValue.value.', json_format.Parse, text, message)
class UnknownClass(object):
def __str__(self):
return 'v'
self.assertRaisesRegex(
json_format.ParseError,
r' at TestListValue.value\[1\].fake.',
json_format.ParseDict,
{'value': ['hello', {'fake': UnknownClass()}]}, message)
def testInvalidStruct(self):
message = json_format_proto3_pb2.TestStruct()
text = '{"value": 1234}'
self.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
'Failed to parse value field: Struct must be in a dict which is 1234',
json_format.Parse, text, message)
'Failed to parse value field: Struct must be in a dict which is '
'1234 at TestStruct.value', json_format.Parse, text, message)
def testTimestampInvalidStringValue(self):
message = json_format_proto3_pb2.TestTimestamp()
text = '{"value": {"foo": 123}}'
self.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
r"Timestamp JSON value not a string: {u?'foo': 123}", json_format.Parse,
text, message)
@@ -1119,15 +1122,14 @@ class JsonFormatTest(JsonFormatBase):
def testDurationInvalidStringValue(self):
message = json_format_proto3_pb2.TestDuration()
text = '{"value": {"foo": 123}}'
self.assertRaisesRegexp(
json_format.ParseError,
r"Duration JSON value not a string: {u?'foo': 123}", json_format.Parse,
text, message)
self.assertRaisesRegex(json_format.ParseError,
r"Duration JSON value not a string: {u?'foo': 123}",
json_format.Parse, text, message)
def testFieldMaskInvalidStringValue(self):
message = json_format_proto3_pb2.TestFieldMask()
text = '{"value": {"foo": 123}}'
self.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
r"FieldMask JSON value not a string: {u?'foo': 123}", json_format.Parse,
text, message)
@@ -1135,21 +1137,16 @@ class JsonFormatTest(JsonFormatBase):
def testInvalidAny(self):
message = any_pb2.Any()
text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
self.assertRaisesRegexp(
KeyError,
'value',
json_format.Parse, text, message)
self.assertRaisesRegex(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)
self.assertRaisesRegex(json_format.ParseError,
'@type is missing when parsing any message at Any',
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)
self.assertRaisesRegex(
json_format.ParseError, 'Can not find message descriptor by type_url: '
'type.googleapis.com/MessageNotExist at Any', 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}')
@@ -1225,7 +1222,9 @@ class JsonFormatTest(JsonFormatBase):
self.assertEqual(
str(cm.exception),
'Failed to parse any_value field: Can not find message descriptor by'
' type_url: type.googleapis.com/proto3.MessageType..')
' type_url: type.googleapis.com/proto3.MessageType at '
'TestAny.any_value.'
)
def testParseDictUnknownValueType(self):
class UnknownClass(object):
@@ -1233,12 +1232,10 @@ class JsonFormatTest(JsonFormatBase):
def __repr__(self):
return 'v'
message = json_format_proto3_pb2.TestValue()
self.assertRaisesRegexp(
self.assertRaisesRegex(
json_format.ParseError,
r"Value v has unexpected type <class '.*\.UnknownClass'>.",
json_format.ParseDict,
{'value': UnknownClass()},
message)
json_format.ParseDict, {'value': UnknownClass()}, message)
def testMessageToDict(self):
message = json_format_proto3_pb2.TestMessage()
@@ -1271,6 +1268,18 @@ class JsonFormatTest(JsonFormatBase):
'uint32Value': 4, 'stringValue': 'bla'},
indent=2, sort_keys=True))
def testNestedRecursiveLimit(self):
message = unittest_pb2.NestedTestAllTypes()
self.assertRaisesRegex(
json_format.ParseError,
'Message too deep. Max recursion depth is 3',
json_format.Parse,
'{"child": {"child": {"child" : {}}}}',
message,
max_recursion_depth=3)
# The following one can pass
json_format.Parse('{"payload": {}, "child": {"child":{}}}',
message, max_recursion_depth=3)
if __name__ == '__main__':
unittest.main()
@@ -174,48 +174,42 @@ class MessageFactoryTest(unittest.TestCase):
factory = message_factory.MessageFactory(pool=pool)
# Add Container message.
f = descriptor_pb2.FileDescriptorProto()
f.name = 'google/protobuf/internal/container.proto'
f.package = 'google.protobuf.python.internal'
msg = f.message_type.add()
msg.name = 'Container'
rng = msg.extension_range.add()
rng.start = 1
rng.end = 10
f = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/container.proto',
package='google.protobuf.python.internal')
f.message_type.add(name='Container').extension_range.add(start=1, end=10)
pool.Add(f)
msgs = factory.GetMessages([f.name])
self.assertIn('google.protobuf.python.internal.Container', msgs)
# Extend container.
f = descriptor_pb2.FileDescriptorProto()
f.name = 'google/protobuf/internal/extension.proto'
f.package = 'google.protobuf.python.internal'
f.dependency.append('google/protobuf/internal/container.proto')
msg = f.message_type.add()
msg.name = 'Extension'
ext = msg.extension.add()
ext.name = 'extension_field'
ext.number = 2
ext.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
ext.type_name = 'Extension'
ext.extendee = 'Container'
f = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/extension.proto',
package='google.protobuf.python.internal',
dependency=['google/protobuf/internal/container.proto'])
msg = f.message_type.add(name='Extension')
msg.extension.add(
name='extension_field',
number=2,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='Extension',
extendee='Container')
pool.Add(f)
msgs = factory.GetMessages([f.name])
self.assertIn('google.protobuf.python.internal.Extension', msgs)
# Add Duplicate extending the same field number.
f = descriptor_pb2.FileDescriptorProto()
f.name = 'google/protobuf/internal/duplicate.proto'
f.package = 'google.protobuf.python.internal'
f.dependency.append('google/protobuf/internal/container.proto')
msg = f.message_type.add()
msg.name = 'Duplicate'
ext = msg.extension.add()
ext.name = 'extension_field'
ext.number = 2
ext.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL
ext.type_name = 'Duplicate'
ext.extendee = 'Container'
f = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/duplicate.proto',
package='google.protobuf.python.internal',
dependency=['google/protobuf/internal/container.proto'])
msg = f.message_type.add(name='Duplicate')
msg.extension.add(
name='extension_field',
number=2,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='Duplicate',
extendee='Container')
pool.Add(f)
with self.assertRaises(Exception) as cm:
@@ -230,6 +224,76 @@ class MessageFactoryTest(unittest.TestCase):
' with field number 2.',
'Double registration of Extensions'])
def testExtensionValueInDifferentFile(self):
# Add Container message.
f1 = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/container.proto',
package='google.protobuf.python.internal')
f1.message_type.add(name='Container').extension_range.add(start=1, end=10)
# Add ValueType message.
f2 = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/value_type.proto',
package='google.protobuf.python.internal')
f2.message_type.add(name='ValueType').field.add(
name='setting',
number=1,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type=descriptor_pb2.FieldDescriptorProto.TYPE_INT32,
default_value='123')
# Extend container with field of ValueType.
f3 = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/extension.proto',
package='google.protobuf.python.internal',
dependency=[f1.name, f2.name])
f3.extension.add(
name='top_level_extension_field',
number=2,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='ValueType',
extendee='Container')
f3.message_type.add(name='Extension').extension.add(
name='nested_extension_field',
number=3,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='ValueType',
extendee='Container')
class SimpleDescriptorDB:
def __init__(self, files):
self._files = files
def FindFileByName(self, name):
return self._files[name]
db = SimpleDescriptorDB({f1.name: f1, f2.name: f2, f3.name: f3})
pool = descriptor_pool.DescriptorPool(db)
factory = message_factory.MessageFactory(pool=pool)
msgs = factory.GetMessages([f1.name, f3.name]) # Deliberately not f2.
msg = msgs['google.protobuf.python.internal.Container']
desc = msgs['google.protobuf.python.internal.Extension'].DESCRIPTOR
ext1 = desc.file.extensions_by_name['top_level_extension_field']
ext2 = desc.extensions_by_name['nested_extension_field']
m = msg()
m.Extensions[ext1].setting = 234
m.Extensions[ext2].setting = 345
serialized = m.SerializeToString()
pool = descriptor_pool.DescriptorPool(db)
factory = message_factory.MessageFactory(pool=pool)
msgs = factory.GetMessages([f1.name, f3.name]) # Deliberately not f2.
msg = msgs['google.protobuf.python.internal.Container']
desc = msgs['google.protobuf.python.internal.Extension'].DESCRIPTOR
ext1 = desc.file.extensions_by_name['top_level_extension_field']
ext2 = desc.extensions_by_name['nested_extension_field']
m = msg.FromString(serialized)
self.assertEqual(2, len(m.ListFields()))
self.assertEqual(234, m.Extensions[ext1].setting)
self.assertEqual(345, m.Extensions[ext2].setting)
if __name__ == '__main__':
unittest.main()
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/message_set_extensions.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,42 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n5google/protobuf/internal/message_set_extensions.proto\x12\x18google.protobuf.internal\"\x1e\n\x0eTestMessageSet*\x08\x08\x04\x10\xff\xff\xff\xff\x07:\x02\x08\x01\"\xa5\x01\n\x18TestMessageSetExtension1\x12\t\n\x01i\x18\x0f \x01(\x05\x32~\n\x15message_set_extension\x12(.google.protobuf.internal.TestMessageSet\x18\xab\xff\xf6. \x01(\x0b\x32\x32.google.protobuf.internal.TestMessageSetExtension1\"\xa7\x01\n\x18TestMessageSetExtension2\x12\x0b\n\x03str\x18\x19 \x01(\t2~\n\x15message_set_extension\x12(.google.protobuf.internal.TestMessageSet\x18\xca\xff\xf6. \x01(\x0b\x32\x32.google.protobuf.internal.TestMessageSetExtension2\"(\n\x18TestMessageSetExtension3\x12\x0c\n\x04text\x18# \x01(\t:\x7f\n\x16message_set_extension3\x12(.google.protobuf.internal.TestMessageSet\x18\xdf\xff\xf6. \x01(\x0b\x32\x32.google.protobuf.internal.TestMessageSetExtension3')
MESSAGE_SET_EXTENSION3_FIELD_NUMBER = 98418655
message_set_extension3 = DESCRIPTOR.extensions_by_name['message_set_extension3']
_TESTMESSAGESET = DESCRIPTOR.message_types_by_name['TestMessageSet']
_TESTMESSAGESETEXTENSION1 = DESCRIPTOR.message_types_by_name['TestMessageSetExtension1']
_TESTMESSAGESETEXTENSION2 = DESCRIPTOR.message_types_by_name['TestMessageSetExtension2']
_TESTMESSAGESETEXTENSION3 = DESCRIPTOR.message_types_by_name['TestMessageSetExtension3']
TestMessageSet = _reflection.GeneratedProtocolMessageType('TestMessageSet', (_message.Message,), {
'DESCRIPTOR' : _TESTMESSAGESET,
'__module__' : 'google.protobuf.internal.message_set_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TestMessageSet)
})
_sym_db.RegisterMessage(TestMessageSet)
TestMessageSetExtension1 = _reflection.GeneratedProtocolMessageType('TestMessageSetExtension1', (_message.Message,), {
'DESCRIPTOR' : _TESTMESSAGESETEXTENSION1,
'__module__' : 'google.protobuf.internal.message_set_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TestMessageSetExtension1)
})
_sym_db.RegisterMessage(TestMessageSetExtension1)
TestMessageSetExtension2 = _reflection.GeneratedProtocolMessageType('TestMessageSetExtension2', (_message.Message,), {
'DESCRIPTOR' : _TESTMESSAGESETEXTENSION2,
'__module__' : 'google.protobuf.internal.message_set_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TestMessageSetExtension2)
})
_sym_db.RegisterMessage(TestMessageSetExtension2)
TestMessageSetExtension3 = _reflection.GeneratedProtocolMessageType('TestMessageSetExtension3', (_message.Message,), {
'DESCRIPTOR' : _TESTMESSAGESETEXTENSION3,
'__module__' : 'google.protobuf.internal.message_set_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TestMessageSetExtension3)
})
_sym_db.RegisterMessage(TestMessageSetExtension3)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.message_set_extensions_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
TestMessageSet.RegisterExtension(message_set_extension3)
TestMessageSet.RegisterExtension(_TESTMESSAGESETEXTENSION1.extensions_by_name['message_set_extension'])
@@ -58,10 +58,7 @@ from google.protobuf import map_proto2_unittest_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf import unittest_proto3_arena_pb2
from google.protobuf import descriptor_pb2
from google.protobuf import descriptor_pool
from google.protobuf import message_factory
from google.protobuf import text_format
from google.protobuf import descriptor
from google.protobuf.internal import api_implementation
from google.protobuf.internal import encoder
from google.protobuf.internal import more_extensions_pb2
@@ -74,21 +71,19 @@ from google.protobuf.internal import _parameterized
UCS2_MAXUNICODE = 65535
warnings.simplefilter('error', DeprecationWarning)
@_parameterized.named_parameters(
('_proto2', unittest_pb2),
('_proto3', unittest_proto3_arena_pb2))
@_parameterized.named_parameters(('_proto2', unittest_pb2),
('_proto3', unittest_proto3_arena_pb2))
@testing_refleaks.TestCase
class MessageTest(unittest.TestCase):
def testBadUtf8String(self, message_module):
if api_implementation.Type() != 'python':
self.skipTest("Skipping testBadUtf8String, currently only the python "
"api implementation raises UnicodeDecodeError when a "
"string field contains bad utf-8.")
self.skipTest('Skipping testBadUtf8String, currently only the python '
'api implementation raises UnicodeDecodeError when a '
'string field contains bad utf-8.')
bad_utf8_data = test_util.GoldenFileData('bad_utf8_string')
with self.assertRaises(UnicodeDecodeError) as context:
message_module.TestAllTypes.FromString(bad_utf8_data)
@@ -99,8 +94,7 @@ class MessageTest(unittest.TestCase):
# and doesn't preserve unknown fields, so for proto3 we use a golden
# message that doesn't have these fields set.
if message_module is unittest_pb2:
golden_data = test_util.GoldenFileData(
'golden_message_oneof_implemented')
golden_data = test_util.GoldenFileData('golden_message_oneof_implemented')
else:
golden_data = test_util.GoldenFileData('golden_message_proto3')
@@ -131,10 +125,13 @@ class MessageTest(unittest.TestCase):
# TODO(jieluo): Fix cpp extension to raise error instead of warning.
# b/27494216
end_tag = encoder.TagBytes(1, 4)
if api_implementation.Type() == 'python':
if (api_implementation.Type() == 'python' or
api_implementation.Type() == 'upb'):
with self.assertRaises(message.DecodeError) as context:
msg.FromString(end_tag)
self.assertEqual('Unexpected end-group tag.', str(context.exception))
if api_implementation.Type() == 'python':
# Only pure-Python has an error message this specific.
self.assertEqual('Unexpected end-group tag.', str(context.exception))
# Field number 0 is illegal.
self.assertRaises(message.DecodeError, msg.FromString, b'\3\4')
@@ -439,8 +436,7 @@ class MessageTest(unittest.TestCase):
except TypeError:
pass
self.assertEqual(2, len(msg.repeated_nested_message))
self.assertEqual([1, 2],
[m.bb for m in msg.repeated_nested_message])
self.assertEqual([1, 2], [m.bb for m in msg.repeated_nested_message])
def testInsertRepeatedCompositeField(self, message_module):
msg = message_module.TestAllTypes()
@@ -462,22 +458,22 @@ class MessageTest(unittest.TestCase):
self.assertEqual(5, len(msg.repeated_nested_message))
self.assertEqual([-1000, 2, -1, 1, 3],
[m.bb for m in msg.repeated_nested_message])
self.assertEqual(str(msg),
'repeated_nested_message {\n'
' bb: -1000\n'
'}\n'
'repeated_nested_message {\n'
' bb: 2\n'
'}\n'
'repeated_nested_message {\n'
' bb: -1\n'
'}\n'
'repeated_nested_message {\n'
' bb: 1\n'
'}\n'
'repeated_nested_message {\n'
' bb: 3\n'
'}\n')
self.assertEqual(
str(msg), 'repeated_nested_message {\n'
' bb: -1000\n'
'}\n'
'repeated_nested_message {\n'
' bb: 2\n'
'}\n'
'repeated_nested_message {\n'
' bb: -1\n'
'}\n'
'repeated_nested_message {\n'
' bb: 1\n'
'}\n'
'repeated_nested_message {\n'
' bb: 3\n'
'}\n')
self.assertEqual(sub_msg.bb, 1)
def testMergeFromRepeatedField(self, message_module):
@@ -496,8 +492,7 @@ class MessageTest(unittest.TestCase):
self.assertEqual(4, len(msg.repeated_int32))
msg.repeated_nested_message.MergeFrom(other_msg.repeated_nested_message)
self.assertEqual([1, 2, 3, 4],
[m.bb for m in msg.repeated_nested_message])
self.assertEqual([1, 2, 3, 4], [m.bb for m in msg.repeated_nested_message])
def testAddWrongRepeatedNestedField(self, message_module):
msg = message_module.TestAllTypes()
@@ -542,8 +537,7 @@ class MessageTest(unittest.TestCase):
msg.repeated_nested_message.add(bb=3)
msg.repeated_nested_message.add(bb=4)
self.assertEqual([1, 2, 3, 4],
[m.bb for m in msg.repeated_nested_message])
self.assertEqual([1, 2, 3, 4], [m.bb for m in msg.repeated_nested_message])
self.assertEqual([4, 3, 2, 1],
[m.bb for m in reversed(msg.repeated_nested_message)])
self.assertEqual([4, 3, 2, 1],
@@ -626,8 +620,9 @@ class MessageTest(unittest.TestCase):
self.assertEqual(message.repeated_nested_message[3].bb, 4)
self.assertEqual(message.repeated_nested_message[4].bb, 5)
self.assertEqual(message.repeated_nested_message[5].bb, 6)
self.assertEqual(str(message.repeated_nested_message),
'[bb: 1\n, bb: 2\n, bb: 3\n, bb: 4\n, bb: 5\n, bb: 6\n]')
self.assertEqual(
str(message.repeated_nested_message),
'[bb: 1\n, bb: 2\n, bb: 3\n, bb: 4\n, bb: 5\n, bb: 6\n]')
def testSortingRepeatedCompositeFieldsStable(self, message_module):
"""Check passing a custom comparator to sort a repeated composite field."""
@@ -641,18 +636,16 @@ class MessageTest(unittest.TestCase):
message.repeated_nested_message.add().bb = 24
message.repeated_nested_message.add().bb = 10
message.repeated_nested_message.sort(key=lambda z: z.bb // 10)
self.assertEqual(
[13, 11, 10, 21, 20, 24, 33],
[n.bb for n in message.repeated_nested_message])
self.assertEqual([13, 11, 10, 21, 20, 24, 33],
[n.bb for n in message.repeated_nested_message])
# Make sure that for the C++ implementation, the underlying fields
# are actually reordered.
pb = message.SerializeToString()
message.Clear()
message.MergeFromString(pb)
self.assertEqual(
[13, 11, 10, 21, 20, 24, 33],
[n.bb for n in message.repeated_nested_message])
self.assertEqual([13, 11, 10, 21, 20, 24, 33],
[n.bb for n in message.repeated_nested_message])
def testRepeatedCompositeFieldSortArguments(self, message_module):
"""Check sorting a repeated composite field using list.sort() arguments."""
@@ -825,7 +818,7 @@ class MessageTest(unittest.TestCase):
self.assertTrue(m.HasField('oneof_uint32'))
self.assertFalse(m.HasField('oneof_string'))
m.oneof_string = ""
m.oneof_string = ''
self.assertEqual('oneof_string', m.WhichOneof('oneof_field'))
self.assertTrue(m.HasField('oneof_string'))
self.assertFalse(m.HasField('oneof_uint32'))
@@ -972,7 +965,9 @@ class MessageTest(unittest.TestCase):
def testAssignByteStringToUnicodeField(self, message_module):
"""Assigning a byte string to a string field should result
in the value being converted to a Unicode string."""
in the value being converted to a Unicode string.
"""
m = message_module.TestAllTypes()
m.optional_string = str('')
self.assertIsInstance(m.optional_string, str)
@@ -1000,8 +995,7 @@ class MessageTest(unittest.TestCase):
with self.assertRaises(NameError) as _:
m.repeated_int32.extend(a for i in range(10)) # pylint: disable=undefined-variable
with self.assertRaises(NameError) as _:
m.repeated_nested_enum.extend(
a for i in range(10)) # pylint: disable=undefined-variable
m.repeated_nested_enum.extend(a for i in range(10)) # pylint: disable=undefined-variable
FALSY_VALUES = [None, False, 0, 0.0, b'', u'', bytearray(), [], {}, set()]
@@ -1147,29 +1141,43 @@ class MessageTest(unittest.TestCase):
m.repeated_string.extend(MessageTest.TestIterable(['3', '4']))
self.assertSequenceEqual(['', '1', '2', '3', '4'], m.repeated_string)
class TestIndex(object):
"""This index object mimics the behavior of numpy.int64 and other types."""
def __init__(self, value=None):
self.value = value
def __index__(self):
return self.value
def testRepeatedIndexingWithIntIndex(self, message_module):
msg = message_module.TestAllTypes()
msg.repeated_int32.extend([1, 2, 3])
self.assertEqual(1, msg.repeated_int32[MessageTest.TestIndex(0)])
def testRepeatedIndexingWithNegative1IntIndex(self, message_module):
msg = message_module.TestAllTypes()
msg.repeated_int32.extend([1, 2, 3])
self.assertEqual(3, msg.repeated_int32[MessageTest.TestIndex(-1)])
def testRepeatedIndexingWithNegative1Int(self, message_module):
msg = message_module.TestAllTypes()
msg.repeated_int32.extend([1, 2, 3])
self.assertEqual(3, msg.repeated_int32[-1])
def testPickleRepeatedScalarContainer(self, message_module):
# TODO(tibell): The pure-Python implementation support pickling of
# scalar containers in *some* cases. For now the cpp2 version
# throws an exception to avoid a segfault. Investigate if we
# want to support pickling of these fields.
#
# For more information see: https://b2.corp.google.com/u/0/issues/18677897
if (api_implementation.Type() != 'cpp' or
api_implementation.Version() == 2):
return
# Pickle repeated scalar container is not supported.
m = message_module.TestAllTypes()
with self.assertRaises(pickle.PickleError) as _:
pickle.dumps(m.repeated_int32, pickle.HIGHEST_PROTOCOL)
def testSortEmptyRepeatedCompositeContainer(self, message_module):
"""Exercise a scenario that has led to segfaults in the past.
"""
"""Exercise a scenario that has led to segfaults in the past."""
m = message_module.TestAllTypes()
m.repeated_nested_message.sort()
def testHasFieldOnRepeatedField(self, message_module):
"""Using HasField on a repeated field should raise an exception.
"""
"""Using HasField on a repeated field should raise an exception."""
m = message_module.TestAllTypes()
with self.assertRaises(ValueError) as _:
m.HasField('repeated_int32')
@@ -1209,6 +1217,7 @@ class MessageTest(unittest.TestCase):
def testReleasedNestedMessages(self, message_module):
"""A case that lead to a segfault when a message detached from its parent
container has itself a child container.
"""
m = message_module.NestedTestAllTypes()
@@ -1254,17 +1263,17 @@ class Proto2Test(unittest.TestCase):
def testFieldPresence(self):
message = unittest_pb2.TestAllTypes()
self.assertFalse(message.HasField("optional_int32"))
self.assertFalse(message.HasField("optional_bool"))
self.assertFalse(message.HasField("optional_nested_message"))
self.assertFalse(message.HasField('optional_int32'))
self.assertFalse(message.HasField('optional_bool'))
self.assertFalse(message.HasField('optional_nested_message'))
with self.assertRaises(ValueError):
message.HasField("field_doesnt_exist")
message.HasField('field_doesnt_exist')
with self.assertRaises(ValueError):
message.HasField("repeated_int32")
message.HasField('repeated_int32')
with self.assertRaises(ValueError):
message.HasField("repeated_nested_message")
message.HasField('repeated_nested_message')
self.assertEqual(0, message.optional_int32)
self.assertEqual(False, message.optional_bool)
@@ -1274,27 +1283,27 @@ class Proto2Test(unittest.TestCase):
message.optional_int32 = 0
message.optional_bool = False
message.optional_nested_message.bb = 0
self.assertTrue(message.HasField("optional_int32"))
self.assertTrue(message.HasField("optional_bool"))
self.assertTrue(message.HasField("optional_nested_message"))
self.assertTrue(message.HasField('optional_int32'))
self.assertTrue(message.HasField('optional_bool'))
self.assertTrue(message.HasField('optional_nested_message'))
# Set the fields to non-default values.
message.optional_int32 = 5
message.optional_bool = True
message.optional_nested_message.bb = 15
self.assertTrue(message.HasField(u"optional_int32"))
self.assertTrue(message.HasField("optional_bool"))
self.assertTrue(message.HasField("optional_nested_message"))
self.assertTrue(message.HasField(u'optional_int32'))
self.assertTrue(message.HasField('optional_bool'))
self.assertTrue(message.HasField('optional_nested_message'))
# Clearing the fields unsets them and resets their value to default.
message.ClearField("optional_int32")
message.ClearField(u"optional_bool")
message.ClearField("optional_nested_message")
message.ClearField('optional_int32')
message.ClearField(u'optional_bool')
message.ClearField('optional_nested_message')
self.assertFalse(message.HasField("optional_int32"))
self.assertFalse(message.HasField("optional_bool"))
self.assertFalse(message.HasField("optional_nested_message"))
self.assertFalse(message.HasField('optional_int32'))
self.assertFalse(message.HasField('optional_bool'))
self.assertFalse(message.HasField('optional_nested_message'))
self.assertEqual(0, message.optional_int32)
self.assertEqual(False, message.optional_bool)
self.assertEqual(0, message.optional_nested_message.bb)
@@ -1344,16 +1353,17 @@ class Proto2Test(unittest.TestCase):
msg1 = more_extensions_pb2.TopLevelMessage()
msg2 = more_extensions_pb2.TopLevelMessage()
# Cpp extension will lazily create a sub message which is immutable.
self.assertEqual(0, msg1.submessage.Extensions[
more_extensions_pb2.optional_int_extension])
self.assertEqual(
0,
msg1.submessage.Extensions[more_extensions_pb2.optional_int_extension])
self.assertFalse(msg1.HasField('submessage'))
msg2.submessage.Extensions[
more_extensions_pb2.optional_int_extension] = 123
msg2.submessage.Extensions[more_extensions_pb2.optional_int_extension] = 123
# Make sure cmessage and extensions pointing to a mutable message
# after merge instead of the lazily created message.
msg1.MergeFrom(msg2)
self.assertEqual(123, msg1.submessage.Extensions[
more_extensions_pb2.optional_int_extension])
self.assertEqual(
123,
msg1.submessage.Extensions[more_extensions_pb2.optional_int_extension])
def testGoldenExtensions(self):
golden_data = test_util.GoldenFileData('golden_message')
@@ -1387,17 +1397,19 @@ class Proto2Test(unittest.TestCase):
# This is still an incomplete proto - so serializing should fail
self.assertRaises(message.EncodeError, unpickled_message.SerializeToString)
# TODO(haberman): this isn't really a proto2-specific test except that this
# message has a required field in it. Should probably be factored out so
# that we can test the other parts with proto3.
def testParsingMerge(self):
"""Check the merge behavior when a required or optional field appears
multiple times in the input."""
multiple times in the input.
"""
messages = [
unittest_pb2.TestAllTypes(),
unittest_pb2.TestAllTypes(),
unittest_pb2.TestAllTypes() ]
unittest_pb2.TestAllTypes()
]
messages[0].optional_int32 = 1
messages[1].optional_int64 = 2
messages[2].optional_int32 = 3
@@ -1430,15 +1442,16 @@ class Proto2Test(unittest.TestCase):
self.assertEqual(parsing_merge.optional_all_types, merged_message)
self.assertEqual(parsing_merge.optionalgroup.optional_group_all_types,
merged_message)
self.assertEqual(parsing_merge.Extensions[
unittest_pb2.TestParsingMerge.optional_ext],
merged_message)
self.assertEqual(
parsing_merge.Extensions[unittest_pb2.TestParsingMerge.optional_ext],
merged_message)
# Repeated fields should not be merged.
self.assertEqual(len(parsing_merge.repeated_all_types), 3)
self.assertEqual(len(parsing_merge.repeatedgroup), 3)
self.assertEqual(len(parsing_merge.Extensions[
unittest_pb2.TestParsingMerge.repeated_ext]), 3)
self.assertEqual(
len(parsing_merge.Extensions[
unittest_pb2.TestParsingMerge.repeated_ext]), 3)
def testPythonicInit(self):
message = unittest_pb2.TestAllTypes(
@@ -1450,8 +1463,11 @@ class Proto2Test(unittest.TestCase):
optional_nested_message={'bb': 500},
optional_foreign_message={},
optional_nested_enum='BAZ',
repeatedgroup=[{'a': 600},
{'a': 700}],
repeatedgroup=[{
'a': 600
}, {
'a': 700
}],
repeated_nested_enum=['FOO', unittest_pb2.TestAllTypes.BAR],
default_int32=800,
oneof_string='y')
@@ -1658,6 +1674,26 @@ class Proto3Test(unittest.TestCase):
self.assertEqual(msg.WhichOneof('_optional_int32'), None)
# Test has presence:
for field in test_proto3_optional_pb2.TestProto3Optional.DESCRIPTOR.fields:
self.assertTrue(field.has_presence)
for field in unittest_pb2.TestAllTypes.DESCRIPTOR.fields:
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
self.assertFalse(field.has_presence)
else:
self.assertTrue(field.has_presence)
proto3_descriptor = unittest_proto3_arena_pb2.TestAllTypes.DESCRIPTOR
repeated_field = proto3_descriptor.fields_by_name['repeated_int32']
self.assertFalse(repeated_field.has_presence)
singular_field = proto3_descriptor.fields_by_name['optional_int32']
self.assertFalse(singular_field.has_presence)
optional_field = proto3_descriptor.fields_by_name['proto3_optional_int32']
self.assertTrue(optional_field.has_presence)
message_field = proto3_descriptor.fields_by_name['optional_nested_message']
self.assertTrue(message_field.has_presence)
oneof_field = proto3_descriptor.fields_by_name['oneof_uint32']
self.assertTrue(oneof_field.has_presence)
def testAssignUnknownEnum(self):
"""Assigning an unknown enum value is allowed and preserves the value."""
m = unittest_proto3_arena_pb2.TestAllTypes()
@@ -1811,8 +1847,7 @@ class Proto3Test(unittest.TestCase):
self.assertEqual(True, msg2.map_bool_bool[True])
self.assertEqual(2, msg2.map_int32_enum[888])
self.assertEqual(456, msg2.map_int32_enum[123])
self.assertEqual('{-123: -456}',
str(msg2.map_int32_int32))
self.assertEqual('{-123: -456}', str(msg2.map_int32_int32))
def testMapEntryAlwaysSerialized(self):
msg = map_unittest_pb2.TestMap()
@@ -1875,8 +1910,9 @@ class Proto3Test(unittest.TestCase):
self.assertEqual(2, len(msg2.map_int32_foreign_message))
msg2.map_int32_foreign_message[123].c = 1
# TODO(jieluo): Fix text format for message map.
self.assertIn(str(msg2.map_int32_foreign_message),
('{-456: , 123: c: 1\n}', '{123: c: 1\n, -456: }'))
self.assertIn(
str(msg2.map_int32_foreign_message),
('{-456: , 123: c: 1\n}', '{123: c: 1\n, -456: }'))
def testNestedMessageMapItemDelete(self):
msg = map_unittest_pb2.TestMap()
@@ -2004,8 +2040,7 @@ class Proto3Test(unittest.TestCase):
# Test when cpp extension cache a map.
m1 = map_unittest_pb2.TestMap()
m2 = map_unittest_pb2.TestMap()
self.assertEqual(m1.map_int32_foreign_message,
m1.map_int32_foreign_message)
self.assertEqual(m1.map_int32_foreign_message, m1.map_int32_foreign_message)
m2.map_int32_foreign_message[123].c = 10
m1.MergeFrom(m2)
self.assertEqual(10, m2.map_int32_foreign_message[123].c)
@@ -2033,7 +2068,7 @@ class Proto3Test(unittest.TestCase):
def testMergeFromBadType(self):
msg = map_unittest_pb2.TestMap()
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
TypeError,
r'Parameter to MergeFrom\(\) must be instance of same class: expected '
r'.+TestMap got int\.'):
@@ -2041,7 +2076,7 @@ class Proto3Test(unittest.TestCase):
def testCopyFromBadType(self):
msg = map_unittest_pb2.TestMap()
with self.assertRaisesRegexp(
with self.assertRaisesRegex(
TypeError,
r'Parameter to [A-Za-z]*From\(\) must be instance of same class: '
r'expected .+TestMap got int\.'):
@@ -2130,6 +2165,34 @@ class Proto3Test(unittest.TestCase):
for key in int32_foreign_iter:
pass
def testModifyMapEntryWhileIterating(self):
msg = map_unittest_pb2.TestMap()
msg.map_string_string['abc'] = '123'
msg.map_string_string['def'] = '456'
msg.map_string_string['ghi'] = '789'
msg.map_int32_foreign_message[5].c = 5
msg.map_int32_foreign_message[6].c = 6
msg.map_int32_foreign_message[7].c = 7
string_string_keys = list(msg.map_string_string.keys())
int32_foreign_keys = list(msg.map_int32_foreign_message.keys())
keys = []
for key in msg.map_string_string:
keys.append(key)
msg.map_string_string[key] = '000'
self.assertEqual(keys, string_string_keys)
self.assertEqual(keys, list(msg.map_string_string.keys()))
keys = []
for key in msg.map_int32_foreign_message:
keys.append(key)
msg.map_int32_foreign_message[key].c = 0
self.assertEqual(keys, int32_foreign_keys)
self.assertEqual(keys, list(msg.map_int32_foreign_message.keys()))
def testSubmessageMap(self):
msg = map_unittest_pb2.TestMap()
@@ -2166,7 +2229,7 @@ class Proto3Test(unittest.TestCase):
def testMapItems(self):
# Map items used to have strange behaviors when use c extension. Because
# [] may reorder the map and invalidate any exsting iterators.
# [] may reorder the map and invalidate any existing iterators.
# TODO(jieluo): Check if [] reordering the map is a bug or intended
# behavior.
msg = map_unittest_pb2.TestMap()
@@ -2241,7 +2304,7 @@ class Proto3Test(unittest.TestCase):
msg1 = map_unittest_pb2.TestMap()
msg1.map_string_foreign_message['test'].c = 42
msg2 = map_unittest_pb2.TestMap(
map_string_foreign_message=msg1.map_string_foreign_message)
map_string_foreign_message=msg1.map_string_foreign_message)
self.assertEqual(42, msg2.map_string_foreign_message['test'].c)
def testMapFieldRaisesCorrectError(self):
@@ -2376,24 +2439,21 @@ class Proto3Test(unittest.TestCase):
msg2.MergeFromString(serialized)
self.assertEqual(msg2.optional_string, u'😍')
msg = unittest_proto3_arena_pb2.TestAllTypes(
optional_string=u'\ud001')
msg = unittest_proto3_arena_pb2.TestAllTypes(optional_string=u'\ud001')
self.assertEqual(msg.optional_string, u'\ud001')
def testSurrogatesInPython3(self):
# Surrogates are rejected at setters in Python3.
with self.assertRaises(ValueError):
unittest_proto3_arena_pb2.TestAllTypes(
optional_string=u'\ud801\udc01')
unittest_proto3_arena_pb2.TestAllTypes(optional_string=u'\ud801\udc01')
with self.assertRaises(ValueError):
unittest_proto3_arena_pb2.TestAllTypes(
optional_string=b'\xed\xa0\x81')
unittest_proto3_arena_pb2.TestAllTypes(optional_string=b'\xed\xa0\x81')
with self.assertRaises(ValueError):
unittest_proto3_arena_pb2.TestAllTypes(
optional_string=u'\ud801')
unittest_proto3_arena_pb2.TestAllTypes(optional_string=u'\ud801')
with self.assertRaises(ValueError):
unittest_proto3_arena_pb2.TestAllTypes(
optional_string=u'\ud801\ud801')
unittest_proto3_arena_pb2.TestAllTypes(optional_string=u'\ud801\ud801')
@testing_refleaks.TestCase
@@ -2404,8 +2464,9 @@ class ValidTypeNamesTest(unittest.TestCase):
tp_name = str(type(msg)).split("'")[1]
valid_names = ('Repeated%sContainer' % base_name,
'Repeated%sFieldContainer' % base_name)
self.assertTrue(any(tp_name.endswith(v) for v in valid_names),
'%r does end with any of %r' % (tp_name, valid_names))
self.assertTrue(
any(tp_name.endswith(v) for v in valid_names),
'%r does end with any of %r' % (tp_name, valid_names))
parts = tp_name.split('.')
class_name = parts[-1]
@@ -2418,6 +2479,7 @@ class ValidTypeNamesTest(unittest.TestCase):
self.assertImportFromName(pb.repeated_int32, 'Scalar')
self.assertImportFromName(pb.repeated_nested_message, 'Composite')
@testing_refleaks.TestCase
class PackedFieldTest(unittest.TestCase):
@@ -2476,66 +2538,35 @@ class PackedFieldTest(unittest.TestCase):
self.assertEqual(golden_data, message.SerializeToString())
@unittest.skipIf(api_implementation.Type() != 'cpp',
@unittest.skipIf(api_implementation.Type() == 'python',
'explicit tests of the C++ implementation')
@testing_refleaks.TestCase
class OversizeProtosTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# At the moment, reference cycles between DescriptorPool and Message classes
# are not detected and these objects are never freed.
# To avoid errors with ReferenceLeakChecker, we create the class only once.
file_desc = """
name: "f/f.msg2"
package: "f"
message_type {
name: "msg1"
field {
name: "payload"
number: 1
label: LABEL_OPTIONAL
type: TYPE_STRING
}
}
message_type {
name: "msg2"
field {
name: "field"
number: 1
label: LABEL_OPTIONAL
type: TYPE_MESSAGE
type_name: "msg1"
}
}
"""
pool = descriptor_pool.DescriptorPool()
desc = descriptor_pb2.FileDescriptorProto()
text_format.Parse(file_desc, desc)
pool.Add(desc)
cls.proto_cls = message_factory.MessageFactory(pool).GetPrototype(
pool.FindMessageTypeByName('f.msg2'))
def GenerateNestedProto(self, n):
msg = unittest_pb2.TestRecursiveMessage()
sub = msg
for _ in range(n):
sub = sub.a
sub.i = 0
return msg.SerializeToString()
def setUp(self):
self.p = self.proto_cls()
self.p.field.payload = 'c' * (1024 * 1024 * 64 + 1)
self.p_serialized = self.p.SerializeToString()
def testSucceedOkSizedProto(self):
msg = unittest_pb2.TestRecursiveMessage()
msg.ParseFromString(self.GenerateNestedProto(100))
def testAssertOversizeProto(self):
from google.protobuf.pyext._message import SetAllowOversizeProtos
SetAllowOversizeProtos(False)
q = self.proto_cls()
try:
q.ParseFromString(self.p_serialized)
except message.DecodeError as e:
self.assertEqual(str(e), 'Error parsing message')
api_implementation._c_module.SetAllowOversizeProtos(False)
msg = unittest_pb2.TestRecursiveMessage()
with self.assertRaises(message.DecodeError) as context:
msg.ParseFromString(self.GenerateNestedProto(101))
self.assertIn('Error parsing message', str(context.exception))
def testSucceedOversizeProto(self):
from google.protobuf.pyext._message import SetAllowOversizeProtos
SetAllowOversizeProtos(True)
q = self.proto_cls()
q.ParseFromString(self.p_serialized)
self.assertEqual(self.p.field.payload, q.field.payload)
api_implementation._c_module.SetAllowOversizeProtos(True)
msg = unittest_pb2.TestRecursiveMessage()
msg.ParseFromString(self.GenerateNestedProto(101))
if __name__ == '__main__':
unittest.main()
@@ -44,9 +44,7 @@ message TestEnumValues {
}
message TestMissingEnumValues {
enum NestedEnum {
TWO = 2;
}
enum NestedEnum { TWO = 2; }
optional NestedEnum optional_nested_enum = 1;
repeated NestedEnum repeated_nested_enum = 2;
repeated NestedEnum packed_nested_enum = 3 [packed = true];
@@ -55,3 +53,4 @@ message TestMissingEnumValues {
message JustString {
required string dummy = 1;
}
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/missing_enum_values.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,34 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n2google/protobuf/internal/missing_enum_values.proto\x12\x1fgoogle.protobuf.python.internal\"\xc1\x02\n\x0eTestEnumValues\x12X\n\x14optional_nested_enum\x18\x01 \x01(\x0e\x32:.google.protobuf.python.internal.TestEnumValues.NestedEnum\x12X\n\x14repeated_nested_enum\x18\x02 \x03(\x0e\x32:.google.protobuf.python.internal.TestEnumValues.NestedEnum\x12Z\n\x12packed_nested_enum\x18\x03 \x03(\x0e\x32:.google.protobuf.python.internal.TestEnumValues.NestedEnumB\x02\x10\x01\"\x1f\n\nNestedEnum\x12\x08\n\x04ZERO\x10\x00\x12\x07\n\x03ONE\x10\x01\"\xd3\x02\n\x15TestMissingEnumValues\x12_\n\x14optional_nested_enum\x18\x01 \x01(\x0e\x32\x41.google.protobuf.python.internal.TestMissingEnumValues.NestedEnum\x12_\n\x14repeated_nested_enum\x18\x02 \x03(\x0e\x32\x41.google.protobuf.python.internal.TestMissingEnumValues.NestedEnum\x12\x61\n\x12packed_nested_enum\x18\x03 \x03(\x0e\x32\x41.google.protobuf.python.internal.TestMissingEnumValues.NestedEnumB\x02\x10\x01\"\x15\n\nNestedEnum\x12\x07\n\x03TWO\x10\x02\"\x1b\n\nJustString\x12\r\n\x05\x64ummy\x18\x01 \x02(\t')
_TESTENUMVALUES = DESCRIPTOR.message_types_by_name['TestEnumValues']
_TESTMISSINGENUMVALUES = DESCRIPTOR.message_types_by_name['TestMissingEnumValues']
_JUSTSTRING = DESCRIPTOR.message_types_by_name['JustString']
_TESTENUMVALUES_NESTEDENUM = _TESTENUMVALUES.enum_types_by_name['NestedEnum']
_TESTMISSINGENUMVALUES_NESTEDENUM = _TESTMISSINGENUMVALUES.enum_types_by_name['NestedEnum']
TestEnumValues = _reflection.GeneratedProtocolMessageType('TestEnumValues', (_message.Message,), {
'DESCRIPTOR' : _TESTENUMVALUES,
'__module__' : 'google.protobuf.internal.missing_enum_values_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestEnumValues)
})
_sym_db.RegisterMessage(TestEnumValues)
TestMissingEnumValues = _reflection.GeneratedProtocolMessageType('TestMissingEnumValues', (_message.Message,), {
'DESCRIPTOR' : _TESTMISSINGENUMVALUES,
'__module__' : 'google.protobuf.internal.missing_enum_values_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestMissingEnumValues)
})
_sym_db.RegisterMessage(TestMissingEnumValues)
JustString = _reflection.GeneratedProtocolMessageType('JustString', (_message.Message,), {
'DESCRIPTOR' : _JUSTSTRING,
'__module__' : 'google.protobuf.internal.missing_enum_values_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.JustString)
})
_sym_db.RegisterMessage(JustString)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.missing_enum_values_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/more_extensions_dynamic.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -17,22 +16,8 @@ from google.protobuf.internal import more_extensions_pb2 as google_dot_protobuf_
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n6google/protobuf/internal/more_extensions_dynamic.proto\x12\x18google.protobuf.internal\x1a.google/protobuf/internal/more_extensions.proto\"\x1f\n\x12\x44ynamicMessageType\x12\t\n\x01\x61\x18\x01 \x01(\x05:J\n\x17\x64ynamic_int32_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x64 \x01(\x05:z\n\x19\x64ynamic_message_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x65 \x01(\x0b\x32,.google.protobuf.internal.DynamicMessageType:\x83\x01\n\"repeated_dynamic_message_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x66 \x03(\x0b\x32,.google.protobuf.internal.DynamicMessageType')
DYNAMIC_INT32_EXTENSION_FIELD_NUMBER = 100
dynamic_int32_extension = DESCRIPTOR.extensions_by_name['dynamic_int32_extension']
DYNAMIC_MESSAGE_EXTENSION_FIELD_NUMBER = 101
dynamic_message_extension = DESCRIPTOR.extensions_by_name['dynamic_message_extension']
REPEATED_DYNAMIC_MESSAGE_EXTENSION_FIELD_NUMBER = 102
repeated_dynamic_message_extension = DESCRIPTOR.extensions_by_name['repeated_dynamic_message_extension']
_DYNAMICMESSAGETYPE = DESCRIPTOR.message_types_by_name['DynamicMessageType']
DynamicMessageType = _reflection.GeneratedProtocolMessageType('DynamicMessageType', (_message.Message,), {
'DESCRIPTOR' : _DYNAMICMESSAGETYPE,
'__module__' : 'google.protobuf.internal.more_extensions_dynamic_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.DynamicMessageType)
})
_sym_db.RegisterMessage(DynamicMessageType)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.more_extensions_dynamic_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
google_dot_protobuf_dot_internal_dot_more__extensions__pb2.ExtendedMessage.RegisterExtension(dynamic_int32_extension)
google_dot_protobuf_dot_internal_dot_more__extensions__pb2.ExtendedMessage.RegisterExtension(dynamic_message_extension)
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/more_extensions.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,48 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n.google/protobuf/internal/more_extensions.proto\x12\x18google.protobuf.internal\"\x99\x01\n\x0fTopLevelMessage\x12\x41\n\nsubmessage\x18\x01 \x01(\x0b\x32).google.protobuf.internal.ExtendedMessageB\x02(\x01\x12\x43\n\x0enested_message\x18\x02 \x01(\x0b\x32\'.google.protobuf.internal.NestedMessageB\x02(\x01\"R\n\rNestedMessage\x12\x41\n\nsubmessage\x18\x01 \x01(\x0b\x32).google.protobuf.internal.ExtendedMessageB\x02(\x01\"K\n\x0f\x45xtendedMessage\x12\x17\n\x0eoptional_int32\x18\xe9\x07 \x01(\x05\x12\x18\n\x0frepeated_string\x18\xea\x07 \x03(\t*\x05\x08\x01\x10\xe8\x07\"-\n\x0e\x46oreignMessage\x12\x1b\n\x13\x66oreign_message_int\x18\x01 \x01(\x05:I\n\x16optional_int_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x01 \x01(\x05:w\n\x1aoptional_message_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x02 \x01(\x0b\x32(.google.protobuf.internal.ForeignMessage:I\n\x16repeated_int_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x03 \x03(\x05:w\n\x1arepeated_message_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x04 \x03(\x0b\x32(.google.protobuf.internal.ForeignMessage')
OPTIONAL_INT_EXTENSION_FIELD_NUMBER = 1
optional_int_extension = DESCRIPTOR.extensions_by_name['optional_int_extension']
OPTIONAL_MESSAGE_EXTENSION_FIELD_NUMBER = 2
optional_message_extension = DESCRIPTOR.extensions_by_name['optional_message_extension']
REPEATED_INT_EXTENSION_FIELD_NUMBER = 3
repeated_int_extension = DESCRIPTOR.extensions_by_name['repeated_int_extension']
REPEATED_MESSAGE_EXTENSION_FIELD_NUMBER = 4
repeated_message_extension = DESCRIPTOR.extensions_by_name['repeated_message_extension']
_TOPLEVELMESSAGE = DESCRIPTOR.message_types_by_name['TopLevelMessage']
_NESTEDMESSAGE = DESCRIPTOR.message_types_by_name['NestedMessage']
_EXTENDEDMESSAGE = DESCRIPTOR.message_types_by_name['ExtendedMessage']
_FOREIGNMESSAGE = DESCRIPTOR.message_types_by_name['ForeignMessage']
TopLevelMessage = _reflection.GeneratedProtocolMessageType('TopLevelMessage', (_message.Message,), {
'DESCRIPTOR' : _TOPLEVELMESSAGE,
'__module__' : 'google.protobuf.internal.more_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.TopLevelMessage)
})
_sym_db.RegisterMessage(TopLevelMessage)
NestedMessage = _reflection.GeneratedProtocolMessageType('NestedMessage', (_message.Message,), {
'DESCRIPTOR' : _NESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.more_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.NestedMessage)
})
_sym_db.RegisterMessage(NestedMessage)
ExtendedMessage = _reflection.GeneratedProtocolMessageType('ExtendedMessage', (_message.Message,), {
'DESCRIPTOR' : _EXTENDEDMESSAGE,
'__module__' : 'google.protobuf.internal.more_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.ExtendedMessage)
})
_sym_db.RegisterMessage(ExtendedMessage)
ForeignMessage = _reflection.GeneratedProtocolMessageType('ForeignMessage', (_message.Message,), {
'DESCRIPTOR' : _FOREIGNMESSAGE,
'__module__' : 'google.protobuf.internal.more_extensions_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.internal.ForeignMessage)
})
_sym_db.RegisterMessage(ForeignMessage)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.more_extensions_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
ExtendedMessage.RegisterExtension(optional_int_extension)
ExtendedMessage.RegisterExtension(optional_message_extension)
File diff suppressed because it is too large. Load diff
@@ -2,11 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/no_package.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -17,20 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n)google/protobuf/internal/no_package.proto\";\n\x10NoPackageMessage\x12\'\n\x0fno_package_enum\x18\x01 \x01(\x0e\x32\x0e.NoPackageEnum*?\n\rNoPackageEnum\x12\x16\n\x12NO_PACKAGE_VALUE_0\x10\x00\x12\x16\n\x12NO_PACKAGE_VALUE_1\x10\x01')
_NOPACKAGEENUM = DESCRIPTOR.enum_types_by_name['NoPackageEnum']
NoPackageEnum = enum_type_wrapper.EnumTypeWrapper(_NOPACKAGEENUM)
NO_PACKAGE_VALUE_0 = 0
NO_PACKAGE_VALUE_1 = 1
_NOPACKAGEMESSAGE = DESCRIPTOR.message_types_by_name['NoPackageMessage']
NoPackageMessage = _reflection.GeneratedProtocolMessageType('NoPackageMessage', (_message.Message,), {
'DESCRIPTOR' : _NOPACKAGEMESSAGE,
'__module__' : 'google.protobuf.internal.no_package_pb2'
# @@protoc_insertion_point(class_scope:NoPackageMessage)
})
_sym_db.RegisterMessage(NoPackageMessage)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.no_package_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/packed_field_test.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,25 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n0google/protobuf/internal/packed_field_test.proto\x12\x1fgoogle.protobuf.python.internal\"\xdb\x03\n\x0fTestPackedTypes\x12\x16\n\x0erepeated_int32\x18\x01 \x03(\x05\x12\x16\n\x0erepeated_int64\x18\x02 \x03(\x03\x12\x17\n\x0frepeated_uint32\x18\x03 \x03(\r\x12\x17\n\x0frepeated_uint64\x18\x04 \x03(\x04\x12\x17\n\x0frepeated_sint32\x18\x05 \x03(\x11\x12\x17\n\x0frepeated_sint64\x18\x06 \x03(\x12\x12\x18\n\x10repeated_fixed32\x18\x07 \x03(\x07\x12\x18\n\x10repeated_fixed64\x18\x08 \x03(\x06\x12\x19\n\x11repeated_sfixed32\x18\t \x03(\x0f\x12\x19\n\x11repeated_sfixed64\x18\n \x03(\x10\x12\x16\n\x0erepeated_float\x18\x0b \x03(\x02\x12\x17\n\x0frepeated_double\x18\x0c \x03(\x01\x12\x15\n\rrepeated_bool\x18\r \x03(\x08\x12Y\n\x14repeated_nested_enum\x18\x0e \x03(\x0e\x32;.google.protobuf.python.internal.TestPackedTypes.NestedEnum\"\'\n\nNestedEnum\x12\x07\n\x03\x46OO\x10\x00\x12\x07\n\x03\x42\x41R\x10\x01\x12\x07\n\x03\x42\x41Z\x10\x02\"\xec\x03\n\x11TestUnpackedTypes\x12\x1a\n\x0erepeated_int32\x18\x01 \x03(\x05\x42\x02\x10\x00\x12\x1a\n\x0erepeated_int64\x18\x02 \x03(\x03\x42\x02\x10\x00\x12\x1b\n\x0frepeated_uint32\x18\x03 \x03(\rB\x02\x10\x00\x12\x1b\n\x0frepeated_uint64\x18\x04 \x03(\x04\x42\x02\x10\x00\x12\x1b\n\x0frepeated_sint32\x18\x05 \x03(\x11\x42\x02\x10\x00\x12\x1b\n\x0frepeated_sint64\x18\x06 \x03(\x12\x42\x02\x10\x00\x12\x1c\n\x10repeated_fixed32\x18\x07 \x03(\x07\x42\x02\x10\x00\x12\x1c\n\x10repeated_fixed64\x18\x08 \x03(\x06\x42\x02\x10\x00\x12\x1d\n\x11repeated_sfixed32\x18\t \x03(\x0f\x42\x02\x10\x00\x12\x1d\n\x11repeated_sfixed64\x18\n \x03(\x10\x42\x02\x10\x00\x12\x1a\n\x0erepeated_float\x18\x0b \x03(\x02\x42\x02\x10\x00\x12\x1b\n\x0frepeated_double\x18\x0c \x03(\x01\x42\x02\x10\x00\x12\x19\n\rrepeated_bool\x18\r \x03(\x08\x42\x02\x10\x00\x12]\n\x14repeated_nested_enum\x18\x0e \x03(\x0e\x32;.google.protobuf.python.internal.TestPackedTypes.NestedEnumB\x02\x10\x00\x62\x06proto3')
_TESTPACKEDTYPES = DESCRIPTOR.message_types_by_name['TestPackedTypes']
_TESTUNPACKEDTYPES = DESCRIPTOR.message_types_by_name['TestUnpackedTypes']
_TESTPACKEDTYPES_NESTEDENUM = _TESTPACKEDTYPES.enum_types_by_name['NestedEnum']
TestPackedTypes = _reflection.GeneratedProtocolMessageType('TestPackedTypes', (_message.Message,), {
'DESCRIPTOR' : _TESTPACKEDTYPES,
'__module__' : 'google.protobuf.internal.packed_field_test_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestPackedTypes)
})
_sym_db.RegisterMessage(TestPackedTypes)
TestUnpackedTypes = _reflection.GeneratedProtocolMessageType('TestUnpackedTypes', (_message.Message,), {
'DESCRIPTOR' : _TESTUNPACKEDTYPES,
'__module__' : 'google.protobuf.internal.packed_field_test_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestUnpackedTypes)
})
_sym_db.RegisterMessage(TestUnpackedTypes)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.packed_field_test_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -31,10 +31,7 @@
"""Tests for google.protobuf.proto_builder."""
import collections
try:
import unittest2 as unittest
except ImportError:
import unittest
import unittest
from google.protobuf import descriptor_pb2 # pylint: disable=g-import-not-at-top
from google.protobuf import descriptor
@@ -1479,7 +1479,7 @@ class _Listener(object):
In order to support semantics like:
foo.bar.baz.qux = 23
foo.bar.baz.moo = 23
assert foo.HasField('bar')
...child objects must have back references to their parents.
@@ -36,8 +36,12 @@ namespace google {
namespace protobuf {
namespace python {
static const Message* GetCProtoInsidePyProtoStub(PyObject* msg) { return NULL; }
static Message* MutableCProtoInsidePyProtoStub(PyObject* msg) { return NULL; }
static const Message* GetCProtoInsidePyProtoStub(PyObject* msg) {
return nullptr;
}
static Message* MutableCProtoInsidePyProtoStub(PyObject* msg) {
return nullptr;
}
// This is initialized with a default, stub implementation.
// If python-google.protobuf.cc is loaded, the function pointer is overridden
@@ -37,6 +37,7 @@ import copy
import gc
import operator
import struct
import sys
import warnings
import unittest
@@ -376,7 +377,8 @@ class ReflectionTest(unittest.TestCase):
self.assertRaises(TypeError, setattr, proto, 'optional_float', 'foo')
self.assertRaises(TypeError, setattr, proto, 'optional_double', 'foo')
# TODO(jieluo): Fix type checking difference for python and c extension
if api_implementation.Type() == 'python':
if (api_implementation.Type() == 'python' or
(sys.version_info.major, sys.version_info.minor) >= (3, 10)):
self.assertRaises(TypeError, setattr, proto, 'optional_bool', 1.1)
else:
proto.optional_bool = 1.1
@@ -427,7 +429,7 @@ class ReflectionTest(unittest.TestCase):
pb.optional_uint64 = '2'
# The exact error should propagate with a poorly written custom integer.
with self.assertRaisesRegexp(RuntimeError, 'my_error'):
with self.assertRaisesRegex(RuntimeError, 'my_error'):
pb.optional_uint64 = test_util.NonStandardInteger(5, 'my_error')
def assetIntegerBoundsChecking(self, integer_fn, message_module):
@@ -1931,17 +1933,17 @@ class Proto2ReflectionTest(unittest.TestCase):
def testDisconnectingInOneof(self):
m = unittest_pb2.TestOneof2() # This message has two messages in a oneof.
m.foo_message.qux_int = 5
m.foo_message.moo_int = 5
sub_message = m.foo_message
# Accessing another message's field does not clear the first one
self.assertEqual(m.foo_lazy_message.qux_int, 0)
self.assertEqual(m.foo_message.qux_int, 5)
self.assertEqual(m.foo_lazy_message.moo_int, 0)
self.assertEqual(m.foo_message.moo_int, 5)
# But mutating another message in the oneof detaches the first one.
m.foo_lazy_message.qux_int = 6
self.assertEqual(m.foo_message.qux_int, 0)
m.foo_lazy_message.moo_int = 6
self.assertEqual(m.foo_message.moo_int, 0)
# The reference we got above was detached and is still valid.
self.assertEqual(sub_message.qux_int, 5)
sub_message.qux_int = 7
self.assertEqual(sub_message.moo_int, 5)
sub_message.moo_int = 7
def assertInitialized(self, proto):
self.assertTrue(proto.IsInitialized())
@@ -2018,7 +2020,7 @@ class Proto2ReflectionTest(unittest.TestCase):
self.assertRaises(TypeError, proto.IsInitialized, 1, 2, 3)
@unittest.skipIf(
api_implementation.Type() != 'cpp' or api_implementation.Version() != 2,
api_implementation.Type() == 'python',
'Errors are only available from the most recent C++ implementation.')
def testFileDescriptorErrors(self):
file_name = 'test_file_descriptor_errors.proto'
@@ -3223,7 +3225,7 @@ class OptionsTest(unittest.TestCase):
class ClassAPITest(unittest.TestCase):
@unittest.skipIf(
api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
api_implementation.Type() != 'python',
'C++ implementation requires a call to MakeDescriptor()')
@testing_refleaks.SkipReferenceLeakChecker('MakeClass is not repeatable')
def testMakeClassWithNestedDescriptor(self):
@@ -2,13 +2,10 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/test_bad_identifiers.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import service as _service
from google.protobuf import service_reflection
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
@@ -18,33 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n3google/protobuf/internal/test_bad_identifiers.proto\x12\x11protobuf_unittest\"\x1e\n\x12TestBadIdentifiers*\x08\x08\x64\x10\x80\x80\x80\x80\x02\"\x10\n\x0e\x41notherMessage2\x10\n\x0e\x41notherService:;\n\x07message\x12%.protobuf_unittest.TestBadIdentifiers\x18\x64 \x01(\t:\x03\x66oo:>\n\ndescriptor\x12%.protobuf_unittest.TestBadIdentifiers\x18\x65 \x01(\t:\x03\x62\x61r:>\n\nreflection\x12%.protobuf_unittest.TestBadIdentifiers\x18\x66 \x01(\t:\x03\x62\x61z:;\n\x07service\x12%.protobuf_unittest.TestBadIdentifiers\x18g \x01(\t:\x03quxB\x03\x90\x01\x01')
MESSAGE_FIELD_NUMBER = 100
message = DESCRIPTOR.extensions_by_name['message']
DESCRIPTOR_FIELD_NUMBER = 101
descriptor = DESCRIPTOR.extensions_by_name['descriptor']
REFLECTION_FIELD_NUMBER = 102
reflection = DESCRIPTOR.extensions_by_name['reflection']
SERVICE_FIELD_NUMBER = 103
service = DESCRIPTOR.extensions_by_name['service']
_TESTBADIDENTIFIERS = DESCRIPTOR.message_types_by_name['TestBadIdentifiers']
_ANOTHERMESSAGE = DESCRIPTOR.message_types_by_name['AnotherMessage']
TestBadIdentifiers = _reflection.GeneratedProtocolMessageType('TestBadIdentifiers', (_message.Message,), {
'DESCRIPTOR' : _TESTBADIDENTIFIERS,
'__module__' : 'google.protobuf.internal.test_bad_identifiers_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestBadIdentifiers)
})
_sym_db.RegisterMessage(TestBadIdentifiers)
AnotherMessage = _reflection.GeneratedProtocolMessageType('AnotherMessage', (_message.Message,), {
'DESCRIPTOR' : _ANOTHERMESSAGE,
'__module__' : 'google.protobuf.internal.test_bad_identifiers_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.AnotherMessage)
})
_sym_db.RegisterMessage(AnotherMessage)
_ANOTHERSERVICE = DESCRIPTOR.services_by_name['AnotherService']
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.test_bad_identifiers_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
TestBadIdentifiers.RegisterExtension(message)
TestBadIdentifiers.RegisterExtension(descriptor)
@@ -59,15 +31,5 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_ANOTHERMESSAGE._serialized_end=122
_ANOTHERSERVICE._serialized_start=124
_ANOTHERSERVICE._serialized_end=140
AnotherService = service_reflection.GeneratedServiceType('AnotherService', (_service.Service,), dict(
DESCRIPTOR = _ANOTHERSERVICE,
__module__ = 'google.protobuf.internal.test_bad_identifiers_pb2'
))
AnotherService_Stub = service_reflection.GeneratedServiceStubType('AnotherService_Stub', (AnotherService,), dict(
DESCRIPTOR = _ANOTHERSERVICE,
__module__ = 'google.protobuf.internal.test_bad_identifiers_pb2'
))
_builder.BuildServices(DESCRIPTOR, 'google.protobuf.internal.test_bad_identifiers_pb2', globals())
# @@protoc_insertion_point(module_scope)
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/test_proto3_optional.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,26 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n3google/protobuf/internal/test_proto3_optional.proto\x12\x1fgoogle.protobuf.python.internal\"\xf8\x08\n\x12TestProto3Optional\x12\x1b\n\x0eoptional_int32\x18\x01 \x01(\x05H\x00\x88\x01\x01\x12\x1b\n\x0eoptional_int64\x18\x02 \x01(\x03H\x01\x88\x01\x01\x12\x1c\n\x0foptional_uint32\x18\x03 \x01(\rH\x02\x88\x01\x01\x12\x1c\n\x0foptional_uint64\x18\x04 \x01(\x04H\x03\x88\x01\x01\x12\x1c\n\x0foptional_sint32\x18\x05 \x01(\x11H\x04\x88\x01\x01\x12\x1c\n\x0foptional_sint64\x18\x06 \x01(\x12H\x05\x88\x01\x01\x12\x1d\n\x10optional_fixed32\x18\x07 \x01(\x07H\x06\x88\x01\x01\x12\x1d\n\x10optional_fixed64\x18\x08 \x01(\x06H\x07\x88\x01\x01\x12\x1e\n\x11optional_sfixed32\x18\t \x01(\x0fH\x08\x88\x01\x01\x12\x1e\n\x11optional_sfixed64\x18\n \x01(\x10H\t\x88\x01\x01\x12\x1b\n\x0eoptional_float\x18\x0b \x01(\x02H\n\x88\x01\x01\x12\x1c\n\x0foptional_double\x18\x0c \x01(\x01H\x0b\x88\x01\x01\x12\x1a\n\roptional_bool\x18\r \x01(\x08H\x0c\x88\x01\x01\x12\x1c\n\x0foptional_string\x18\x0e \x01(\tH\r\x88\x01\x01\x12\x1b\n\x0eoptional_bytes\x18\x0f \x01(\x0cH\x0e\x88\x01\x01\x12g\n\x17optional_nested_message\x18\x12 \x01(\x0b\x32\x41.google.protobuf.python.internal.TestProto3Optional.NestedMessageH\x0f\x88\x01\x01\x12\x61\n\x14optional_nested_enum\x18\x15 \x01(\x0e\x32>.google.protobuf.python.internal.TestProto3Optional.NestedEnumH\x10\x88\x01\x01\x1a\'\n\rNestedMessage\x12\x0f\n\x02\x62\x62\x18\x01 \x01(\x05H\x00\x88\x01\x01\x42\x05\n\x03_bb\"J\n\nNestedEnum\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x07\n\x03\x46OO\x10\x01\x12\x07\n\x03\x42\x41R\x10\x02\x12\x07\n\x03\x42\x41Z\x10\x03\x12\x10\n\x03NEG\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x42\x11\n\x0f_optional_int32B\x11\n\x0f_optional_int64B\x12\n\x10_optional_uint32B\x12\n\x10_optional_uint64B\x12\n\x10_optional_sint32B\x12\n\x10_optional_sint64B\x13\n\x11_optional_fixed32B\x13\n\x11_optional_fixed64B\x14\n\x12_optional_sfixed32B\x14\n\x12_optional_sfixed64B\x11\n\x0f_optional_floatB\x12\n\x10_optional_doubleB\x10\n\x0e_optional_boolB\x12\n\x10_optional_stringB\x11\n\x0f_optional_bytesB\x1a\n\x18_optional_nested_messageB\x17\n\x15_optional_nested_enumb\x06proto3')
_TESTPROTO3OPTIONAL = DESCRIPTOR.message_types_by_name['TestProto3Optional']
_TESTPROTO3OPTIONAL_NESTEDMESSAGE = _TESTPROTO3OPTIONAL.nested_types_by_name['NestedMessage']
_TESTPROTO3OPTIONAL_NESTEDENUM = _TESTPROTO3OPTIONAL.enum_types_by_name['NestedEnum']
TestProto3Optional = _reflection.GeneratedProtocolMessageType('TestProto3Optional', (_message.Message,), {
'NestedMessage' : _reflection.GeneratedProtocolMessageType('NestedMessage', (_message.Message,), {
'DESCRIPTOR' : _TESTPROTO3OPTIONAL_NESTEDMESSAGE,
'__module__' : 'google.protobuf.internal.test_proto3_optional_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestProto3Optional.NestedMessage)
})
,
'DESCRIPTOR' : _TESTPROTO3OPTIONAL,
'__module__' : 'google.protobuf.internal.test_proto3_optional_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestProto3Optional)
})
_sym_db.RegisterMessage(TestProto3Optional)
_sym_db.RegisterMessage(TestProto3Optional.NestedMessage)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.internal.test_proto3_optional_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -218,6 +218,7 @@ def SetAllNonLazyFields(message):
def SetAllFields(message):
SetAllNonLazyFields(message)
message.optional_lazy_message.bb = 127
message.optional_unverified_lazy_message.bb = 128
def SetAllExtensions(message):
@@ -257,6 +258,7 @@ def SetAllExtensions(message):
extensions[pb2.optional_import_message_extension].d = 120
extensions[pb2.optional_public_import_message_extension].e = 126
extensions[pb2.optional_lazy_message_extension].bb = 127
extensions[pb2.optional_unverified_lazy_message_extension].bb = 128
extensions[pb2.optional_nested_enum_extension] = pb2.TestAllTypes.BAZ
extensions[pb2.optional_nested_enum_extension] = pb2.TestAllTypes.BAZ
@@ -465,6 +467,7 @@ def ExpectAllFieldsSet(test_case, message):
test_case.assertEqual(120, message.optional_import_message.d)
test_case.assertEqual(126, message.optional_public_import_message.e)
test_case.assertEqual(127, message.optional_lazy_message.bb)
test_case.assertEqual(128, message.optional_unverified_lazy_message.bb)
test_case.assertEqual(unittest_pb2.TestAllTypes.BAZ,
message.optional_nested_enum)
@@ -634,6 +637,13 @@ def GoldenFile(filename):
# Found it. Load the golden file from the testdata directory.
return open(full_path, 'rb')
# Search for cross-repo path.
full_path = os.path.join('external/com_google_protobuf/src/google/protobuf/testdata',
filename)
if os.path.exists(full_path):
# Found it. Load the golden file from the testdata directory.
return open(full_path, 'rb')
raise RuntimeError(
'Could not find golden files. This test must be run from within the '
'protobuf source package so that it can read test data files from the '
@@ -67,6 +67,12 @@ class ReferenceLeakCheckerMixin(object):
NB_RUNS = 3
def run(self, result=None):
testMethod = getattr(self, self._testMethodName)
expecting_failure_method = getattr(testMethod, "__unittest_expecting_failure__", False)
expecting_failure_class = getattr(self, "__unittest_expecting_failure__", False)
if expecting_failure_class or expecting_failure_method:
return
# python_message.py registers all Message classes to some pickle global
# registry, which makes the classes immortal.
# We save a copy of this registry, and reset it before we could references.
@@ -78,12 +84,23 @@ class ReferenceLeakCheckerMixin(object):
oldrefcount = 0
local_result = LocalTestResult(result)
num_flakes = 0
refcount_deltas = []
for _ in range(self.NB_RUNS):
while len(refcount_deltas) < self.NB_RUNS:
oldrefcount = self._getRefcounts()
super(ReferenceLeakCheckerMixin, self).run(result=local_result)
newrefcount = self._getRefcounts()
# If the GC was able to collect some objects after the call to run() that
# it could not collect before the call, then the counts won't match.
if newrefcount < oldrefcount and num_flakes < 2:
# This result is (probably) a flake -- garbage collectors aren't very
# predictable, but a lower ending refcount is the opposite of the
# failure we are testing for. If the result is repeatable, then we will
# eventually report it, but not after trying to eliminate it.
num_flakes += 1
continue
num_flakes = 0
refcount_deltas.append(newrefcount - oldrefcount)
print(refcount_deltas, self)
@@ -40,6 +40,7 @@ import textwrap
import unittest
from google.protobuf import any_pb2
from google.protobuf import struct_pb2
from google.protobuf import any_test_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_custom_options_pb2
@@ -48,6 +49,7 @@ from google.protobuf import unittest_pb2
from google.protobuf import unittest_proto3_arena_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import any_test_pb2 as test_extend_any
from google.protobuf.internal import api_implementation
from google.protobuf.internal import message_set_extensions_pb2
from google.protobuf.internal import test_proto3_optional_pb2
from google.protobuf.internal import test_util
@@ -582,6 +584,10 @@ class TextFormatMessageToStringTests(TextFormatBase):
text_format.Parse(expected_text, parsed_proto)
self.assertEqual(message_proto, parsed_proto)
@unittest.skipIf(
api_implementation.Type() == 'upb',
"upb API doesn't support old UnknownField API. The TextFormat library "
"needs to convert to the new API.")
def testPrintUnknownFieldsEmbeddedMessageInBytes(self, message_module):
inner_msg = message_module.TestAllTypes()
inner_msg.optional_int32 = 101
@@ -1470,9 +1476,11 @@ class Proto2Tests(TextFormatBase):
text = ('message_set {\n'
' [unknown_extension] {\n'
' i: 23\n'
' bin: "\xe0"'
' repeated_i: []\n'
' bin: "\xe0"\n'
' [nested_unknown_ext]: {\n'
' i: 23\n'
' repeated_i: [1, 2]\n'
' x: x\n'
' test: "test_string"\n'
' floaty_float: -0.315\n'
@@ -1485,6 +1493,7 @@ class Proto2Tests(TextFormatBase):
' i: 24\n'
' pointfloat: .3\n'
' test: "test_string"\n'
' repeated_test: ["test_string1", "test_string2"]\n'
' floaty_float: -0.315\n'
' num: -inf\n'
' long_string: "test" "test2" \n'
@@ -1931,6 +1940,16 @@ class Proto3Tests(unittest.TestCase):
text_format.Merge(text, message)
self.assertEqual(str(e.exception), '3:11 : Expected "}".')
def testParseExpandedAnyListValue(self):
any_msg = any_pb2.Any()
any_msg.Pack(struct_pb2.ListValue())
msg = any_test_pb2.TestAny(any_value=any_msg)
text = ('any_value {\n'
' [type.googleapis.com/google.protobuf.ListValue] {}\n'
'}\n')
parsed_msg = text_format.Parse(text, any_test_pb2.TestAny())
self.assertEqual(msg, parsed_msg)
def testProto3Optional(self):
msg = test_proto3_optional_pb2.TestProto3Optional()
self.assertEqual(text_format.MessageToString(msg), '')
@@ -48,7 +48,6 @@ __author__ = 'robinson@google.com (Will Robinson)'
import ctypes
import numbers
from google.protobuf.internal import api_implementation
from google.protobuf.internal import decoder
from google.protobuf.internal import encoder
from google.protobuf.internal import wire_format
@@ -77,7 +76,8 @@ def ToShortestFloat(original):
def SupportsOpenEnums(field_descriptor):
return field_descriptor.containing_type.syntax == "proto3"
return field_descriptor.containing_type.syntax == 'proto3'
def GetTypeChecker(field):
"""Returns a type checker for a message field of the specified types.
@@ -105,7 +105,6 @@ def GetTypeChecker(field):
# subclassing builtin types and doing weird things. We're not trying to
# protect against malicious clients here, just people accidentally shooting
# themselves in the foot in obvious ways.
class TypeChecker(object):
"""Type checker used to catch type errors as early as possible
@@ -124,11 +123,6 @@ class TypeChecker(object):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_value, type(proposed_value), self._acceptable_types))
raise TypeError(message)
# Some field types(float, double and bool) accept other types, must
# convert to the correct type in such cases.
if self._acceptable_types:
if self._acceptable_types[0] in (bool, float):
return self._acceptable_types[0](proposed_value)
return proposed_value
@@ -142,6 +136,22 @@ class TypeCheckerWithDefault(TypeChecker):
return self._default_value
class BoolValueChecker(object):
"""Type checker used for bool fields."""
def CheckValue(self, proposed_value):
if not hasattr(proposed_value, '__index__') or (
type(proposed_value).__module__ == 'numpy' and
type(proposed_value).__name__ == 'ndarray'):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_value, type(proposed_value), (bool, int)))
raise TypeError(message)
return bool(proposed_value)
def DefaultValue(self):
return False
# IntValueChecker and its subclasses perform integer type-checks
# and bounds-checks.
class IntValueChecker(object):
@@ -149,10 +159,13 @@ class IntValueChecker(object):
"""Checker used for integer fields. Performs type-check and range check."""
def CheckValue(self, proposed_value):
if not isinstance(proposed_value, numbers.Integral):
if not hasattr(proposed_value, '__index__') or (
type(proposed_value).__module__ == 'numpy' and
type(proposed_value).__name__ == 'ndarray'):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_value, type(proposed_value), (int,)))
raise TypeError(message)
if not self._MIN <= int(proposed_value) <= self._MAX:
raise ValueError('Value out of range: %d' % proposed_value)
# We force all values to int to make alternate implementations where the
@@ -249,20 +262,38 @@ _INF = float('inf')
_NEG_INF = float('-inf')
class FloatValueChecker(object):
class DoubleValueChecker(object):
"""Checker used for double fields.
"""Checker used for float fields. Performs type-check and range check.
Performs type-check and range check.
"""
def CheckValue(self, proposed_value):
"""Check and convert proposed_value to float."""
if (not hasattr(proposed_value, '__float__') and
not hasattr(proposed_value, '__index__')) or (
type(proposed_value).__module__ == 'numpy' and
type(proposed_value).__name__ == 'ndarray'):
message = ('%.1024r has type %s, but expected one of: int, float' %
(proposed_value, type(proposed_value)))
raise TypeError(message)
return float(proposed_value)
def DefaultValue(self):
return 0.0
class FloatValueChecker(DoubleValueChecker):
"""Checker used for float fields.
Performs type-check and range check.
Values exceeding a 32-bit float will be converted to inf/-inf.
"""
def CheckValue(self, proposed_value):
"""Check and convert proposed_value to float."""
if not isinstance(proposed_value, numbers.Real):
message = ('%.1024r has type %s, but expected one of: numbers.Real' %
(proposed_value, type(proposed_value)))
raise TypeError(message)
converted_value = float(proposed_value)
converted_value = super().CheckValue(proposed_value)
# This inf rounding matches the C++ proto SafeDoubleToFloat logic.
if converted_value > _FLOAT_MAX:
return _INF
@@ -271,23 +302,17 @@ class FloatValueChecker(object):
return TruncateToFourByteFloat(converted_value)
def DefaultValue(self):
return 0.0
# Type-checkers for all scalar CPPTYPEs.
_VALUE_CHECKERS = {
_FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(),
_FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(),
_FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(),
_FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(),
_FieldDescriptor.CPPTYPE_DOUBLE: TypeCheckerWithDefault(
0.0, float, numbers.Real),
_FieldDescriptor.CPPTYPE_DOUBLE: DoubleValueChecker(),
_FieldDescriptor.CPPTYPE_FLOAT: FloatValueChecker(),
_FieldDescriptor.CPPTYPE_BOOL: TypeCheckerWithDefault(
False, bool, numbers.Integral),
_FieldDescriptor.CPPTYPE_BOOL: BoolValueChecker(),
_FieldDescriptor.CPPTYPE_STRING: TypeCheckerWithDefault(b'', bytes),
}
}
# Map from field type to a function F, such that F(field_num, value)
@@ -49,7 +49,7 @@ from google.protobuf.internal import testing_refleaks
from google.protobuf.internal import type_checkers
from google.protobuf.internal import wire_format
from google.protobuf import descriptor
from google.protobuf import unknown_fields
try:
import tracemalloc # pylint: disable=g-import-not-at-top
except ImportError:
@@ -106,14 +106,14 @@ class UnknownFieldsTest(unittest.TestCase):
proto = message_set_extensions_pb2.TestMessageSet()
proto.MergeFromString(serialized)
unknown_fields = proto.UnknownFields()
self.assertEqual(len(unknown_fields), 1)
unknown_field_set = unknown_fields.UnknownFieldSet(proto)
self.assertEqual(len(unknown_field_set), 1)
# Unknown field should have wire format data which can be parsed back to
# original message.
self.assertEqual(unknown_fields[0].field_number, item.type_id)
self.assertEqual(unknown_fields[0].wire_type,
self.assertEqual(unknown_field_set[0].field_number, item.type_id)
self.assertEqual(unknown_field_set[0].wire_type,
wire_format.WIRETYPE_LENGTH_DELIMITED)
d = unknown_fields[0].data
d = unknown_field_set[0].data
message_new = message_set_extensions_pb2.TestMessageSetExtension1()
message_new.ParseFromString(d)
self.assertEqual(message1, message_new)
@@ -184,7 +184,7 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
# serialized string is checked.
# TODO(jieluo): Remove message._unknown_fields.
def InternalCheckUnknownField(self, name, expected_value):
if api_implementation.Type() == 'cpp':
if api_implementation.Type() != 'python':
return
field_descriptor = self.descriptor.fields_by_name[name]
wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type]
@@ -196,11 +196,11 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
decoder(memoryview(value), 0, len(value), self.all_fields, result_dict)
self.assertEqual(expected_value, result_dict[field_descriptor])
def CheckUnknownField(self, name, unknown_fields, expected_value):
def CheckUnknownField(self, name, unknown_field_set, expected_value):
field_descriptor = self.descriptor.fields_by_name[name]
expected_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[
field_descriptor.type]
for unknown_field in unknown_fields:
for unknown_field in unknown_field_set:
if unknown_field.field_number == field_descriptor.number:
self.assertEqual(expected_type, unknown_field.wire_type)
if expected_type == 3:
@@ -218,57 +218,57 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
self.assertEqual(expected_value, unknown_field.data)
def testCheckUnknownFieldValue(self):
unknown_fields = self.empty_message.UnknownFields()
unknown_field_set = unknown_fields.UnknownFieldSet(self.empty_message)
# Test enum.
self.CheckUnknownField('optional_nested_enum',
unknown_fields,
unknown_field_set,
self.all_fields.optional_nested_enum)
self.InternalCheckUnknownField('optional_nested_enum',
self.all_fields.optional_nested_enum)
# Test repeated enum.
self.CheckUnknownField('repeated_nested_enum',
unknown_fields,
unknown_field_set,
self.all_fields.repeated_nested_enum)
self.InternalCheckUnknownField('repeated_nested_enum',
self.all_fields.repeated_nested_enum)
# Test varint.
self.CheckUnknownField('optional_int32',
unknown_fields,
unknown_field_set,
self.all_fields.optional_int32)
self.InternalCheckUnknownField('optional_int32',
self.all_fields.optional_int32)
# Test fixed32.
self.CheckUnknownField('optional_fixed32',
unknown_fields,
unknown_field_set,
self.all_fields.optional_fixed32)
self.InternalCheckUnknownField('optional_fixed32',
self.all_fields.optional_fixed32)
# Test fixed64.
self.CheckUnknownField('optional_fixed64',
unknown_fields,
unknown_field_set,
self.all_fields.optional_fixed64)
self.InternalCheckUnknownField('optional_fixed64',
self.all_fields.optional_fixed64)
# Test length delimited.
self.CheckUnknownField('optional_string',
unknown_fields,
unknown_field_set,
self.all_fields.optional_string.encode('utf-8'))
self.InternalCheckUnknownField('optional_string',
self.all_fields.optional_string)
# Test group.
self.CheckUnknownField('optionalgroup',
unknown_fields,
unknown_field_set,
(17, 0, 117))
self.InternalCheckUnknownField('optionalgroup',
self.all_fields.optionalgroup)
self.assertEqual(97, len(unknown_fields))
self.assertEqual(98, len(unknown_field_set))
def testCopyFrom(self):
message = unittest_pb2.TestEmptyMessage()
@@ -286,18 +286,14 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
message.optional_int64 = 3
message.optional_uint32 = 4
destination = unittest_pb2.TestEmptyMessage()
unknown_fields = destination.UnknownFields()
self.assertEqual(0, len(unknown_fields))
unknown_field_set = unknown_fields.UnknownFieldSet(destination)
self.assertEqual(0, len(unknown_field_set))
destination.ParseFromString(message.SerializeToString())
# ParseFromString clears the message thus unknown fields is invalid.
with self.assertRaises(ValueError) as context:
len(unknown_fields)
self.assertIn('UnknownFields does not exist.',
str(context.exception))
unknown_fields = destination.UnknownFields()
self.assertEqual(2, len(unknown_fields))
self.assertEqual(0, len(unknown_field_set))
unknown_field_set = unknown_fields.UnknownFieldSet(destination)
self.assertEqual(2, len(unknown_field_set))
destination.MergeFrom(source)
self.assertEqual(4, len(unknown_fields))
self.assertEqual(2, len(unknown_field_set))
# Check that the fields where correctly merged, even stored in the unknown
# fields set.
message.ParseFromString(destination.SerializeToString())
@@ -306,14 +302,11 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
self.assertEqual(message.optional_int64, 3)
def testClear(self):
unknown_fields = self.empty_message.UnknownFields()
unknown_field_set = unknown_fields.UnknownFieldSet(self.empty_message)
self.empty_message.Clear()
# All cleared, even unknown fields.
self.assertEqual(self.empty_message.SerializeToString(), b'')
with self.assertRaises(ValueError) as context:
len(unknown_fields)
self.assertIn('UnknownFields does not exist.',
str(context.exception))
self.assertEqual(len(unknown_field_set), 98)
@unittest.skipIf((sys.version_info.major, sys.version_info.minor) < (3, 4),
'tracemalloc requires python 3.4+')
@@ -323,7 +316,7 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
def leaking_function():
for _ in range(nb_leaks):
self.empty_message.UnknownFields()
unknown_fields.UnknownFieldSet(self.empty_message)
tracemalloc.start()
snapshot1 = tracemalloc.take_snapshot()
@@ -340,49 +333,39 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
message.optionalgroup.a = 123
destination = unittest_pb2.TestEmptyMessage()
destination.ParseFromString(message.SerializeToString())
sub_unknown_fields = destination.UnknownFields()[0].data
sub_unknown_fields = unknown_fields.UnknownFieldSet(destination)[0].data
self.assertEqual(1, len(sub_unknown_fields))
self.assertEqual(sub_unknown_fields[0].data, 123)
destination.Clear()
with self.assertRaises(ValueError) as context:
len(sub_unknown_fields)
self.assertIn('UnknownFields does not exist.',
str(context.exception))
with self.assertRaises(ValueError) as context:
# pylint: disable=pointless-statement
sub_unknown_fields[0]
self.assertIn('UnknownFields does not exist.',
str(context.exception))
self.assertEqual(1, len(sub_unknown_fields))
self.assertEqual(sub_unknown_fields[0].data, 123)
message.Clear()
message.optional_uint32 = 456
nested_message = unittest_pb2.NestedTestAllTypes()
nested_message.payload.optional_nested_message.ParseFromString(
message.SerializeToString())
unknown_fields = (
nested_message.payload.optional_nested_message.UnknownFields())
self.assertEqual(unknown_fields[0].data, 456)
unknown_field_set = unknown_fields.UnknownFieldSet(
nested_message.payload.optional_nested_message)
self.assertEqual(unknown_field_set[0].data, 456)
nested_message.ClearField('payload')
self.assertEqual(unknown_fields[0].data, 456)
unknown_fields = (
nested_message.payload.optional_nested_message.UnknownFields())
self.assertEqual(0, len(unknown_fields))
self.assertEqual(unknown_field_set[0].data, 456)
unknown_field_set = unknown_fields.UnknownFieldSet(
nested_message.payload.optional_nested_message)
self.assertEqual(0, len(unknown_field_set))
def testUnknownField(self):
message = unittest_pb2.TestAllTypes()
message.optional_int32 = 123
destination = unittest_pb2.TestEmptyMessage()
destination.ParseFromString(message.SerializeToString())
unknown_field = destination.UnknownFields()[0]
unknown_field = unknown_fields.UnknownFieldSet(destination)[0]
destination.Clear()
with self.assertRaises(ValueError) as context:
unknown_field.data # pylint: disable=pointless-statement
self.assertIn('The parent message might be cleared.',
str(context.exception))
self.assertEqual(unknown_field.data, 123)
def testUnknownExtensions(self):
message = unittest_pb2.TestEmptyMessageWithExtensions()
message.ParseFromString(self.all_fields_data)
self.assertEqual(len(message.UnknownFields()), 97)
self.assertEqual(len(unknown_fields.UnknownFieldSet(message)), 98)
self.assertEqual(message.SerializeToString(), self.all_fields_data)
@@ -416,9 +399,10 @@ class UnknownEnumValuesTest(unittest.TestCase):
def CheckUnknownField(self, name, expected_value):
field_descriptor = self.descriptor.fields_by_name[name]
unknown_fields = self.missing_message.UnknownFields()
unknown_field_set = unknown_fields.UnknownFieldSet(self.missing_message)
self.assertIsInstance(unknown_field_set, unknown_fields.UnknownFieldSet)
count = 0
for field in unknown_fields:
for field in unknown_field_set:
if field.field_number == field_descriptor.number:
count += 1
if field_descriptor.label == descriptor.FieldDescriptor.LABEL_REPEATED:
@@ -458,8 +442,8 @@ class UnknownEnumValuesTest(unittest.TestCase):
self.assertEqual([], self.missing_message.packed_nested_enum)
def testCheckUnknownFieldValueForEnum(self):
unknown_fields = self.missing_message.UnknownFields()
self.assertEqual(len(unknown_fields), 5)
unknown_field_set = unknown_fields.UnknownFieldSet(self.missing_message)
self.assertEqual(len(unknown_field_set), 5)
self.CheckUnknownField('optional_nested_enum',
self.message.optional_nested_enum)
self.CheckUnknownField('repeated_nested_enum',
@@ -42,8 +42,7 @@ __author__ = 'jieluo@google.com (Jie Luo)'
import calendar
import collections.abc
from datetime import datetime
from datetime import timedelta
import datetime
from google.protobuf.descriptor import FieldDescriptor
@@ -89,7 +88,9 @@ class Any(object):
return '/' in self.type_url and self.TypeName() == descriptor.full_name
_EPOCH_DATETIME = datetime.utcfromtimestamp(0)
_EPOCH_DATETIME_NAIVE = datetime.datetime.utcfromtimestamp(0)
_EPOCH_DATETIME_AWARE = datetime.datetime.fromtimestamp(
0, tz=datetime.timezone.utc)
class Timestamp(object):
@@ -109,7 +110,7 @@ class Timestamp(object):
total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND
seconds = total_sec % _SECONDS_PER_DAY
days = (total_sec - seconds) // _SECONDS_PER_DAY
dt = datetime(1970, 1, 1) + timedelta(days, seconds)
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(days, seconds)
result = dt.isoformat()
if (nanos % 1e9) == 0:
@@ -159,8 +160,8 @@ class Timestamp(object):
raise ValueError(
'time data \'{0}\' does not match format \'%Y-%m-%dT%H:%M:%S\', '
'lowercase \'t\' is not accepted'.format(second_value))
date_object = datetime.strptime(second_value, _TIMESTAMPFOMAT)
td = date_object - datetime(1970, 1, 1)
date_object = datetime.datetime.strptime(second_value, _TIMESTAMPFOMAT)
td = date_object - datetime.datetime(1970, 1, 1)
seconds = td.seconds + td.days * _SECONDS_PER_DAY
if len(nano_value) > 9:
raise ValueError(
@@ -191,7 +192,7 @@ class Timestamp(object):
def GetCurrentTime(self):
"""Get the current UTC into Timestamp."""
self.FromDatetime(datetime.utcnow())
self.FromDatetime(datetime.datetime.utcnow())
def ToNanoseconds(self):
"""Converts Timestamp to nanoseconds since epoch."""
@@ -231,14 +232,32 @@ class Timestamp(object):
self.seconds = seconds
self.nanos = 0
def ToDatetime(self):
"""Converts Timestamp to datetime."""
return _EPOCH_DATETIME + timedelta(
seconds=self.seconds, microseconds=_RoundTowardZero(
self.nanos, _NANOS_PER_MICROSECOND))
def ToDatetime(self, tzinfo=None):
"""Converts Timestamp to a datetime.
Args:
tzinfo: A datetime.tzinfo subclass; defaults to None.
Returns:
If tzinfo is None, returns a timezone-naive UTC datetime (with no timezone
information, i.e. not aware that it's UTC).
Otherwise, returns a timezone-aware datetime in the input timezone.
"""
delta = datetime.timedelta(
seconds=self.seconds,
microseconds=_RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND))
if tzinfo is None:
return _EPOCH_DATETIME_NAIVE + delta
else:
return _EPOCH_DATETIME_AWARE.astimezone(tzinfo) + delta
def FromDatetime(self, dt):
"""Converts datetime to Timestamp."""
"""Converts datetime to Timestamp.
Args:
dt: A datetime. If it's timezone-naive, it's assumed to be in UTC.
"""
# Using this guide: http://wiki.python.org/moin/WorkingWithTime
# And this conversion guide: http://docs.python.org/library/time.html
@@ -363,7 +382,7 @@ class Duration(object):
def ToTimedelta(self):
"""Converts Duration to timedelta."""
return timedelta(
return datetime.timedelta(
seconds=self.seconds, microseconds=_RoundTowardZero(
self.nanos, _NANOS_PER_MICROSECOND))
@@ -849,6 +868,7 @@ class ListValue(object):
collections.abc.MutableSequence.register(ListValue)
# LINT.IfChange(wktbases)
WKTBASES = {
'google.protobuf.Any': Any,
'google.protobuf.Duration': Duration,
@@ -857,3 +877,4 @@ WKTBASES = {
'google.protobuf.Struct': Struct,
'google.protobuf.Timestamp': Timestamp,
}
# LINT.ThenChange(//depot/google.protobuf/compiler/python/pyi_generator.cc:wktbases)
@@ -48,9 +48,19 @@ from google.protobuf.internal import test_util
from google.protobuf.internal import well_known_types
from google.protobuf import descriptor
from google.protobuf import text_format
from google.protobuf.internal import _parameterized
try:
# New module in Python 3.9:
import zoneinfo # pylint:disable=g-import-not-at-top
_TZ_JAPAN = zoneinfo.ZoneInfo('Japan')
_TZ_PACIFIC = zoneinfo.ZoneInfo('US/Pacific')
except ImportError:
_TZ_JAPAN = datetime.timezone(datetime.timedelta(hours=9), 'Japan')
_TZ_PACIFIC = datetime.timezone(datetime.timedelta(hours=-8), 'US/Pacific')
class TimeUtilTestBase(unittest.TestCase):
class TimeUtilTestBase(_parameterized.TestCase):
def CheckTimestampConversion(self, message, text):
self.assertEqual(text, message.ToJsonString())
@@ -233,43 +243,68 @@ class TimeUtilTest(TimeUtilTestBase):
message.FromNanoseconds(-1999)
self.assertEqual(-1, message.ToMicroseconds())
def testDatetimeConverison(self):
def testTimezoneNaiveDatetimeConversion(self):
message = timestamp_pb2.Timestamp()
dt = datetime.datetime(1970, 1, 1)
message.FromDatetime(dt)
self.assertEqual(dt, message.ToDatetime())
naive_utc_epoch = datetime.datetime(1970, 1, 1)
message.FromDatetime(naive_utc_epoch)
self.assertEqual(0, message.seconds)
self.assertEqual(0, message.nanos)
self.assertEqual(naive_utc_epoch, message.ToDatetime())
naive_epoch_morning = datetime.datetime(1970, 1, 1, 8, 0, 0, 1)
message.FromDatetime(naive_epoch_morning)
self.assertEqual(8 * 3600, message.seconds)
self.assertEqual(1000, message.nanos)
self.assertEqual(naive_epoch_morning, message.ToDatetime())
message.FromMilliseconds(1999)
self.assertEqual(1, message.seconds)
self.assertEqual(999_000_000, message.nanos)
self.assertEqual(datetime.datetime(1970, 1, 1, 0, 0, 1, 999000),
message.ToDatetime())
dt = datetime.datetime(2555, 2, 22, 1, 2, 3, 456789)
message.FromDatetime(dt)
self.assertEqual(dt, message.ToDatetime())
naive_future = datetime.datetime(2555, 2, 22, 1, 2, 3, 456789)
message.FromDatetime(naive_future)
self.assertEqual(naive_future, message.ToDatetime())
dt = datetime.datetime.max
message.FromDatetime(dt)
self.assertEqual(dt, message.ToDatetime())
naive_end_of_time = datetime.datetime.max
message.FromDatetime(naive_end_of_time)
self.assertEqual(naive_end_of_time, message.ToDatetime())
def testDatetimeConversionWithTimezone(self):
class TZ(datetime.tzinfo):
# Two hours after the Unix Epoch, around the world.
@_parameterized.named_parameters(
('London', [1970, 1, 1, 2], datetime.timezone.utc),
('Tokyo', [1970, 1, 1, 11], _TZ_JAPAN),
('LA', [1969, 12, 31, 18], _TZ_PACIFIC),
)
def testTimezoneAwareDatetimeConversion(self, date_parts, tzinfo):
original_datetime = datetime.datetime(*date_parts, tzinfo=tzinfo) # pylint:disable=g-tzinfo-datetime
def utcoffset(self, _):
return datetime.timedelta(hours=1)
message = timestamp_pb2.Timestamp()
message.FromDatetime(original_datetime)
self.assertEqual(7200, message.seconds)
self.assertEqual(0, message.nanos)
def dst(self, _):
return datetime.timedelta(0)
# ToDatetime() with no parameters produces a naive UTC datetime, i.e. it not
# only loses the original timezone information (e.g. US/Pacific) as it's
# "normalised" to UTC, but also drops the information that the datetime
# represents a UTC one.
naive_datetime = message.ToDatetime()
self.assertEqual(datetime.datetime(1970, 1, 1, 2), naive_datetime)
self.assertIsNone(naive_datetime.tzinfo)
self.assertNotEqual(original_datetime, naive_datetime) # not even for UTC!
def tzname(self, _):
return 'UTC+1'
message1 = timestamp_pb2.Timestamp()
dt = datetime.datetime(1970, 1, 1, 1, tzinfo=TZ())
message1.FromDatetime(dt)
message2 = timestamp_pb2.Timestamp()
dt = datetime.datetime(1970, 1, 1, 0)
message2.FromDatetime(dt)
self.assertEqual(message1, message2)
# In contrast, ToDatetime(tzinfo=) produces an aware datetime in the given
# timezone.
aware_datetime = message.ToDatetime(tzinfo=tzinfo)
self.assertEqual(original_datetime, aware_datetime)
self.assertEqual(
datetime.datetime(1970, 1, 1, 2, tzinfo=datetime.timezone.utc),
aware_datetime)
self.assertEqual(tzinfo, aware_datetime.tzinfo)
def testTimedeltaConversion(self):
message = duration_pb2.Duration()
@@ -295,85 +330,64 @@ class TimeUtilTest(TimeUtilTestBase):
def testInvalidTimestamp(self):
message = timestamp_pb2.Timestamp()
self.assertRaisesRegexp(
ValueError,
'Failed to parse timestamp: missing valid timezone offset.',
message.FromJsonString,
'')
self.assertRaisesRegexp(
ValueError,
'Failed to parse timestamp: invalid trailing data '
'1970-01-01T00:00:01Ztrail.',
message.FromJsonString,
self.assertRaisesRegex(
ValueError, 'Failed to parse timestamp: missing valid timezone offset.',
message.FromJsonString, '')
self.assertRaisesRegex(
ValueError, 'Failed to parse timestamp: invalid trailing data '
'1970-01-01T00:00:01Ztrail.', message.FromJsonString,
'1970-01-01T00:00:01Ztrail')
self.assertRaisesRegexp(
ValueError,
'time data \'10000-01-01T00:00:00\' does not match'
' format \'%Y-%m-%dT%H:%M:%S\'',
message.FromJsonString, '10000-01-01T00:00:00.00Z')
self.assertRaisesRegexp(
ValueError,
'nanos 0123456789012 more than 9 fractional digits.',
message.FromJsonString,
'1970-01-01T00:00:00.0123456789012Z')
self.assertRaisesRegexp(
self.assertRaisesRegex(
ValueError, 'time data \'10000-01-01T00:00:00\' does not match'
' format \'%Y-%m-%dT%H:%M:%S\'', message.FromJsonString,
'10000-01-01T00:00:00.00Z')
self.assertRaisesRegex(
ValueError, 'nanos 0123456789012 more than 9 fractional digits.',
message.FromJsonString, '1970-01-01T00:00:00.0123456789012Z')
self.assertRaisesRegex(
ValueError,
(r'Invalid timezone offset value: \+08.'),
message.FromJsonString,
'1972-01-01T01:00:00.01+08',)
self.assertRaisesRegexp(
ValueError,
'year (0 )?is out of range',
message.FromJsonString,
'0000-01-01T00:00:00Z')
'1972-01-01T01:00:00.01+08',
)
self.assertRaisesRegex(ValueError, 'year (0 )?is out of range',
message.FromJsonString, '0000-01-01T00:00:00Z')
message.seconds = 253402300800
self.assertRaisesRegexp(
OverflowError,
'date value out of range',
message.ToJsonString)
self.assertRaisesRegex(OverflowError, 'date value out of range',
message.ToJsonString)
def testInvalidDuration(self):
message = duration_pb2.Duration()
self.assertRaisesRegexp(
ValueError,
'Duration must end with letter "s": 1.',
message.FromJsonString, '1')
self.assertRaisesRegexp(
ValueError,
'Couldn\'t parse duration: 1...2s.',
message.FromJsonString, '1...2s')
self.assertRaisesRegex(ValueError, 'Duration must end with letter "s": 1.',
message.FromJsonString, '1')
self.assertRaisesRegex(ValueError, 'Couldn\'t parse duration: 1...2s.',
message.FromJsonString, '1...2s')
text = '-315576000001.000000000s'
self.assertRaisesRegexp(
self.assertRaisesRegex(
ValueError,
r'Duration is not valid\: Seconds -315576000001 must be in range'
r' \[-315576000000\, 315576000000\].',
message.FromJsonString, text)
r' \[-315576000000\, 315576000000\].', message.FromJsonString, text)
text = '315576000001.000000000s'
self.assertRaisesRegexp(
self.assertRaisesRegex(
ValueError,
r'Duration is not valid\: Seconds 315576000001 must be in range'
r' \[-315576000000\, 315576000000\].',
message.FromJsonString, text)
r' \[-315576000000\, 315576000000\].', message.FromJsonString, text)
message.seconds = -315576000001
message.nanos = 0
self.assertRaisesRegexp(
self.assertRaisesRegex(
ValueError,
r'Duration is not valid\: Seconds -315576000001 must be in range'
r' \[-315576000000\, 315576000000\].',
message.ToJsonString)
r' \[-315576000000\, 315576000000\].', message.ToJsonString)
message.seconds = 0
message.nanos = 999999999 + 1
self.assertRaisesRegexp(
ValueError,
r'Duration is not valid\: Nanos 1000000000 must be in range'
r' \[-999999999\, 999999999\].',
message.ToJsonString)
self.assertRaisesRegex(
ValueError, r'Duration is not valid\: Nanos 1000000000 must be in range'
r' \[-999999999\, 999999999\].', message.ToJsonString)
message.seconds = -1
message.nanos = 1
self.assertRaisesRegexp(
ValueError,
r'Duration is not valid\: Sign mismatch.',
message.ToJsonString)
self.assertRaisesRegex(ValueError,
r'Duration is not valid\: Sign mismatch.',
message.ToJsonString)
class FieldMaskTest(unittest.TestCase):
@@ -412,7 +426,7 @@ class FieldMaskTest(unittest.TestCase):
mask = field_mask_pb2.FieldMask()
msg_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
mask.AllFieldsFromDescriptor(msg_descriptor)
self.assertEqual(75, len(mask.paths))
self.assertEqual(76, len(mask.paths))
self.assertTrue(mask.IsValidForDescriptor(msg_descriptor))
for field in msg_descriptor.fields:
self.assertTrue(field.name in mask.paths)
@@ -643,9 +657,9 @@ class FieldMaskTest(unittest.TestCase):
# Test Merge oneof field.
new_msg = unittest_pb2.TestOneof2()
dst = unittest_pb2.TestOneof2()
dst.foo_message.qux_int = 1
dst.foo_message.moo_int = 1
mask = field_mask_pb2.FieldMask()
mask.FromJsonString('fooMessage,fooLazyMessage.quxInt')
mask.FromJsonString('fooMessage,fooLazyMessage.mooInt')
mask.MergeMessage(new_msg, dst)
self.assertTrue(dst.HasField('foo_message'))
self.assertFalse(dst.HasField('foo_lazy_message'))
@@ -695,34 +709,29 @@ class FieldMaskTest(unittest.TestCase):
well_known_types._SnakeCaseToCamelCase('foo3_bar'))
# No uppercase letter is allowed.
self.assertRaisesRegexp(
self.assertRaisesRegex(
ValueError,
'Fail to print FieldMask to Json string: Path name Foo must '
'not contain uppercase letters.',
well_known_types._SnakeCaseToCamelCase,
'Foo')
well_known_types._SnakeCaseToCamelCase, 'Foo')
# Any character after a "_" must be a lowercase letter.
# 1. "_" cannot be followed by another "_".
# 2. "_" cannot be followed by a digit.
# 3. "_" cannot appear as the last character.
self.assertRaisesRegexp(
self.assertRaisesRegex(
ValueError,
'Fail to print FieldMask to Json string: The character after a '
'"_" must be a lowercase letter in path name foo__bar.',
well_known_types._SnakeCaseToCamelCase,
'foo__bar')
self.assertRaisesRegexp(
well_known_types._SnakeCaseToCamelCase, 'foo__bar')
self.assertRaisesRegex(
ValueError,
'Fail to print FieldMask to Json string: The character after a '
'"_" must be a lowercase letter in path name foo_3bar.',
well_known_types._SnakeCaseToCamelCase,
'foo_3bar')
self.assertRaisesRegexp(
well_known_types._SnakeCaseToCamelCase, 'foo_3bar')
self.assertRaisesRegex(
ValueError,
'Fail to print FieldMask to Json string: Trailing "_" in path '
'name foo_bar_.',
well_known_types._SnakeCaseToCamelCase,
'foo_bar_')
'name foo_bar_.', well_known_types._SnakeCaseToCamelCase, 'foo_bar_')
def testCamelCaseToSnakeCase(self):
self.assertEqual('foo_bar',
@@ -731,11 +740,10 @@ class FieldMaskTest(unittest.TestCase):
well_known_types._CamelCaseToSnakeCase('FooBar'))
self.assertEqual('foo3_bar',
well_known_types._CamelCaseToSnakeCase('foo3Bar'))
self.assertRaisesRegexp(
self.assertRaisesRegex(
ValueError,
'Fail to parse FieldMask: Path name foo_bar must not contain "_"s.',
well_known_types._CamelCaseToSnakeCase,
'foo_bar')
well_known_types._CamelCaseToSnakeCase, 'foo_bar')
class StructTest(unittest.TestCase):
+172 -116
View File
@@ -95,7 +95,8 @@ def MessageToJson(
sort_keys=False,
use_integers_for_enums=False,
descriptor_pool=None,
float_precision=None):
float_precision=None,
ensure_ascii=True):
"""Converts protobuf message to JSON format.
Args:
@@ -114,6 +115,8 @@ def MessageToJson(
descriptor_pool: A Descriptor Pool for resolving types. If None use the
default.
float_precision: If set, use this to specify float field valid digits.
ensure_ascii: If True, strings with non-ASCII characters are escaped.
If False, Unicode strings are returned unchanged.
Returns:
A string containing the JSON formatted protocol buffer message.
@@ -124,7 +127,7 @@ def MessageToJson(
use_integers_for_enums,
descriptor_pool,
float_precision=float_precision)
return printer.ToJsonString(message, indent, sort_keys)
return printer.ToJsonString(message, indent, sort_keys, ensure_ascii)
def MessageToDict(
@@ -190,9 +193,10 @@ class _Printer(object):
else:
self.float_format = None
def ToJsonString(self, message, indent, sort_keys):
def ToJsonString(self, message, indent, sort_keys, ensure_ascii):
js = self._MessageToJsonObject(message)
return json.dumps(js, indent=indent, sort_keys=sort_keys)
return json.dumps(
js, indent=indent, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
def _MessageToJsonObject(self, message):
"""Converts message to an object according to Proto3 JSON Specification."""
@@ -395,12 +399,16 @@ def _CreateMessageFromTypeUrl(type_url, descriptor_pool):
message_descriptor = pool.FindMessageTypeByName(type_name)
except KeyError:
raise TypeError(
'Can not find message descriptor by type_url: {0}.'.format(type_url))
'Can not find message descriptor by type_url: {0}'.format(type_url))
message_class = db.GetPrototype(message_descriptor)
return message_class()
def Parse(text, message, ignore_unknown_fields=False, descriptor_pool=None):
def Parse(text,
message,
ignore_unknown_fields=False,
descriptor_pool=None,
max_recursion_depth=100):
"""Parses a JSON representation of a protocol message into a message.
Args:
@@ -408,7 +416,10 @@ def Parse(text, message, ignore_unknown_fields=False, descriptor_pool=None):
message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors for unknown fields.
descriptor_pool: A Descriptor Pool for resolving types. If None use the
default.
default.
max_recursion_depth: max recursion depth of JSON message to be
deserialized. JSON messages over this depth will fail to be
deserialized. Default value is 100.
Returns:
The same message passed as argument.
@@ -422,13 +433,15 @@ def Parse(text, message, ignore_unknown_fields=False, descriptor_pool=None):
js = json.loads(text, object_pairs_hook=_DuplicateChecker)
except ValueError as e:
raise ParseError('Failed to load JSON: {0}.'.format(str(e)))
return ParseDict(js, message, ignore_unknown_fields, descriptor_pool)
return ParseDict(js, message, ignore_unknown_fields, descriptor_pool,
max_recursion_depth)
def ParseDict(js_dict,
message,
ignore_unknown_fields=False,
descriptor_pool=None):
descriptor_pool=None,
max_recursion_depth=100):
"""Parses a JSON dictionary representation into a message.
Args:
@@ -437,12 +450,15 @@ def ParseDict(js_dict,
ignore_unknown_fields: If True, do not raise errors for unknown fields.
descriptor_pool: A Descriptor Pool for resolving types. If None use the
default.
max_recursion_depth: max recursion depth of JSON message to be
deserialized. JSON messages over this depth will fail to be
deserialized. Default value is 100.
Returns:
The same message passed as argument.
"""
parser = _Parser(ignore_unknown_fields, descriptor_pool)
parser.ConvertMessage(js_dict, message)
parser = _Parser(ignore_unknown_fields, descriptor_pool, max_recursion_depth)
parser.ConvertMessage(js_dict, message, '')
return message
@@ -452,35 +468,47 @@ _INT_OR_FLOAT = (int, float)
class _Parser(object):
"""JSON format parser for protocol message."""
def __init__(self, ignore_unknown_fields, descriptor_pool):
def __init__(self, ignore_unknown_fields, descriptor_pool,
max_recursion_depth):
self.ignore_unknown_fields = ignore_unknown_fields
self.descriptor_pool = descriptor_pool
self.max_recursion_depth = max_recursion_depth
self.recursion_depth = 0
def ConvertMessage(self, value, message):
def ConvertMessage(self, value, message, path):
"""Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
path: parent path to log parse error info.
Raises:
ParseError: In case of convert problems.
"""
self.recursion_depth += 1
if self.recursion_depth > self.max_recursion_depth:
raise ParseError('Message too deep. Max recursion depth is {0}'.format(
self.max_recursion_depth))
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if not path:
path = message_descriptor.name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value, message)
self._ConvertWrapperMessage(value, message, path)
elif full_name in _WKTJSONMETHODS:
methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self)
methodcaller(_WKTJSONMETHODS[full_name][1], value, message, path)(self)
else:
self._ConvertFieldValuePair(value, message)
self._ConvertFieldValuePair(value, message, path)
self.recursion_depth -= 1
def _ConvertFieldValuePair(self, js, message):
def _ConvertFieldValuePair(self, js, message, path):
"""Convert field value pairs into regular message.
Args:
js: A JSON object to convert the field value pairs.
message: A regular protocol message to record the data.
path: parent path to log parse error info.
Raises:
ParseError: In case of problems converting.
@@ -496,8 +524,9 @@ class _Parser(object):
field = message_descriptor.fields_by_name.get(name, None)
if not field and _VALID_EXTENSION_NAME.match(name):
if not message_descriptor.is_extendable:
raise ParseError('Message type {0} does not have extensions'.format(
message_descriptor.full_name))
raise ParseError(
'Message type {0} does not have extensions at {1}'.format(
message_descriptor.full_name, path))
identifier = name[1:-1] # strip [] brackets
# pylint: disable=protected-access
field = message.Extensions._FindExtensionByName(identifier)
@@ -513,14 +542,14 @@ class _Parser(object):
if self.ignore_unknown_fields:
continue
raise ParseError(
('Message type "{0}" has no field named "{1}".\n'
' Available Fields(except extensions): {2}').format(
message_descriptor.full_name, name,
('Message type "{0}" has no field named "{1}" at "{2}".\n'
' Available Fields(except extensions): "{3}"').format(
message_descriptor.full_name, name, path,
[f.json_name for f in message_descriptor.fields]))
if name in names:
raise ParseError('Message type "{0}" should not have multiple '
'"{1}" fields.'.format(
message.DESCRIPTOR.full_name, name))
'"{1}" fields at "{2}".'.format(
message.DESCRIPTOR.full_name, name, path))
names.append(name)
value = js[name]
# Check no other oneof field is parsed.
@@ -528,8 +557,9 @@ class _Parser(object):
oneof_name = field.containing_oneof.name
if oneof_name in names:
raise ParseError('Message type "{0}" should not have multiple '
'"{1}" oneof fields.'.format(
message.DESCRIPTOR.full_name, oneof_name))
'"{1}" oneof fields at "{2}".'.format(
message.DESCRIPTOR.full_name, oneof_name,
path))
names.append(oneof_name)
if value is None:
@@ -547,42 +577,51 @@ class _Parser(object):
# Parse field value.
if _IsMapEntry(field):
message.ClearField(field.name)
self._ConvertMapFieldValue(value, message, field)
self._ConvertMapFieldValue(value, message, field,
'{0}.{1}'.format(path, name))
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
message.ClearField(field.name)
if not isinstance(value, list):
raise ParseError('repeated field {0} must be in [] which is '
'{1}.'.format(name, value))
'{1} at {2}'.format(name, value, path))
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
# Repeated message field.
for item in value:
for index, item in enumerate(value):
sub_message = getattr(message, field.name).add()
# None is a null_value in Value.
if (item is None and
sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'):
raise ParseError('null is not allowed to be used as an element'
' in a repeated field.')
self.ConvertMessage(item, sub_message)
' in a repeated field at {0}.{1}[{2}]'.format(
path, name, index))
self.ConvertMessage(item, sub_message,
'{0}.{1}[{2}]'.format(path, name, index))
else:
# Repeated scalar field.
for item in value:
for index, item in enumerate(value):
if item is None:
raise ParseError('null is not allowed to be used as an element'
' in a repeated field.')
' in a repeated field at {0}.{1}[{2}]'.format(
path, name, index))
getattr(message, field.name).append(
_ConvertScalarFieldValue(item, field))
_ConvertScalarFieldValue(
item, field, '{0}.{1}[{2}]'.format(path, name, index)))
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
if field.is_extension:
sub_message = message.Extensions[field]
else:
sub_message = getattr(message, field.name)
sub_message.SetInParent()
self.ConvertMessage(value, sub_message)
self.ConvertMessage(value, sub_message, '{0}.{1}'.format(path, name))
else:
if field.is_extension:
message.Extensions[field] = _ConvertScalarFieldValue(value, field)
message.Extensions[field] = _ConvertScalarFieldValue(
value, field, '{0}.{1}'.format(path, name))
else:
setattr(message, field.name, _ConvertScalarFieldValue(value, field))
setattr(
message, field.name,
_ConvertScalarFieldValue(value, field,
'{0}.{1}'.format(path, name)))
except ParseError as e:
if field and field.containing_oneof is None:
raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
@@ -593,46 +632,52 @@ class _Parser(object):
except TypeError as e:
raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
def _ConvertAnyMessage(self, value, message):
def _ConvertAnyMessage(self, value, message, path):
"""Convert a JSON representation into Any message."""
if isinstance(value, dict) and not value:
return
try:
type_url = value['@type']
except KeyError:
raise ParseError('@type is missing when parsing any message.')
raise ParseError(
'@type is missing when parsing any message at {0}'.format(path))
sub_message = _CreateMessageFromTypeUrl(type_url, self.descriptor_pool)
try:
sub_message = _CreateMessageFromTypeUrl(type_url, self.descriptor_pool)
except TypeError as e:
raise ParseError('{0} at {1}'.format(e, path))
message_descriptor = sub_message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value['value'], sub_message)
self._ConvertWrapperMessage(value['value'], sub_message,
'{0}.value'.format(path))
elif full_name in _WKTJSONMETHODS:
methodcaller(
_WKTJSONMETHODS[full_name][1], value['value'], sub_message)(self)
methodcaller(_WKTJSONMETHODS[full_name][1], value['value'], sub_message,
'{0}.value'.format(path))(
self)
else:
del value['@type']
self._ConvertFieldValuePair(value, sub_message)
self._ConvertFieldValuePair(value, sub_message, path)
value['@type'] = type_url
# Sets Any message
message.value = sub_message.SerializeToString()
message.type_url = type_url
def _ConvertGenericMessage(self, value, message):
def _ConvertGenericMessage(self, value, message, path):
"""Convert a JSON representation into message with FromJsonString."""
# Duration, Timestamp, FieldMask have a FromJsonString method to do the
# conversion. Users can also call the method directly.
try:
message.FromJsonString(value)
except ValueError as e:
raise ParseError(e)
raise ParseError('{0} at {1}'.format(e, path))
def _ConvertValueMessage(self, value, message):
def _ConvertValueMessage(self, value, message, path):
"""Convert a JSON representation into Value message."""
if isinstance(value, dict):
self._ConvertStructMessage(value, message.struct_value)
self._ConvertStructMessage(value, message.struct_value, path)
elif isinstance(value, list):
self. _ConvertListValueMessage(value, message.list_value)
self._ConvertListValueMessage(value, message.list_value, path)
elif value is None:
message.null_value = 0
elif isinstance(value, bool):
@@ -642,68 +687,76 @@ class _Parser(object):
elif isinstance(value, _INT_OR_FLOAT):
message.number_value = value
else:
raise ParseError('Value {0} has unexpected type {1}.'.format(
value, type(value)))
raise ParseError('Value {0} has unexpected type {1} at {2}'.format(
value, type(value), path))
def _ConvertListValueMessage(self, value, message):
def _ConvertListValueMessage(self, value, message, path):
"""Convert a JSON representation into ListValue message."""
if not isinstance(value, list):
raise ParseError(
'ListValue must be in [] which is {0}.'.format(value))
raise ParseError('ListValue must be in [] which is {0} at {1}'.format(
value, path))
message.ClearField('values')
for item in value:
self._ConvertValueMessage(item, message.values.add())
for index, item in enumerate(value):
self._ConvertValueMessage(item, message.values.add(),
'{0}[{1}]'.format(path, index))
def _ConvertStructMessage(self, value, message):
def _ConvertStructMessage(self, value, message, path):
"""Convert a JSON representation into Struct message."""
if not isinstance(value, dict):
raise ParseError(
'Struct must be in a dict which is {0}.'.format(value))
raise ParseError('Struct must be in a dict which is {0} at {1}'.format(
value, path))
# Clear will mark the struct as modified so it will be created even if
# there are no values.
message.Clear()
for key in value:
self._ConvertValueMessage(value[key], message.fields[key])
self._ConvertValueMessage(value[key], message.fields[key],
'{0}.{1}'.format(path, key))
return
def _ConvertWrapperMessage(self, value, message):
def _ConvertWrapperMessage(self, value, message, path):
"""Convert a JSON representation into Wrapper message."""
field = message.DESCRIPTOR.fields_by_name['value']
setattr(message, 'value', _ConvertScalarFieldValue(value, field))
setattr(
message, 'value',
_ConvertScalarFieldValue(value, field, path='{0}.value'.format(path)))
def _ConvertMapFieldValue(self, value, message, field):
def _ConvertMapFieldValue(self, value, message, field, path):
"""Convert map field value for a message map field.
Args:
value: A JSON object to convert the map field value.
message: A protocol message to record the converted data.
field: The descriptor of the map field to be converted.
path: parent path to log parse error info.
Raises:
ParseError: In case of convert problems.
"""
if not isinstance(value, dict):
raise ParseError(
'Map field {0} must be in a dict which is {1}.'.format(
field.name, value))
'Map field {0} must be in a dict which is {1} at {2}'.format(
field.name, value, path))
key_field = field.message_type.fields_by_name['key']
value_field = field.message_type.fields_by_name['value']
for key in value:
key_value = _ConvertScalarFieldValue(key, key_field, True)
key_value = _ConvertScalarFieldValue(key, key_field,
'{0}.key'.format(path), True)
if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
self.ConvertMessage(value[key], getattr(
message, field.name)[key_value])
self.ConvertMessage(value[key],
getattr(message, field.name)[key_value],
'{0}[{1}]'.format(path, key_value))
else:
getattr(message, field.name)[key_value] = _ConvertScalarFieldValue(
value[key], value_field)
value[key], value_field, path='{0}[{1}]'.format(path, key_value))
def _ConvertScalarFieldValue(value, field, require_str=False):
def _ConvertScalarFieldValue(value, field, path, require_str=False):
"""Convert a single scalar field value.
Args:
value: A scalar value to convert the scalar field value.
field: The descriptor of the field to convert.
path: parent path to log parse error info.
require_str: If True, the field value must be a str.
Returns:
@@ -712,44 +765,47 @@ def _ConvertScalarFieldValue(value, field, require_str=False):
Raises:
ParseError: In case of convert problems.
"""
if field.cpp_type in _INT_TYPES:
return _ConvertInteger(value)
elif field.cpp_type in _FLOAT_TYPES:
return _ConvertFloat(value, field)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return _ConvertBool(value, require_str)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
if isinstance(value, str):
encoded = value.encode('utf-8')
try:
if field.cpp_type in _INT_TYPES:
return _ConvertInteger(value)
elif field.cpp_type in _FLOAT_TYPES:
return _ConvertFloat(value, field)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return _ConvertBool(value, require_str)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
if isinstance(value, str):
encoded = value.encode('utf-8')
else:
encoded = value
# Add extra padding '='
padded_value = encoded + b'=' * (4 - len(encoded) % 4)
return base64.urlsafe_b64decode(padded_value)
else:
encoded = value
# Add extra padding '='
padded_value = encoded + b'=' * (4 - len(encoded) % 4)
return base64.urlsafe_b64decode(padded_value)
else:
# Checking for unpaired surrogates appears to be unreliable,
# depending on the specific Python version, so we check manually.
if _UNPAIRED_SURROGATE_PATTERN.search(value):
raise ParseError('Unpaired surrogate')
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
# Convert an enum value.
enum_value = field.enum_type.values_by_name.get(value, None)
if enum_value is None:
try:
number = int(value)
enum_value = field.enum_type.values_by_number.get(number, None)
except ValueError:
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
# Checking for unpaired surrogates appears to be unreliable,
# depending on the specific Python version, so we check manually.
if _UNPAIRED_SURROGATE_PATTERN.search(value):
raise ParseError('Unpaired surrogate')
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
# Convert an enum value.
enum_value = field.enum_type.values_by_name.get(value, None)
if enum_value is None:
if field.file.syntax == 'proto3':
# Proto3 accepts unknown enums.
return number
raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
value, field.enum_type.full_name))
return enum_value.number
try:
number = int(value)
enum_value = field.enum_type.values_by_number.get(number, None)
except ValueError:
raise ParseError('Invalid enum value {0} for enum type {1}'.format(
value, field.enum_type.full_name))
if enum_value is None:
if field.file.syntax == 'proto3':
# Proto3 accepts unknown enums.
return number
raise ParseError('Invalid enum value {0} for enum type {1}'.format(
value, field.enum_type.full_name))
return enum_value.number
except ParseError as e:
raise ParseError('{0} at {1}'.format(e, path))
def _ConvertInteger(value):
@@ -765,14 +821,14 @@ def _ConvertInteger(value):
ParseError: If an integer couldn't be consumed.
"""
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
raise ParseError('Couldn\'t parse integer: {0}'.format(value))
if isinstance(value, str) and value.find(' ') != -1:
raise ParseError('Couldn\'t parse integer: "{0}".'.format(value))
raise ParseError('Couldn\'t parse integer: "{0}"'.format(value))
if isinstance(value, bool):
raise ParseError('Bool value {0} is not acceptable for '
'integer field.'.format(value))
'integer field'.format(value))
return int(value)
@@ -781,14 +837,14 @@ def _ConvertFloat(value, field):
"""Convert an floating point number."""
if isinstance(value, float):
if math.isnan(value):
raise ParseError('Couldn\'t parse NaN, use quoted "NaN" instead.')
raise ParseError('Couldn\'t parse NaN, use quoted "NaN" instead')
if math.isinf(value):
if value > 0:
raise ParseError('Couldn\'t parse Infinity or value too large, '
'use quoted "Infinity" instead.')
'use quoted "Infinity" instead')
else:
raise ParseError('Couldn\'t parse -Infinity or value too small, '
'use quoted "-Infinity" instead.')
'use quoted "-Infinity" instead')
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT:
# pylint: disable=protected-access
if value > type_checkers._FLOAT_MAX:
@@ -797,7 +853,7 @@ def _ConvertFloat(value, field):
if value < type_checkers._FLOAT_MIN:
raise ParseError('Float value too small')
if value == 'nan':
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
raise ParseError('Couldn\'t parse float "nan", use "NaN" instead')
try:
# Assume Python compatible syntax.
return float(value)
@@ -810,7 +866,7 @@ def _ConvertFloat(value, field):
elif value == _NAN:
return float('nan')
else:
raise ParseError('Couldn\'t parse float: {0}.'.format(value))
raise ParseError('Couldn\'t parse float: {0}'.format(value))
def _ConvertBool(value, require_str):
@@ -832,10 +888,10 @@ def _ConvertBool(value, require_str):
elif value == 'false':
return False
else:
raise ParseError('Expected "true" or "false", not {0}.'.format(value))
raise ParseError('Expected "true" or "false", not {0}'.format(value))
if not isinstance(value, bool):
raise ParseError('Expected true or false without quotes.')
raise ParseError('Expected true or false without quotes')
return value
_WKTJSONMETHODS = {
@@ -2,11 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/map_proto2_unittest.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -22,229 +20,8 @@ except AttributeError:
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n)google/protobuf/map_proto2_unittest.proto\x12\x11protobuf_unittest\x1a%google/protobuf/unittest_import.proto\"\xdb\x02\n\x0bTestEnumMap\x12J\n\x0fknown_map_field\x18\x65 \x03(\x0b\x32\x31.protobuf_unittest.TestEnumMap.KnownMapFieldEntry\x12N\n\x11unknown_map_field\x18\x66 \x03(\x0b\x32\x33.protobuf_unittest.TestEnumMap.UnknownMapFieldEntry\x1aV\n\x12KnownMapFieldEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12/\n\x05value\x18\x02 \x01(\x0e\x32 .protobuf_unittest.Proto2MapEnum:\x02\x38\x01\x1aX\n\x14UnknownMapFieldEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12/\n\x05value\x18\x02 \x01(\x0e\x32 .protobuf_unittest.Proto2MapEnum:\x02\x38\x01\"\x88\x03\n\x14TestEnumMapPlusExtra\x12S\n\x0fknown_map_field\x18\x65 \x03(\x0b\x32:.protobuf_unittest.TestEnumMapPlusExtra.KnownMapFieldEntry\x12W\n\x11unknown_map_field\x18\x66 \x03(\x0b\x32<.protobuf_unittest.TestEnumMapPlusExtra.UnknownMapFieldEntry\x1a_\n\x12KnownMapFieldEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\x38\n\x05value\x18\x02 \x01(\x0e\x32).protobuf_unittest.Proto2MapEnumPlusExtra:\x02\x38\x01\x1a\x61\n\x14UnknownMapFieldEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\x38\n\x05value\x18\x02 \x01(\x0e\x32).protobuf_unittest.Proto2MapEnumPlusExtra:\x02\x38\x01\"\xc7\x01\n\x11TestImportEnumMap\x12P\n\x0fimport_enum_amp\x18\x01 \x03(\x0b\x32\x37.protobuf_unittest.TestImportEnumMap.ImportEnumAmpEntry\x1a`\n\x12ImportEnumAmpEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\x39\n\x05value\x18\x02 \x01(\x0e\x32*.protobuf_unittest_import.ImportEnumForMap:\x02\x38\x01\"m\n\rTestIntIntMap\x12\x32\n\x01m\x18\x01 \x03(\x0b\x32\'.protobuf_unittest.TestIntIntMap.MEntry\x1a(\n\x06MEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\"\xb8\r\n\x08TestMaps\x12\x38\n\x07m_int32\x18\x01 \x03(\x0b\x32\'.protobuf_unittest.TestMaps.MInt32Entry\x12\x38\n\x07m_int64\x18\x02 \x03(\x0b\x32\'.protobuf_unittest.TestMaps.MInt64Entry\x12:\n\x08m_uint32\x18\x03 \x03(\x0b\x32(.protobuf_unittest.TestMaps.MUint32Entry\x12:\n\x08m_uint64\x18\x04 \x03(\x0b\x32(.protobuf_unittest.TestMaps.MUint64Entry\x12:\n\x08m_sint32\x18\x05 \x03(\x0b\x32(.protobuf_unittest.TestMaps.MSint32Entry\x12:\n\x08m_sint64\x18\x06 \x03(\x0b\x32(.protobuf_unittest.TestMaps.MSint64Entry\x12<\n\tm_fixed32\x18\x07 \x03(\x0b\x32).protobuf_unittest.TestMaps.MFixed32Entry\x12<\n\tm_fixed64\x18\x08 \x03(\x0b\x32).protobuf_unittest.TestMaps.MFixed64Entry\x12>\n\nm_sfixed32\x18\t \x03(\x0b\x32*.protobuf_unittest.TestMaps.MSfixed32Entry\x12>\n\nm_sfixed64\x18\n \x03(\x0b\x32*.protobuf_unittest.TestMaps.MSfixed64Entry\x12\x36\n\x06m_bool\x18\x0b \x03(\x0b\x32&.protobuf_unittest.TestMaps.MBoolEntry\x12:\n\x08m_string\x18\x0c \x03(\x0b\x32(.protobuf_unittest.TestMaps.MStringEntry\x1aO\n\x0bMInt32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aO\n\x0bMInt64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x03\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aP\n\x0cMUint32Entry\x12\x0b\n\x03key\x18\x01 \x01(\r\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aP\n\x0cMUint64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x04\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aP\n\x0cMSint32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x11\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aP\n\x0cMSint64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x12\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aQ\n\rMFixed32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x07\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aQ\n\rMFixed64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x06\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aR\n\x0eMSfixed32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x0f\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aR\n\x0eMSfixed64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x10\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aN\n\nMBoolEntry\x12\x0b\n\x03key\x18\x01 \x01(\x08\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\x1aP\n\x0cMStringEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12/\n\x05value\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestIntIntMap:\x02\x38\x01\"<\n\x12TestSubmessageMaps\x12&\n\x01m\x18\x01 \x01(\x0b\x32\x1b.protobuf_unittest.TestMaps*Z\n\rProto2MapEnum\x12\x17\n\x13PROTO2_MAP_ENUM_FOO\x10\x00\x12\x17\n\x13PROTO2_MAP_ENUM_BAR\x10\x01\x12\x17\n\x13PROTO2_MAP_ENUM_BAZ\x10\x02*\x86\x01\n\x16Proto2MapEnumPlusExtra\x12\x19\n\x15\x45_PROTO2_MAP_ENUM_FOO\x10\x00\x12\x19\n\x15\x45_PROTO2_MAP_ENUM_BAR\x10\x01\x12\x19\n\x15\x45_PROTO2_MAP_ENUM_BAZ\x10\x02\x12\x1b\n\x17\x45_PROTO2_MAP_ENUM_EXTRA\x10\x03\x42\x03\xf8\x01\x01')
_PROTO2MAPENUM = DESCRIPTOR.enum_types_by_name['Proto2MapEnum']
Proto2MapEnum = enum_type_wrapper.EnumTypeWrapper(_PROTO2MAPENUM)
_PROTO2MAPENUMPLUSEXTRA = DESCRIPTOR.enum_types_by_name['Proto2MapEnumPlusExtra']
Proto2MapEnumPlusExtra = enum_type_wrapper.EnumTypeWrapper(_PROTO2MAPENUMPLUSEXTRA)
PROTO2_MAP_ENUM_FOO = 0
PROTO2_MAP_ENUM_BAR = 1
PROTO2_MAP_ENUM_BAZ = 2
E_PROTO2_MAP_ENUM_FOO = 0
E_PROTO2_MAP_ENUM_BAR = 1
E_PROTO2_MAP_ENUM_BAZ = 2
E_PROTO2_MAP_ENUM_EXTRA = 3
_TESTENUMMAP = DESCRIPTOR.message_types_by_name['TestEnumMap']
_TESTENUMMAP_KNOWNMAPFIELDENTRY = _TESTENUMMAP.nested_types_by_name['KnownMapFieldEntry']
_TESTENUMMAP_UNKNOWNMAPFIELDENTRY = _TESTENUMMAP.nested_types_by_name['UnknownMapFieldEntry']
_TESTENUMMAPPLUSEXTRA = DESCRIPTOR.message_types_by_name['TestEnumMapPlusExtra']
_TESTENUMMAPPLUSEXTRA_KNOWNMAPFIELDENTRY = _TESTENUMMAPPLUSEXTRA.nested_types_by_name['KnownMapFieldEntry']
_TESTENUMMAPPLUSEXTRA_UNKNOWNMAPFIELDENTRY = _TESTENUMMAPPLUSEXTRA.nested_types_by_name['UnknownMapFieldEntry']
_TESTIMPORTENUMMAP = DESCRIPTOR.message_types_by_name['TestImportEnumMap']
_TESTIMPORTENUMMAP_IMPORTENUMAMPENTRY = _TESTIMPORTENUMMAP.nested_types_by_name['ImportEnumAmpEntry']
_TESTINTINTMAP = DESCRIPTOR.message_types_by_name['TestIntIntMap']
_TESTINTINTMAP_MENTRY = _TESTINTINTMAP.nested_types_by_name['MEntry']
_TESTMAPS = DESCRIPTOR.message_types_by_name['TestMaps']
_TESTMAPS_MINT32ENTRY = _TESTMAPS.nested_types_by_name['MInt32Entry']
_TESTMAPS_MINT64ENTRY = _TESTMAPS.nested_types_by_name['MInt64Entry']
_TESTMAPS_MUINT32ENTRY = _TESTMAPS.nested_types_by_name['MUint32Entry']
_TESTMAPS_MUINT64ENTRY = _TESTMAPS.nested_types_by_name['MUint64Entry']
_TESTMAPS_MSINT32ENTRY = _TESTMAPS.nested_types_by_name['MSint32Entry']
_TESTMAPS_MSINT64ENTRY = _TESTMAPS.nested_types_by_name['MSint64Entry']
_TESTMAPS_MFIXED32ENTRY = _TESTMAPS.nested_types_by_name['MFixed32Entry']
_TESTMAPS_MFIXED64ENTRY = _TESTMAPS.nested_types_by_name['MFixed64Entry']
_TESTMAPS_MSFIXED32ENTRY = _TESTMAPS.nested_types_by_name['MSfixed32Entry']
_TESTMAPS_MSFIXED64ENTRY = _TESTMAPS.nested_types_by_name['MSfixed64Entry']
_TESTMAPS_MBOOLENTRY = _TESTMAPS.nested_types_by_name['MBoolEntry']
_TESTMAPS_MSTRINGENTRY = _TESTMAPS.nested_types_by_name['MStringEntry']
_TESTSUBMESSAGEMAPS = DESCRIPTOR.message_types_by_name['TestSubmessageMaps']
TestEnumMap = _reflection.GeneratedProtocolMessageType('TestEnumMap', (_message.Message,), {
'KnownMapFieldEntry' : _reflection.GeneratedProtocolMessageType('KnownMapFieldEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTENUMMAP_KNOWNMAPFIELDENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestEnumMap.KnownMapFieldEntry)
})
,
'UnknownMapFieldEntry' : _reflection.GeneratedProtocolMessageType('UnknownMapFieldEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTENUMMAP_UNKNOWNMAPFIELDENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestEnumMap.UnknownMapFieldEntry)
})
,
'DESCRIPTOR' : _TESTENUMMAP,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestEnumMap)
})
_sym_db.RegisterMessage(TestEnumMap)
_sym_db.RegisterMessage(TestEnumMap.KnownMapFieldEntry)
_sym_db.RegisterMessage(TestEnumMap.UnknownMapFieldEntry)
TestEnumMapPlusExtra = _reflection.GeneratedProtocolMessageType('TestEnumMapPlusExtra', (_message.Message,), {
'KnownMapFieldEntry' : _reflection.GeneratedProtocolMessageType('KnownMapFieldEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTENUMMAPPLUSEXTRA_KNOWNMAPFIELDENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestEnumMapPlusExtra.KnownMapFieldEntry)
})
,
'UnknownMapFieldEntry' : _reflection.GeneratedProtocolMessageType('UnknownMapFieldEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTENUMMAPPLUSEXTRA_UNKNOWNMAPFIELDENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestEnumMapPlusExtra.UnknownMapFieldEntry)
})
,
'DESCRIPTOR' : _TESTENUMMAPPLUSEXTRA,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestEnumMapPlusExtra)
})
_sym_db.RegisterMessage(TestEnumMapPlusExtra)
_sym_db.RegisterMessage(TestEnumMapPlusExtra.KnownMapFieldEntry)
_sym_db.RegisterMessage(TestEnumMapPlusExtra.UnknownMapFieldEntry)
TestImportEnumMap = _reflection.GeneratedProtocolMessageType('TestImportEnumMap', (_message.Message,), {
'ImportEnumAmpEntry' : _reflection.GeneratedProtocolMessageType('ImportEnumAmpEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTIMPORTENUMMAP_IMPORTENUMAMPENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestImportEnumMap.ImportEnumAmpEntry)
})
,
'DESCRIPTOR' : _TESTIMPORTENUMMAP,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestImportEnumMap)
})
_sym_db.RegisterMessage(TestImportEnumMap)
_sym_db.RegisterMessage(TestImportEnumMap.ImportEnumAmpEntry)
TestIntIntMap = _reflection.GeneratedProtocolMessageType('TestIntIntMap', (_message.Message,), {
'MEntry' : _reflection.GeneratedProtocolMessageType('MEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTINTINTMAP_MENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestIntIntMap.MEntry)
})
,
'DESCRIPTOR' : _TESTINTINTMAP,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestIntIntMap)
})
_sym_db.RegisterMessage(TestIntIntMap)
_sym_db.RegisterMessage(TestIntIntMap.MEntry)
TestMaps = _reflection.GeneratedProtocolMessageType('TestMaps', (_message.Message,), {
'MInt32Entry' : _reflection.GeneratedProtocolMessageType('MInt32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MINT32ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MInt32Entry)
})
,
'MInt64Entry' : _reflection.GeneratedProtocolMessageType('MInt64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MINT64ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MInt64Entry)
})
,
'MUint32Entry' : _reflection.GeneratedProtocolMessageType('MUint32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MUINT32ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MUint32Entry)
})
,
'MUint64Entry' : _reflection.GeneratedProtocolMessageType('MUint64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MUINT64ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MUint64Entry)
})
,
'MSint32Entry' : _reflection.GeneratedProtocolMessageType('MSint32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MSINT32ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MSint32Entry)
})
,
'MSint64Entry' : _reflection.GeneratedProtocolMessageType('MSint64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MSINT64ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MSint64Entry)
})
,
'MFixed32Entry' : _reflection.GeneratedProtocolMessageType('MFixed32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MFIXED32ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MFixed32Entry)
})
,
'MFixed64Entry' : _reflection.GeneratedProtocolMessageType('MFixed64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MFIXED64ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MFixed64Entry)
})
,
'MSfixed32Entry' : _reflection.GeneratedProtocolMessageType('MSfixed32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MSFIXED32ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MSfixed32Entry)
})
,
'MSfixed64Entry' : _reflection.GeneratedProtocolMessageType('MSfixed64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MSFIXED64ENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MSfixed64Entry)
})
,
'MBoolEntry' : _reflection.GeneratedProtocolMessageType('MBoolEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MBOOLENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MBoolEntry)
})
,
'MStringEntry' : _reflection.GeneratedProtocolMessageType('MStringEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPS_MSTRINGENTRY,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps.MStringEntry)
})
,
'DESCRIPTOR' : _TESTMAPS,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMaps)
})
_sym_db.RegisterMessage(TestMaps)
_sym_db.RegisterMessage(TestMaps.MInt32Entry)
_sym_db.RegisterMessage(TestMaps.MInt64Entry)
_sym_db.RegisterMessage(TestMaps.MUint32Entry)
_sym_db.RegisterMessage(TestMaps.MUint64Entry)
_sym_db.RegisterMessage(TestMaps.MSint32Entry)
_sym_db.RegisterMessage(TestMaps.MSint64Entry)
_sym_db.RegisterMessage(TestMaps.MFixed32Entry)
_sym_db.RegisterMessage(TestMaps.MFixed64Entry)
_sym_db.RegisterMessage(TestMaps.MSfixed32Entry)
_sym_db.RegisterMessage(TestMaps.MSfixed64Entry)
_sym_db.RegisterMessage(TestMaps.MBoolEntry)
_sym_db.RegisterMessage(TestMaps.MStringEntry)
TestSubmessageMaps = _reflection.GeneratedProtocolMessageType('TestSubmessageMaps', (_message.Message,), {
'DESCRIPTOR' : _TESTSUBMESSAGEMAPS,
'__module__' : 'google.protobuf.map_proto2_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestSubmessageMaps)
})
_sym_db.RegisterMessage(TestSubmessageMaps)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.map_proto2_unittest_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
@@ -2,11 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/map_unittest.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -18,473 +16,8 @@ from google.protobuf import unittest_pb2 as google_dot_protobuf_dot_unittest__pb
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\"google/protobuf/map_unittest.proto\x12\x11protobuf_unittest\x1a\x1egoogle/protobuf/unittest.proto\"\xff\x14\n\x07TestMap\x12\x46\n\x0fmap_int32_int32\x18\x01 \x03(\x0b\x32-.protobuf_unittest.TestMap.MapInt32Int32Entry\x12\x46\n\x0fmap_int64_int64\x18\x02 \x03(\x0b\x32-.protobuf_unittest.TestMap.MapInt64Int64Entry\x12J\n\x11map_uint32_uint32\x18\x03 \x03(\x0b\x32/.protobuf_unittest.TestMap.MapUint32Uint32Entry\x12J\n\x11map_uint64_uint64\x18\x04 \x03(\x0b\x32/.protobuf_unittest.TestMap.MapUint64Uint64Entry\x12J\n\x11map_sint32_sint32\x18\x05 \x03(\x0b\x32/.protobuf_unittest.TestMap.MapSint32Sint32Entry\x12J\n\x11map_sint64_sint64\x18\x06 \x03(\x0b\x32/.protobuf_unittest.TestMap.MapSint64Sint64Entry\x12N\n\x13map_fixed32_fixed32\x18\x07 \x03(\x0b\x32\x31.protobuf_unittest.TestMap.MapFixed32Fixed32Entry\x12N\n\x13map_fixed64_fixed64\x18\x08 \x03(\x0b\x32\x31.protobuf_unittest.TestMap.MapFixed64Fixed64Entry\x12R\n\x15map_sfixed32_sfixed32\x18\t \x03(\x0b\x32\x33.protobuf_unittest.TestMap.MapSfixed32Sfixed32Entry\x12R\n\x15map_sfixed64_sfixed64\x18\n \x03(\x0b\x32\x33.protobuf_unittest.TestMap.MapSfixed64Sfixed64Entry\x12\x46\n\x0fmap_int32_float\x18\x0b \x03(\x0b\x32-.protobuf_unittest.TestMap.MapInt32FloatEntry\x12H\n\x10map_int32_double\x18\x0c \x03(\x0b\x32..protobuf_unittest.TestMap.MapInt32DoubleEntry\x12\x42\n\rmap_bool_bool\x18\r \x03(\x0b\x32+.protobuf_unittest.TestMap.MapBoolBoolEntry\x12J\n\x11map_string_string\x18\x0e \x03(\x0b\x32/.protobuf_unittest.TestMap.MapStringStringEntry\x12\x46\n\x0fmap_int32_bytes\x18\x0f \x03(\x0b\x32-.protobuf_unittest.TestMap.MapInt32BytesEntry\x12\x44\n\x0emap_int32_enum\x18\x10 \x03(\x0b\x32,.protobuf_unittest.TestMap.MapInt32EnumEntry\x12Y\n\x19map_int32_foreign_message\x18\x11 \x03(\x0b\x32\x36.protobuf_unittest.TestMap.MapInt32ForeignMessageEntry\x12[\n\x1amap_string_foreign_message\x18\x12 \x03(\x0b\x32\x37.protobuf_unittest.TestMap.MapStringForeignMessageEntry\x12M\n\x13map_int32_all_types\x18\x13 \x03(\x0b\x32\x30.protobuf_unittest.TestMap.MapInt32AllTypesEntry\x1a\x34\n\x12MapInt32Int32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x34\n\x12MapInt64Int64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x03\x12\r\n\x05value\x18\x02 \x01(\x03:\x02\x38\x01\x1a\x36\n\x14MapUint32Uint32Entry\x12\x0b\n\x03key\x18\x01 \x01(\r\x12\r\n\x05value\x18\x02 \x01(\r:\x02\x38\x01\x1a\x36\n\x14MapUint64Uint64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x04:\x02\x38\x01\x1a\x36\n\x14MapSint32Sint32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x11\x12\r\n\x05value\x18\x02 \x01(\x11:\x02\x38\x01\x1a\x36\n\x14MapSint64Sint64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x12\x12\r\n\x05value\x18\x02 \x01(\x12:\x02\x38\x01\x1a\x38\n\x16MapFixed32Fixed32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x07\x12\r\n\x05value\x18\x02 \x01(\x07:\x02\x38\x01\x1a\x38\n\x16MapFixed64Fixed64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x06\x12\r\n\x05value\x18\x02 \x01(\x06:\x02\x38\x01\x1a:\n\x18MapSfixed32Sfixed32Entry\x12\x0b\n\x03key\x18\x01 \x01(\x0f\x12\r\n\x05value\x18\x02 \x01(\x0f:\x02\x38\x01\x1a:\n\x18MapSfixed64Sfixed64Entry\x12\x0b\n\x03key\x18\x01 \x01(\x10\x12\r\n\x05value\x18\x02 \x01(\x10:\x02\x38\x01\x1a\x34\n\x12MapInt32FloatEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x02:\x02\x38\x01\x1a\x35\n\x13MapInt32DoubleEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x01:\x02\x38\x01\x1a\x32\n\x10MapBoolBoolEntry\x12\x0b\n\x03key\x18\x01 \x01(\x08\x12\r\n\x05value\x18\x02 \x01(\x08:\x02\x38\x01\x1a\x36\n\x14MapStringStringEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x34\n\x12MapInt32BytesEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x0c:\x02\x38\x01\x1aO\n\x11MapInt32EnumEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12)\n\x05value\x18\x02 \x01(\x0e\x32\x1a.protobuf_unittest.MapEnum:\x02\x38\x01\x1a`\n\x1bMapInt32ForeignMessageEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\x30\n\x05value\x18\x02 \x01(\x0b\x32!.protobuf_unittest.ForeignMessage:\x02\x38\x01\x1a\x61\n\x1cMapStringForeignMessageEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x30\n\x05value\x18\x02 \x01(\x0b\x32!.protobuf_unittest.ForeignMessage:\x02\x38\x01\x1aX\n\x15MapInt32AllTypesEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes:\x02\x38\x01\"A\n\x11TestMapSubmessage\x12,\n\x08test_map\x18\x01 \x01(\x0b\x32\x1a.protobuf_unittest.TestMap\"\xbc\x01\n\x0eTestMessageMap\x12Q\n\x11map_int32_message\x18\x01 \x03(\x0b\x32\x36.protobuf_unittest.TestMessageMap.MapInt32MessageEntry\x1aW\n\x14MapInt32MessageEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes:\x02\x38\x01\"\xe3\x01\n\x0fTestSameTypeMap\x12:\n\x04map1\x18\x01 \x03(\x0b\x32,.protobuf_unittest.TestSameTypeMap.Map1Entry\x12:\n\x04map2\x18\x02 \x03(\x0b\Line truncated
_MAPENUM = DESCRIPTOR.enum_types_by_name['MapEnum']
MapEnum = enum_type_wrapper.EnumTypeWrapper(_MAPENUM)
MAP_ENUM_FOO = 0
MAP_ENUM_BAR = 1
MAP_ENUM_BAZ = 2
_TESTMAP = DESCRIPTOR.message_types_by_name['TestMap']
_TESTMAP_MAPINT32INT32ENTRY = _TESTMAP.nested_types_by_name['MapInt32Int32Entry']
_TESTMAP_MAPINT64INT64ENTRY = _TESTMAP.nested_types_by_name['MapInt64Int64Entry']
_TESTMAP_MAPUINT32UINT32ENTRY = _TESTMAP.nested_types_by_name['MapUint32Uint32Entry']
_TESTMAP_MAPUINT64UINT64ENTRY = _TESTMAP.nested_types_by_name['MapUint64Uint64Entry']
_TESTMAP_MAPSINT32SINT32ENTRY = _TESTMAP.nested_types_by_name['MapSint32Sint32Entry']
_TESTMAP_MAPSINT64SINT64ENTRY = _TESTMAP.nested_types_by_name['MapSint64Sint64Entry']
_TESTMAP_MAPFIXED32FIXED32ENTRY = _TESTMAP.nested_types_by_name['MapFixed32Fixed32Entry']
_TESTMAP_MAPFIXED64FIXED64ENTRY = _TESTMAP.nested_types_by_name['MapFixed64Fixed64Entry']
_TESTMAP_MAPSFIXED32SFIXED32ENTRY = _TESTMAP.nested_types_by_name['MapSfixed32Sfixed32Entry']
_TESTMAP_MAPSFIXED64SFIXED64ENTRY = _TESTMAP.nested_types_by_name['MapSfixed64Sfixed64Entry']
_TESTMAP_MAPINT32FLOATENTRY = _TESTMAP.nested_types_by_name['MapInt32FloatEntry']
_TESTMAP_MAPINT32DOUBLEENTRY = _TESTMAP.nested_types_by_name['MapInt32DoubleEntry']
_TESTMAP_MAPBOOLBOOLENTRY = _TESTMAP.nested_types_by_name['MapBoolBoolEntry']
_TESTMAP_MAPSTRINGSTRINGENTRY = _TESTMAP.nested_types_by_name['MapStringStringEntry']
_TESTMAP_MAPINT32BYTESENTRY = _TESTMAP.nested_types_by_name['MapInt32BytesEntry']
_TESTMAP_MAPINT32ENUMENTRY = _TESTMAP.nested_types_by_name['MapInt32EnumEntry']
_TESTMAP_MAPINT32FOREIGNMESSAGEENTRY = _TESTMAP.nested_types_by_name['MapInt32ForeignMessageEntry']
_TESTMAP_MAPSTRINGFOREIGNMESSAGEENTRY = _TESTMAP.nested_types_by_name['MapStringForeignMessageEntry']
_TESTMAP_MAPINT32ALLTYPESENTRY = _TESTMAP.nested_types_by_name['MapInt32AllTypesEntry']
_TESTMAPSUBMESSAGE = DESCRIPTOR.message_types_by_name['TestMapSubmessage']
_TESTMESSAGEMAP = DESCRIPTOR.message_types_by_name['TestMessageMap']
_TESTMESSAGEMAP_MAPINT32MESSAGEENTRY = _TESTMESSAGEMAP.nested_types_by_name['MapInt32MessageEntry']
_TESTSAMETYPEMAP = DESCRIPTOR.message_types_by_name['TestSameTypeMap']
_TESTSAMETYPEMAP_MAP1ENTRY = _TESTSAMETYPEMAP.nested_types_by_name['Map1Entry']
_TESTSAMETYPEMAP_MAP2ENTRY = _TESTSAMETYPEMAP.nested_types_by_name['Map2Entry']
_TESTREQUIREDMESSAGEMAP = DESCRIPTOR.message_types_by_name['TestRequiredMessageMap']
_TESTREQUIREDMESSAGEMAP_MAPFIELDENTRY = _TESTREQUIREDMESSAGEMAP.nested_types_by_name['MapFieldEntry']
_TESTARENAMAP = DESCRIPTOR.message_types_by_name['TestArenaMap']
_TESTARENAMAP_MAPINT32INT32ENTRY = _TESTARENAMAP.nested_types_by_name['MapInt32Int32Entry']
_TESTARENAMAP_MAPINT64INT64ENTRY = _TESTARENAMAP.nested_types_by_name['MapInt64Int64Entry']
_TESTARENAMAP_MAPUINT32UINT32ENTRY = _TESTARENAMAP.nested_types_by_name['MapUint32Uint32Entry']
_TESTARENAMAP_MAPUINT64UINT64ENTRY = _TESTARENAMAP.nested_types_by_name['MapUint64Uint64Entry']
_TESTARENAMAP_MAPSINT32SINT32ENTRY = _TESTARENAMAP.nested_types_by_name['MapSint32Sint32Entry']
_TESTARENAMAP_MAPSINT64SINT64ENTRY = _TESTARENAMAP.nested_types_by_name['MapSint64Sint64Entry']
_TESTARENAMAP_MAPFIXED32FIXED32ENTRY = _TESTARENAMAP.nested_types_by_name['MapFixed32Fixed32Entry']
_TESTARENAMAP_MAPFIXED64FIXED64ENTRY = _TESTARENAMAP.nested_types_by_name['MapFixed64Fixed64Entry']
_TESTARENAMAP_MAPSFIXED32SFIXED32ENTRY = _TESTARENAMAP.nested_types_by_name['MapSfixed32Sfixed32Entry']
_TESTARENAMAP_MAPSFIXED64SFIXED64ENTRY = _TESTARENAMAP.nested_types_by_name['MapSfixed64Sfixed64Entry']
_TESTARENAMAP_MAPINT32FLOATENTRY = _TESTARENAMAP.nested_types_by_name['MapInt32FloatEntry']
_TESTARENAMAP_MAPINT32DOUBLEENTRY = _TESTARENAMAP.nested_types_by_name['MapInt32DoubleEntry']
_TESTARENAMAP_MAPBOOLBOOLENTRY = _TESTARENAMAP.nested_types_by_name['MapBoolBoolEntry']
_TESTARENAMAP_MAPSTRINGSTRINGENTRY = _TESTARENAMAP.nested_types_by_name['MapStringStringEntry']
_TESTARENAMAP_MAPINT32BYTESENTRY = _TESTARENAMAP.nested_types_by_name['MapInt32BytesEntry']
_TESTARENAMAP_MAPINT32ENUMENTRY = _TESTARENAMAP.nested_types_by_name['MapInt32EnumEntry']
_TESTARENAMAP_MAPINT32FOREIGNMESSAGEENTRY = _TESTARENAMAP.nested_types_by_name['MapInt32ForeignMessageEntry']
_MESSAGECONTAININGENUMCALLEDTYPE = DESCRIPTOR.message_types_by_name['MessageContainingEnumCalledType']
_MESSAGECONTAININGENUMCALLEDTYPE_TYPEENTRY = _MESSAGECONTAININGENUMCALLEDTYPE.nested_types_by_name['TypeEntry']
_MESSAGECONTAININGMAPCALLEDENTRY = DESCRIPTOR.message_types_by_name['MessageContainingMapCalledEntry']
_MESSAGECONTAININGMAPCALLEDENTRY_ENTRYENTRY = _MESSAGECONTAININGMAPCALLEDENTRY.nested_types_by_name['EntryEntry']
_TESTRECURSIVEMAPMESSAGE = DESCRIPTOR.message_types_by_name['TestRecursiveMapMessage']
_TESTRECURSIVEMAPMESSAGE_AENTRY = _TESTRECURSIVEMAPMESSAGE.nested_types_by_name['AEntry']
_MESSAGECONTAININGENUMCALLEDTYPE_TYPE = _MESSAGECONTAININGENUMCALLEDTYPE.enum_types_by_name['Type']
TestMap = _reflection.GeneratedProtocolMessageType('TestMap', (_message.Message,), {
'MapInt32Int32Entry' : _reflection.GeneratedProtocolMessageType('MapInt32Int32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT32INT32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt32Int32Entry)
})
,
'MapInt64Int64Entry' : _reflection.GeneratedProtocolMessageType('MapInt64Int64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT64INT64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt64Int64Entry)
})
,
'MapUint32Uint32Entry' : _reflection.GeneratedProtocolMessageType('MapUint32Uint32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPUINT32UINT32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapUint32Uint32Entry)
})
,
'MapUint64Uint64Entry' : _reflection.GeneratedProtocolMessageType('MapUint64Uint64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPUINT64UINT64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapUint64Uint64Entry)
})
,
'MapSint32Sint32Entry' : _reflection.GeneratedProtocolMessageType('MapSint32Sint32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPSINT32SINT32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapSint32Sint32Entry)
})
,
'MapSint64Sint64Entry' : _reflection.GeneratedProtocolMessageType('MapSint64Sint64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPSINT64SINT64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapSint64Sint64Entry)
})
,
'MapFixed32Fixed32Entry' : _reflection.GeneratedProtocolMessageType('MapFixed32Fixed32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPFIXED32FIXED32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapFixed32Fixed32Entry)
})
,
'MapFixed64Fixed64Entry' : _reflection.GeneratedProtocolMessageType('MapFixed64Fixed64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPFIXED64FIXED64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapFixed64Fixed64Entry)
})
,
'MapSfixed32Sfixed32Entry' : _reflection.GeneratedProtocolMessageType('MapSfixed32Sfixed32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPSFIXED32SFIXED32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapSfixed32Sfixed32Entry)
})
,
'MapSfixed64Sfixed64Entry' : _reflection.GeneratedProtocolMessageType('MapSfixed64Sfixed64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPSFIXED64SFIXED64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapSfixed64Sfixed64Entry)
})
,
'MapInt32FloatEntry' : _reflection.GeneratedProtocolMessageType('MapInt32FloatEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT32FLOATENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt32FloatEntry)
})
,
'MapInt32DoubleEntry' : _reflection.GeneratedProtocolMessageType('MapInt32DoubleEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT32DOUBLEENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt32DoubleEntry)
})
,
'MapBoolBoolEntry' : _reflection.GeneratedProtocolMessageType('MapBoolBoolEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPBOOLBOOLENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapBoolBoolEntry)
})
,
'MapStringStringEntry' : _reflection.GeneratedProtocolMessageType('MapStringStringEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPSTRINGSTRINGENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapStringStringEntry)
})
,
'MapInt32BytesEntry' : _reflection.GeneratedProtocolMessageType('MapInt32BytesEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT32BYTESENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt32BytesEntry)
})
,
'MapInt32EnumEntry' : _reflection.GeneratedProtocolMessageType('MapInt32EnumEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT32ENUMENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt32EnumEntry)
})
,
'MapInt32ForeignMessageEntry' : _reflection.GeneratedProtocolMessageType('MapInt32ForeignMessageEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT32FOREIGNMESSAGEENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt32ForeignMessageEntry)
})
,
'MapStringForeignMessageEntry' : _reflection.GeneratedProtocolMessageType('MapStringForeignMessageEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPSTRINGFOREIGNMESSAGEENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapStringForeignMessageEntry)
})
,
'MapInt32AllTypesEntry' : _reflection.GeneratedProtocolMessageType('MapInt32AllTypesEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMAP_MAPINT32ALLTYPESENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap.MapInt32AllTypesEntry)
})
,
'DESCRIPTOR' : _TESTMAP,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap)
})
_sym_db.RegisterMessage(TestMap)
_sym_db.RegisterMessage(TestMap.MapInt32Int32Entry)
_sym_db.RegisterMessage(TestMap.MapInt64Int64Entry)
_sym_db.RegisterMessage(TestMap.MapUint32Uint32Entry)
_sym_db.RegisterMessage(TestMap.MapUint64Uint64Entry)
_sym_db.RegisterMessage(TestMap.MapSint32Sint32Entry)
_sym_db.RegisterMessage(TestMap.MapSint64Sint64Entry)
_sym_db.RegisterMessage(TestMap.MapFixed32Fixed32Entry)
_sym_db.RegisterMessage(TestMap.MapFixed64Fixed64Entry)
_sym_db.RegisterMessage(TestMap.MapSfixed32Sfixed32Entry)
_sym_db.RegisterMessage(TestMap.MapSfixed64Sfixed64Entry)
_sym_db.RegisterMessage(TestMap.MapInt32FloatEntry)
_sym_db.RegisterMessage(TestMap.MapInt32DoubleEntry)
_sym_db.RegisterMessage(TestMap.MapBoolBoolEntry)
_sym_db.RegisterMessage(TestMap.MapStringStringEntry)
_sym_db.RegisterMessage(TestMap.MapInt32BytesEntry)
_sym_db.RegisterMessage(TestMap.MapInt32EnumEntry)
_sym_db.RegisterMessage(TestMap.MapInt32ForeignMessageEntry)
_sym_db.RegisterMessage(TestMap.MapStringForeignMessageEntry)
_sym_db.RegisterMessage(TestMap.MapInt32AllTypesEntry)
TestMapSubmessage = _reflection.GeneratedProtocolMessageType('TestMapSubmessage', (_message.Message,), {
'DESCRIPTOR' : _TESTMAPSUBMESSAGE,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMapSubmessage)
})
_sym_db.RegisterMessage(TestMapSubmessage)
TestMessageMap = _reflection.GeneratedProtocolMessageType('TestMessageMap', (_message.Message,), {
'MapInt32MessageEntry' : _reflection.GeneratedProtocolMessageType('MapInt32MessageEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTMESSAGEMAP_MAPINT32MESSAGEENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageMap.MapInt32MessageEntry)
})
,
'DESCRIPTOR' : _TESTMESSAGEMAP,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageMap)
})
_sym_db.RegisterMessage(TestMessageMap)
_sym_db.RegisterMessage(TestMessageMap.MapInt32MessageEntry)
TestSameTypeMap = _reflection.GeneratedProtocolMessageType('TestSameTypeMap', (_message.Message,), {
'Map1Entry' : _reflection.GeneratedProtocolMessageType('Map1Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTSAMETYPEMAP_MAP1ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestSameTypeMap.Map1Entry)
})
,
'Map2Entry' : _reflection.GeneratedProtocolMessageType('Map2Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTSAMETYPEMAP_MAP2ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestSameTypeMap.Map2Entry)
})
,
'DESCRIPTOR' : _TESTSAMETYPEMAP,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestSameTypeMap)
})
_sym_db.RegisterMessage(TestSameTypeMap)
_sym_db.RegisterMessage(TestSameTypeMap.Map1Entry)
_sym_db.RegisterMessage(TestSameTypeMap.Map2Entry)
TestRequiredMessageMap = _reflection.GeneratedProtocolMessageType('TestRequiredMessageMap', (_message.Message,), {
'MapFieldEntry' : _reflection.GeneratedProtocolMessageType('MapFieldEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTREQUIREDMESSAGEMAP_MAPFIELDENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestRequiredMessageMap.MapFieldEntry)
})
,
'DESCRIPTOR' : _TESTREQUIREDMESSAGEMAP,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestRequiredMessageMap)
})
_sym_db.RegisterMessage(TestRequiredMessageMap)
_sym_db.RegisterMessage(TestRequiredMessageMap.MapFieldEntry)
TestArenaMap = _reflection.GeneratedProtocolMessageType('TestArenaMap', (_message.Message,), {
'MapInt32Int32Entry' : _reflection.GeneratedProtocolMessageType('MapInt32Int32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPINT32INT32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapInt32Int32Entry)
})
,
'MapInt64Int64Entry' : _reflection.GeneratedProtocolMessageType('MapInt64Int64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPINT64INT64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapInt64Int64Entry)
})
,
'MapUint32Uint32Entry' : _reflection.GeneratedProtocolMessageType('MapUint32Uint32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPUINT32UINT32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapUint32Uint32Entry)
})
,
'MapUint64Uint64Entry' : _reflection.GeneratedProtocolMessageType('MapUint64Uint64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPUINT64UINT64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapUint64Uint64Entry)
})
,
'MapSint32Sint32Entry' : _reflection.GeneratedProtocolMessageType('MapSint32Sint32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPSINT32SINT32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapSint32Sint32Entry)
})
,
'MapSint64Sint64Entry' : _reflection.GeneratedProtocolMessageType('MapSint64Sint64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPSINT64SINT64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapSint64Sint64Entry)
})
,
'MapFixed32Fixed32Entry' : _reflection.GeneratedProtocolMessageType('MapFixed32Fixed32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPFIXED32FIXED32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapFixed32Fixed32Entry)
})
,
'MapFixed64Fixed64Entry' : _reflection.GeneratedProtocolMessageType('MapFixed64Fixed64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPFIXED64FIXED64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapFixed64Fixed64Entry)
})
,
'MapSfixed32Sfixed32Entry' : _reflection.GeneratedProtocolMessageType('MapSfixed32Sfixed32Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPSFIXED32SFIXED32ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapSfixed32Sfixed32Entry)
})
,
'MapSfixed64Sfixed64Entry' : _reflection.GeneratedProtocolMessageType('MapSfixed64Sfixed64Entry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPSFIXED64SFIXED64ENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapSfixed64Sfixed64Entry)
})
,
'MapInt32FloatEntry' : _reflection.GeneratedProtocolMessageType('MapInt32FloatEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPINT32FLOATENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapInt32FloatEntry)
})
,
'MapInt32DoubleEntry' : _reflection.GeneratedProtocolMessageType('MapInt32DoubleEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPINT32DOUBLEENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapInt32DoubleEntry)
})
,
'MapBoolBoolEntry' : _reflection.GeneratedProtocolMessageType('MapBoolBoolEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPBOOLBOOLENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapBoolBoolEntry)
})
,
'MapStringStringEntry' : _reflection.GeneratedProtocolMessageType('MapStringStringEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPSTRINGSTRINGENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapStringStringEntry)
})
,
'MapInt32BytesEntry' : _reflection.GeneratedProtocolMessageType('MapInt32BytesEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPINT32BYTESENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapInt32BytesEntry)
})
,
'MapInt32EnumEntry' : _reflection.GeneratedProtocolMessageType('MapInt32EnumEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPINT32ENUMENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapInt32EnumEntry)
})
,
'MapInt32ForeignMessageEntry' : _reflection.GeneratedProtocolMessageType('MapInt32ForeignMessageEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTARENAMAP_MAPINT32FOREIGNMESSAGEENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap.MapInt32ForeignMessageEntry)
})
,
'DESCRIPTOR' : _TESTARENAMAP,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap)
})
_sym_db.RegisterMessage(TestArenaMap)
_sym_db.RegisterMessage(TestArenaMap.MapInt32Int32Entry)
_sym_db.RegisterMessage(TestArenaMap.MapInt64Int64Entry)
_sym_db.RegisterMessage(TestArenaMap.MapUint32Uint32Entry)
_sym_db.RegisterMessage(TestArenaMap.MapUint64Uint64Entry)
_sym_db.RegisterMessage(TestArenaMap.MapSint32Sint32Entry)
_sym_db.RegisterMessage(TestArenaMap.MapSint64Sint64Entry)
_sym_db.RegisterMessage(TestArenaMap.MapFixed32Fixed32Entry)
_sym_db.RegisterMessage(TestArenaMap.MapFixed64Fixed64Entry)
_sym_db.RegisterMessage(TestArenaMap.MapSfixed32Sfixed32Entry)
_sym_db.RegisterMessage(TestArenaMap.MapSfixed64Sfixed64Entry)
_sym_db.RegisterMessage(TestArenaMap.MapInt32FloatEntry)
_sym_db.RegisterMessage(TestArenaMap.MapInt32DoubleEntry)
_sym_db.RegisterMessage(TestArenaMap.MapBoolBoolEntry)
_sym_db.RegisterMessage(TestArenaMap.MapStringStringEntry)
_sym_db.RegisterMessage(TestArenaMap.MapInt32BytesEntry)
_sym_db.RegisterMessage(TestArenaMap.MapInt32EnumEntry)
_sym_db.RegisterMessage(TestArenaMap.MapInt32ForeignMessageEntry)
MessageContainingEnumCalledType = _reflection.GeneratedProtocolMessageType('MessageContainingEnumCalledType', (_message.Message,), {
'TypeEntry' : _reflection.GeneratedProtocolMessageType('TypeEntry', (_message.Message,), {
'DESCRIPTOR' : _MESSAGECONTAININGENUMCALLEDTYPE_TYPEENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.MessageContainingEnumCalledType.TypeEntry)
})
,
'DESCRIPTOR' : _MESSAGECONTAININGENUMCALLEDTYPE,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.MessageContainingEnumCalledType)
})
_sym_db.RegisterMessage(MessageContainingEnumCalledType)
_sym_db.RegisterMessage(MessageContainingEnumCalledType.TypeEntry)
MessageContainingMapCalledEntry = _reflection.GeneratedProtocolMessageType('MessageContainingMapCalledEntry', (_message.Message,), {
'EntryEntry' : _reflection.GeneratedProtocolMessageType('EntryEntry', (_message.Message,), {
'DESCRIPTOR' : _MESSAGECONTAININGMAPCALLEDENTRY_ENTRYENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.MessageContainingMapCalledEntry.EntryEntry)
})
,
'DESCRIPTOR' : _MESSAGECONTAININGMAPCALLEDENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.MessageContainingMapCalledEntry)
})
_sym_db.RegisterMessage(MessageContainingMapCalledEntry)
_sym_db.RegisterMessage(MessageContainingMapCalledEntry.EntryEntry)
TestRecursiveMapMessage = _reflection.GeneratedProtocolMessageType('TestRecursiveMapMessage', (_message.Message,), {
'AEntry' : _reflection.GeneratedProtocolMessageType('AEntry', (_message.Message,), {
'DESCRIPTOR' : _TESTRECURSIVEMAPMESSAGE_AENTRY,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestRecursiveMapMessage.AEntry)
})
,
'DESCRIPTOR' : _TESTRECURSIVEMAPMESSAGE,
'__module__' : 'google.protobuf.map_unittest_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestRecursiveMapMessage)
})
_sym_db.RegisterMessage(TestRecursiveMapMessage)
_sym_db.RegisterMessage(TestRecursiveMapMessage.AEntry)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.map_unittest_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
+3
View File
@@ -194,6 +194,9 @@ class Message(object):
"""Parse serialized protocol buffer data into this message.
Like :func:`MergeFromString()`, except we clear the object first.
Raises:
message.DecodeError if the input cannot be parsed.
"""
self.Clear()
return self.MergeFromString(serialized)
@@ -43,10 +43,10 @@ from google.protobuf.internal import api_implementation
from google.protobuf import descriptor_pool
from google.protobuf import message
if api_implementation.Type() == 'cpp':
from google.protobuf.pyext import cpp_message as message_impl
else:
if api_implementation.Type() == 'python':
from google.protobuf.internal import python_message as message_impl
else:
from google.protobuf.pyext import cpp_message as message_impl # pylint: disable=g-import-not-at-top
# The type of all Message classes.
@@ -118,6 +118,8 @@ class MessageFactory(object):
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type]
extended_class.RegisterExtension(extension)
if extension.message_type:
self.GetPrototype(extension.message_type)
return result_class
def GetMessages(self, files):
@@ -154,6 +156,8 @@ class MessageFactory(object):
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type]
extended_class.RegisterExtension(extension)
if extension.message_type:
self.GetPrototype(extension.message_type)
return result
+1
View File
@@ -45,6 +45,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_PROTO_API_H__
#define GOOGLE_PROTOBUF_PYTHON_PROTO_API_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <google/protobuf/descriptor_database.h>
@@ -36,7 +36,14 @@ Descriptor objects at runtime backed by the protocol buffer C++ API.
__author__ = 'tibell@google.com (Johan Tibell)'
from google.protobuf.pyext import _message
from google.protobuf.internal import api_implementation
# pylint: disable=protected-access
_message = api_implementation._c_module
# TODO(jieluo): Remove this import after fix api_implementation
if _message is None:
from google.protobuf.pyext import _message
class GeneratedProtocolMessageType(_message.MessageMeta):
File diff suppressed because it is too large. Load diff
@@ -33,6 +33,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <google/protobuf/descriptor.h>
File diff suppressed because it is too large. Load diff
@@ -34,6 +34,7 @@
// Mappings and Sequences of descriptors.
// They implement containers like fields_by_name, EnumDescriptor.values...
// See descriptor_containers.cc for more description.
#define PY_SSIZE_T_CLEAN
#include <Python.h>
namespace google {
@@ -56,7 +56,7 @@ PyDescriptorDatabase::~PyDescriptorDatabase() { Py_DECREF(py_database_); }
// Handles all kinds of Python errors, which are simply logged.
static bool GetFileDescriptorProto(PyObject* py_descriptor,
FileDescriptorProto* output) {
if (py_descriptor == NULL) {
if (py_descriptor == nullptr) {
if (PyErr_ExceptionMatches(PyExc_KeyError)) {
// Expected error: item was simply not found.
PyErr_Clear();
@@ -83,8 +83,8 @@ static bool GetFileDescriptorProto(PyObject* py_descriptor,
// Slow path: serialize the message. This allows to use databases which
// use a different implementation of FileDescriptorProto.
ScopedPyObjectPtr serialized_pb(
PyObject_CallMethod(py_descriptor, "SerializeToString", NULL));
if (serialized_pb == NULL) {
PyObject_CallMethod(py_descriptor, "SerializeToString", nullptr));
if (serialized_pb == nullptr) {
GOOGLE_LOG(ERROR)
<< "DescriptorDatabase method did not return a FileDescriptorProto";
PyErr_Print();
@@ -134,7 +134,7 @@ bool PyDescriptorDatabase::FindFileContainingExtension(
FileDescriptorProto* output) {
ScopedPyObjectPtr py_method(
PyObject_GetAttrString(py_database_, "FindFileContainingExtension"));
if (py_method == NULL) {
if (py_method == nullptr) {
// This method is not implemented, returns without error.
PyErr_Clear();
return false;
@@ -153,7 +153,7 @@ bool PyDescriptorDatabase::FindAllExtensionNumbers(
const std::string& containing_type, std::vector<int>* output) {
ScopedPyObjectPtr py_method(
PyObject_GetAttrString(py_database_, "FindAllExtensionNumbers"));
if (py_method == NULL) {
if (py_method == nullptr) {
// This method is not implemented, returns without error.
PyErr_Clear();
return false;
@@ -161,7 +161,7 @@ bool PyDescriptorDatabase::FindAllExtensionNumbers(
ScopedPyObjectPtr py_list(
PyObject_CallFunction(py_method.get(), "s#", containing_type.c_str(),
containing_type.size()));
if (py_list == NULL) {
if (py_list == nullptr) {
PyErr_Print();
return false;
}
@@ -31,6 +31,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_DATABASE_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_DATABASE_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <google/protobuf/descriptor_database.h>
@@ -42,17 +43,18 @@ namespace python {
class PyDescriptorDatabase : public DescriptorDatabase {
public:
explicit PyDescriptorDatabase(PyObject* py_database);
~PyDescriptorDatabase();
~PyDescriptorDatabase() override;
// Implement the abstract interface. All these functions fill the output
// with a copy of FileDescriptorProto.
// Find a file by file name.
bool FindFileByName(const std::string& filename, FileDescriptorProto* output);
bool FindFileByName(const std::string& filename,
FileDescriptorProto* output) override;
// Find the file that declares the given fully-qualified symbol name.
bool FindFileContainingSymbol(const std::string& symbol_name,
FileDescriptorProto* output);
FileDescriptorProto* output) override;
// Find the file which defines an extension extending the given message type
// with the given field number.
@@ -60,14 +62,14 @@ class PyDescriptorDatabase : public DescriptorDatabase {
// Python objects are not required to implement this method.
bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
FileDescriptorProto* output);
FileDescriptorProto* output) override;
// Finds the tag numbers used by all known extensions of
// containing_type, and appends them to output in an undefined
// order.
// Python objects are not required to implement this method.
bool FindAllExtensionNumbers(const std::string& containing_type,
std::vector<int>* output);
std::vector<int>* output) override;
private:
// The python object that implements the database. The reference is owned.
@@ -32,6 +32,7 @@
#include <unordered_map>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <google/protobuf/descriptor.pb.h>
@@ -43,12 +44,13 @@
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#include <google/protobuf/stubs/hash.h>
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) \
? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == nullptr \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
namespace google {
namespace protobuf {
@@ -98,13 +100,13 @@ class BuildFileErrorCollector : public DescriptorPool::ErrorCollector {
static PyDescriptorPool* _CreateDescriptorPool() {
PyDescriptorPool* cpool = PyObject_GC_New(
PyDescriptorPool, &PyDescriptorPool_Type);
if (cpool == NULL) {
return NULL;
if (cpool == nullptr) {
return nullptr;
}
cpool->error_collector = nullptr;
cpool->underlay = NULL;
cpool->database = NULL;
cpool->underlay = nullptr;
cpool->database = nullptr;
cpool->is_owned = false;
cpool->is_mutable = false;
@@ -112,9 +114,9 @@ static PyDescriptorPool* _CreateDescriptorPool() {
cpool->py_message_factory = message_factory::NewMessageFactory(
&PyMessageFactory_Type, cpool);
if (cpool->py_message_factory == NULL) {
if (cpool->py_message_factory == nullptr) {
Py_DECREF(cpool);
return NULL;
return nullptr;
}
PyObject_GC_Track(cpool);
@@ -130,8 +132,8 @@ static PyDescriptorPool* _CreateDescriptorPool() {
static PyDescriptorPool* PyDescriptorPool_NewWithUnderlay(
const DescriptorPool* underlay) {
PyDescriptorPool* cpool = _CreateDescriptorPool();
if (cpool == NULL) {
return NULL;
if (cpool == nullptr) {
return nullptr;
}
cpool->pool = new DescriptorPool(underlay);
cpool->is_owned = true;
@@ -142,7 +144,7 @@ static PyDescriptorPool* PyDescriptorPool_NewWithUnderlay(
std::make_pair(cpool->pool, cpool)).second) {
// Should never happen -- would indicate an internal error / bug.
PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
return NULL;
return nullptr;
}
return cpool;
@@ -151,10 +153,10 @@ static PyDescriptorPool* PyDescriptorPool_NewWithUnderlay(
static PyDescriptorPool* PyDescriptorPool_NewWithDatabase(
DescriptorDatabase* database) {
PyDescriptorPool* cpool = _CreateDescriptorPool();
if (cpool == NULL) {
return NULL;
if (cpool == nullptr) {
return nullptr;
}
if (database != NULL) {
if (database != nullptr) {
cpool->error_collector = new BuildFileErrorCollector();
cpool->pool = new DescriptorPool(database, cpool->error_collector);
cpool->is_mutable = false;
@@ -168,7 +170,7 @@ static PyDescriptorPool* PyDescriptorPool_NewWithDatabase(
if (!descriptor_pool_map->insert(std::make_pair(cpool->pool, cpool)).second) {
// Should never happen -- would indicate an internal error / bug.
PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
return NULL;
return nullptr;
}
return cpool;
@@ -177,13 +179,13 @@ static PyDescriptorPool* PyDescriptorPool_NewWithDatabase(
// The public DescriptorPool constructor.
static PyObject* New(PyTypeObject* type,
PyObject* args, PyObject* kwargs) {
static const char* kwlist[] = {"descriptor_db", 0};
PyObject* py_database = NULL;
static const char* kwlist[] = {"descriptor_db", nullptr};
PyObject* py_database = nullptr;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
const_cast<char**>(kwlist), &py_database)) {
return NULL;
return nullptr;
}
DescriptorDatabase* database = NULL;
DescriptorDatabase* database = nullptr;
if (py_database && py_database != Py_None) {
database = new PyDescriptorDatabase(py_database);
}
@@ -229,24 +231,24 @@ PyObject* SetErrorFromCollector(DescriptorPool::ErrorCollector* self,
PyErr_Format(PyExc_KeyError, "Couldn't build file for %s %.200s\n%s",
error_type, name, error_collector->error_message.c_str());
error_collector->Clear();
return NULL;
return nullptr;
}
PyErr_Format(PyExc_KeyError, "Couldn't find %s %.200s", error_type, name);
return NULL;
return nullptr;
}
static PyObject* FindMessageByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const Descriptor* message_descriptor =
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindMessageTypeByName(
StringParam(name, name_size));
if (message_descriptor == NULL) {
if (message_descriptor == nullptr) {
return SetErrorFromCollector(
reinterpret_cast<PyDescriptorPool*>(self)->error_collector, name,
"message");
@@ -263,14 +265,14 @@ static PyObject* FindFileByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
PyDescriptorPool* py_pool = reinterpret_cast<PyDescriptorPool*>(self);
const FileDescriptor* file_descriptor =
py_pool->pool->FindFileByName(StringParam(name, name_size));
if (file_descriptor == NULL) {
if (file_descriptor == nullptr) {
return SetErrorFromCollector(py_pool->error_collector, name, "file");
}
return PyFileDescriptor_FromDescriptor(file_descriptor);
@@ -280,12 +282,12 @@ PyObject* FindFieldByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const FieldDescriptor* field_descriptor =
self->pool->FindFieldByName(StringParam(name, name_size));
if (field_descriptor == NULL) {
if (field_descriptor == nullptr) {
return SetErrorFromCollector(self->error_collector, name, "field");
}
@@ -301,12 +303,12 @@ PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const FieldDescriptor* field_descriptor =
self->pool->FindExtensionByName(StringParam(name, name_size));
if (field_descriptor == NULL) {
if (field_descriptor == nullptr) {
return SetErrorFromCollector(self->error_collector, name,
"extension field");
}
@@ -323,12 +325,12 @@ PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const EnumDescriptor* enum_descriptor =
self->pool->FindEnumTypeByName(StringParam(name, name_size));
if (enum_descriptor == NULL) {
if (enum_descriptor == nullptr) {
return SetErrorFromCollector(self->error_collector, name, "enum");
}
@@ -344,12 +346,12 @@ PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const OneofDescriptor* oneof_descriptor =
self->pool->FindOneofByName(StringParam(name, name_size));
if (oneof_descriptor == NULL) {
if (oneof_descriptor == nullptr) {
return SetErrorFromCollector(self->error_collector, name, "oneof");
}
@@ -365,13 +367,13 @@ static PyObject* FindServiceByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const ServiceDescriptor* service_descriptor =
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindServiceByName(
StringParam(name, name_size));
if (service_descriptor == NULL) {
if (service_descriptor == nullptr) {
return SetErrorFromCollector(
reinterpret_cast<PyDescriptorPool*>(self)->error_collector, name,
"service");
@@ -385,13 +387,13 @@ static PyObject* FindMethodByName(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const MethodDescriptor* method_descriptor =
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindMethodByName(
StringParam(name, name_size));
if (method_descriptor == NULL) {
if (method_descriptor == nullptr) {
return SetErrorFromCollector(
reinterpret_cast<PyDescriptorPool*>(self)->error_collector, name,
"method");
@@ -405,13 +407,13 @@ static PyObject* FindFileContainingSymbol(PyObject* self, PyObject* arg) {
Py_ssize_t name_size;
char* name;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
const FileDescriptor* file_descriptor =
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindFileContainingSymbol(
StringParam(name, name_size));
if (file_descriptor == NULL) {
if (file_descriptor == nullptr) {
return SetErrorFromCollector(
reinterpret_cast<PyDescriptorPool*>(self)->error_collector, name,
"symbol");
@@ -425,18 +427,18 @@ static PyObject* FindExtensionByNumber(PyObject* self, PyObject* args) {
PyObject* message_descriptor;
int number;
if (!PyArg_ParseTuple(args, "Oi", &message_descriptor, &number)) {
return NULL;
return nullptr;
}
const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor(
message_descriptor);
if (descriptor == NULL) {
return NULL;
if (descriptor == nullptr) {
return nullptr;
}
const FieldDescriptor* extension_descriptor =
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindExtensionByNumber(
descriptor, number);
if (extension_descriptor == NULL) {
if (extension_descriptor == nullptr) {
BuildFileErrorCollector* error_collector =
reinterpret_cast<BuildFileErrorCollector*>(
reinterpret_cast<PyDescriptorPool*>(self)->error_collector);
@@ -444,10 +446,10 @@ static PyObject* FindExtensionByNumber(PyObject* self, PyObject* args) {
PyErr_Format(PyExc_KeyError, "Couldn't build file for Extension %.d\n%s",
number, error_collector->error_message.c_str());
error_collector->Clear();
return NULL;
return nullptr;
}
PyErr_Format(PyExc_KeyError, "Couldn't find Extension %d", number);
return NULL;
return nullptr;
}
@@ -456,8 +458,8 @@ static PyObject* FindExtensionByNumber(PyObject* self, PyObject* args) {
static PyObject* FindAllExtensions(PyObject* self, PyObject* arg) {
const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor(arg);
if (descriptor == NULL) {
return NULL;
if (descriptor == nullptr) {
return nullptr;
}
std::vector<const FieldDescriptor*> extensions;
@@ -465,13 +467,13 @@ static PyObject* FindAllExtensions(PyObject* self, PyObject* arg) {
descriptor, &extensions);
ScopedPyObjectPtr result(PyList_New(extensions.size()));
if (result == NULL) {
return NULL;
if (result == nullptr) {
return nullptr;
}
for (int i = 0; i < extensions.size(); i++) {
PyObject* extension = PyFieldDescriptor_FromDescriptor(extensions[i]);
if (extension == NULL) {
return NULL;
if (extension == nullptr) {
return nullptr;
}
PyList_SET_ITEM(result.get(), i, extension); // Steals the reference.
}
@@ -491,7 +493,7 @@ static PyObject* AddFileDescriptor(PyObject* self, PyObject* descriptor) {
const FileDescriptor* file_descriptor =
PyFileDescriptor_AsDescriptor(descriptor);
if (!file_descriptor) {
return NULL;
return nullptr;
}
if (file_descriptor !=
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindFileByName(
@@ -499,7 +501,7 @@ static PyObject* AddFileDescriptor(PyObject* self, PyObject* descriptor) {
PyErr_Format(PyExc_ValueError,
"The file descriptor %s does not belong to this pool",
file_descriptor->name().c_str());
return NULL;
return nullptr;
}
Py_RETURN_NONE;
}
@@ -508,7 +510,7 @@ static PyObject* AddDescriptor(PyObject* self, PyObject* descriptor) {
const Descriptor* message_descriptor =
PyMessageDescriptor_AsDescriptor(descriptor);
if (!message_descriptor) {
return NULL;
return nullptr;
}
if (message_descriptor !=
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindMessageTypeByName(
@@ -516,7 +518,7 @@ static PyObject* AddDescriptor(PyObject* self, PyObject* descriptor) {
PyErr_Format(PyExc_ValueError,
"The message descriptor %s does not belong to this pool",
message_descriptor->full_name().c_str());
return NULL;
return nullptr;
}
Py_RETURN_NONE;
}
@@ -525,7 +527,7 @@ static PyObject* AddEnumDescriptor(PyObject* self, PyObject* descriptor) {
const EnumDescriptor* enum_descriptor =
PyEnumDescriptor_AsDescriptor(descriptor);
if (!enum_descriptor) {
return NULL;
return nullptr;
}
if (enum_descriptor !=
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindEnumTypeByName(
@@ -533,7 +535,7 @@ static PyObject* AddEnumDescriptor(PyObject* self, PyObject* descriptor) {
PyErr_Format(PyExc_ValueError,
"The enum descriptor %s does not belong to this pool",
enum_descriptor->full_name().c_str());
return NULL;
return nullptr;
}
Py_RETURN_NONE;
}
@@ -542,7 +544,7 @@ static PyObject* AddExtensionDescriptor(PyObject* self, PyObject* descriptor) {
const FieldDescriptor* extension_descriptor =
PyFieldDescriptor_AsDescriptor(descriptor);
if (!extension_descriptor) {
return NULL;
return nullptr;
}
if (extension_descriptor !=
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindExtensionByName(
@@ -550,7 +552,7 @@ static PyObject* AddExtensionDescriptor(PyObject* self, PyObject* descriptor) {
PyErr_Format(PyExc_ValueError,
"The extension descriptor %s does not belong to this pool",
extension_descriptor->full_name().c_str());
return NULL;
return nullptr;
}
Py_RETURN_NONE;
}
@@ -559,7 +561,7 @@ static PyObject* AddServiceDescriptor(PyObject* self, PyObject* descriptor) {
const ServiceDescriptor* service_descriptor =
PyServiceDescriptor_AsDescriptor(descriptor);
if (!service_descriptor) {
return NULL;
return nullptr;
}
if (service_descriptor !=
reinterpret_cast<PyDescriptorPool*>(self)->pool->FindServiceByName(
@@ -567,7 +569,7 @@ static PyObject* AddServiceDescriptor(PyObject* self, PyObject* descriptor) {
PyErr_Format(PyExc_ValueError,
"The service descriptor %s does not belong to this pool",
service_descriptor->full_name().c_str());
return NULL;
return nullptr;
}
Py_RETURN_NONE;
}
@@ -578,12 +580,12 @@ static PyObject* AddSerializedFile(PyObject* pself, PyObject* serialized_pb) {
char* message_type;
Py_ssize_t message_len;
if (self->database != NULL) {
if (self->database != nullptr) {
PyErr_SetString(
PyExc_ValueError,
"Cannot call Add on a DescriptorPool that uses a DescriptorDatabase. "
"Add your file to the underlying database.");
return NULL;
return nullptr;
}
if (!self->is_mutable) {
PyErr_SetString(
@@ -593,22 +595,22 @@ static PyObject* AddSerializedFile(PyObject* pself, PyObject* serialized_pb) {
}
if (PyBytes_AsStringAndSize(serialized_pb, &message_type, &message_len) < 0) {
return NULL;
return nullptr;
}
FileDescriptorProto file_proto;
if (!file_proto.ParseFromArray(message_type, message_len)) {
PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!");
return NULL;
return nullptr;
}
// If the file was already part of a C++ library, all its descriptors are in
// the underlying pool. No need to do anything else.
const FileDescriptor* generated_file = NULL;
const FileDescriptor* generated_file = nullptr;
if (self->underlay) {
generated_file = self->underlay->FindFileByName(file_proto.name());
}
if (generated_file != NULL) {
if (generated_file != nullptr) {
return PyFileDescriptor_FromDescriptorWithSerializedPb(
generated_file, serialized_pb);
}
@@ -618,11 +620,11 @@ static PyObject* AddSerializedFile(PyObject* pself, PyObject* serialized_pb) {
// Pool is mutable, we can remove the "const".
const_cast<DescriptorPool*>(self->pool)
->BuildFileCollectingErrors(file_proto, &error_collector);
if (descriptor == NULL) {
if (descriptor == nullptr) {
PyErr_Format(PyExc_TypeError,
"Couldn't build proto file into descriptor pool!\n%s",
error_collector.error_message.c_str());
return NULL;
return nullptr;
}
@@ -632,105 +634,109 @@ static PyObject* AddSerializedFile(PyObject* pself, PyObject* serialized_pb) {
static PyObject* Add(PyObject* self, PyObject* file_descriptor_proto) {
ScopedPyObjectPtr serialized_pb(
PyObject_CallMethod(file_descriptor_proto, "SerializeToString", NULL));
if (serialized_pb == NULL) {
return NULL;
PyObject_CallMethod(file_descriptor_proto, "SerializeToString", nullptr));
if (serialized_pb == nullptr) {
return nullptr;
}
return AddSerializedFile(self, serialized_pb.get());
}
static PyMethodDef Methods[] = {
{ "Add", Add, METH_O,
"Adds the FileDescriptorProto and its types to this pool." },
{ "AddSerializedFile", AddSerializedFile, METH_O,
"Adds a serialized FileDescriptorProto to this pool." },
{"Add", Add, METH_O,
"Adds the FileDescriptorProto and its types to this pool."},
{"AddSerializedFile", AddSerializedFile, METH_O,
"Adds a serialized FileDescriptorProto to this pool."},
// TODO(amauryfa): Understand why the Python implementation differs from
// this one, ask users to use another API and deprecate these functions.
{ "AddFileDescriptor", AddFileDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddDescriptor", AddDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddEnumDescriptor", AddEnumDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddExtensionDescriptor", AddExtensionDescriptor, METH_O,
"No-op. Add() must have been called before." },
{ "AddServiceDescriptor", AddServiceDescriptor, METH_O,
"No-op. Add() must have been called before." },
// TODO(amauryfa): Understand why the Python implementation differs from
// this one, ask users to use another API and deprecate these functions.
{"AddFileDescriptor", AddFileDescriptor, METH_O,
"No-op. Add() must have been called before."},
{"AddDescriptor", AddDescriptor, METH_O,
"No-op. Add() must have been called before."},
{"AddEnumDescriptor", AddEnumDescriptor, METH_O,
"No-op. Add() must have been called before."},
{"AddExtensionDescriptor", AddExtensionDescriptor, METH_O,
"No-op. Add() must have been called before."},
{"AddServiceDescriptor", AddServiceDescriptor, METH_O,
"No-op. Add() must have been called before."},
{ "FindFileByName", FindFileByName, METH_O,
"Searches for a file descriptor by its .proto name." },
{ "FindMessageTypeByName", FindMessageByName, METH_O,
"Searches for a message descriptor by full name." },
{ "FindFieldByName", FindFieldByNameMethod, METH_O,
"Searches for a field descriptor by full name." },
{ "FindExtensionByName", FindExtensionByNameMethod, METH_O,
"Searches for extension descriptor by full name." },
{ "FindEnumTypeByName", FindEnumTypeByNameMethod, METH_O,
"Searches for enum type descriptor by full name." },
{ "FindOneofByName", FindOneofByNameMethod, METH_O,
"Searches for oneof descriptor by full name." },
{ "FindServiceByName", FindServiceByName, METH_O,
"Searches for service descriptor by full name." },
{ "FindMethodByName", FindMethodByName, METH_O,
"Searches for method descriptor by full name." },
{"FindFileByName", FindFileByName, METH_O,
"Searches for a file descriptor by its .proto name."},
{"FindMessageTypeByName", FindMessageByName, METH_O,
"Searches for a message descriptor by full name."},
{"FindFieldByName", FindFieldByNameMethod, METH_O,
"Searches for a field descriptor by full name."},
{"FindExtensionByName", FindExtensionByNameMethod, METH_O,
"Searches for extension descriptor by full name."},
{"FindEnumTypeByName", FindEnumTypeByNameMethod, METH_O,
"Searches for enum type descriptor by full name."},
{"FindOneofByName", FindOneofByNameMethod, METH_O,
"Searches for oneof descriptor by full name."},
{"FindServiceByName", FindServiceByName, METH_O,
"Searches for service descriptor by full name."},
{"FindMethodByName", FindMethodByName, METH_O,
"Searches for method descriptor by full name."},
{ "FindFileContainingSymbol", FindFileContainingSymbol, METH_O,
"Gets the FileDescriptor containing the specified symbol." },
{ "FindExtensionByNumber", FindExtensionByNumber, METH_VARARGS,
"Gets the extension descriptor for the given number." },
{ "FindAllExtensions", FindAllExtensions, METH_O,
"Gets all known extensions of the given message descriptor." },
{NULL}
{"FindFileContainingSymbol", FindFileContainingSymbol, METH_O,
"Gets the FileDescriptor containing the specified symbol."},
{"FindExtensionByNumber", FindExtensionByNumber, METH_VARARGS,
"Gets the extension descriptor for the given number."},
{"FindAllExtensions", FindAllExtensions, METH_O,
"Gets all known extensions of the given message descriptor."},
{nullptr},
};
} // namespace cdescriptor_pool
PyTypeObject PyDescriptorPool_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".DescriptorPool", // tp_name
sizeof(PyDescriptorPool), // tp_basicsize
0, // tp_itemsize
cdescriptor_pool::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
".DescriptorPool", // tp_name
sizeof(PyDescriptorPool), // tp_basicsize
0, // tp_itemsize
cdescriptor_pool::Dealloc, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags
"A Descriptor Pool", // tp_doc
cdescriptor_pool::GcTraverse, // tp_traverse
cdescriptor_pool::GcClear, // tp_clear
0, // tp_richcompare
nullptr, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
nullptr, // tp_iter
nullptr, // tp_iternext
cdescriptor_pool::Methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
nullptr, // tp_init
nullptr, // tp_alloc
cdescriptor_pool::New, // tp_new
PyObject_GC_Del, // tp_free
};
// This is the DescriptorPool which contains all the definitions from the
// generated _pb2.py modules.
static PyDescriptorPool* python_generated_pool = NULL;
static PyDescriptorPool* python_generated_pool = nullptr;
bool InitDescriptorPool() {
if (PyType_Ready(&PyDescriptorPool_Type) < 0)
@@ -743,7 +749,7 @@ bool InitDescriptorPool() {
new std::unordered_map<const DescriptorPool*, PyDescriptorPool*>;
python_generated_pool = cdescriptor_pool::PyDescriptorPool_NewWithUnderlay(
DescriptorPool::generated_pool());
if (python_generated_pool == NULL) {
if (python_generated_pool == nullptr) {
delete descriptor_pool_map;
return false;
}
@@ -774,7 +780,7 @@ PyDescriptorPool* GetDescriptorPool_FromPool(const DescriptorPool* pool) {
descriptor_pool_map->find(pool);
if (it == descriptor_pool_map->end()) {
PyErr_SetString(PyExc_KeyError, "Unknown descriptor pool");
return NULL;
return nullptr;
}
return it->second;
}
@@ -31,6 +31,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_POOL_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_POOL_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <unordered_map>
@@ -49,12 +49,13 @@
#include <google/protobuf/pyext/repeated_scalar_container.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) \
? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == nullptr \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
namespace google {
namespace protobuf {
@@ -130,11 +131,11 @@ static void DeallocExtensionIterator(PyObject* _self) {
PyObject* subscript(ExtensionDict* self, PyObject* key) {
const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key);
if (descriptor == NULL) {
return NULL;
if (descriptor == nullptr) {
return nullptr;
}
if (!CheckFieldBelongsToMessage(descriptor, self->parent->message)) {
return NULL;
return nullptr;
}
if (descriptor->label() != FieldDescriptor::LABEL_REPEATED &&
@@ -154,8 +155,8 @@ PyObject* subscript(ExtensionDict* self, PyObject* key) {
// TODO(plabatut): consider building the class on the fly!
ContainerBase* sub_message = cmessage::InternalGetSubMessage(
self->parent, descriptor);
if (sub_message == NULL) {
return NULL;
if (sub_message == nullptr) {
return nullptr;
}
(*self->parent->composite_fields)[descriptor] = sub_message;
return sub_message->AsPyObject();
@@ -178,33 +179,33 @@ PyObject* subscript(ExtensionDict* self, PyObject* key) {
descriptor->message_type());
ScopedPyObjectPtr message_class_handler(
reinterpret_cast<PyObject*>(message_class));
if (message_class == NULL) {
return NULL;
if (message_class == nullptr) {
return nullptr;
}
ContainerBase* py_container = repeated_composite_container::NewContainer(
self->parent, descriptor, message_class);
if (py_container == NULL) {
return NULL;
if (py_container == nullptr) {
return nullptr;
}
(*self->parent->composite_fields)[descriptor] = py_container;
return py_container->AsPyObject();
} else {
ContainerBase* py_container = repeated_scalar_container::NewContainer(
self->parent, descriptor);
if (py_container == NULL) {
return NULL;
if (py_container == nullptr) {
return nullptr;
}
(*self->parent->composite_fields)[descriptor] = py_container;
return py_container->AsPyObject();
}
}
PyErr_SetString(PyExc_ValueError, "control reached unexpected line");
return NULL;
return nullptr;
}
int ass_subscript(ExtensionDict* self, PyObject* key, PyObject* value) {
const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key);
if (descriptor == NULL) {
if (descriptor == nullptr) {
return -1;
}
if (!CheckFieldBelongsToMessage(descriptor, self->parent->message)) {
@@ -232,13 +233,13 @@ PyObject* _FindExtensionByName(ExtensionDict* self, PyObject* arg) {
char* name;
Py_ssize_t name_size;
if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) {
return NULL;
return nullptr;
}
PyDescriptorPool* pool = cmessage::GetFactoryForMessage(self->parent)->pool;
const FieldDescriptor* message_extension =
pool->pool->FindExtensionByName(StringParam(name, name_size));
if (message_extension == NULL) {
if (message_extension == nullptr) {
// Is is the name of a message set extension?
const Descriptor* message_descriptor =
pool->pool->FindMessageTypeByName(StringParam(name, name_size));
@@ -252,7 +253,7 @@ PyObject* _FindExtensionByName(ExtensionDict* self, PyObject* arg) {
}
}
}
if (message_extension == NULL) {
if (message_extension == nullptr) {
Py_RETURN_NONE;
}
@@ -262,13 +263,13 @@ PyObject* _FindExtensionByName(ExtensionDict* self, PyObject* arg) {
PyObject* _FindExtensionByNumber(ExtensionDict* self, PyObject* arg) {
int64_t number = PyLong_AsLong(arg);
if (number == -1 && PyErr_Occurred()) {
return NULL;
return nullptr;
}
PyDescriptorPool* pool = cmessage::GetFactoryForMessage(self->parent)->pool;
const FieldDescriptor* message_extension = pool->pool->FindExtensionByNumber(
self->parent->message->GetDescriptor(), number);
if (message_extension == NULL) {
if (message_extension == nullptr) {
Py_RETURN_NONE;
}
@@ -307,8 +308,8 @@ static int Contains(PyObject* _self, PyObject* key) {
ExtensionDict* NewExtensionDict(CMessage *parent) {
ExtensionDict* self = reinterpret_cast<ExtensionDict*>(
PyType_GenericAlloc(&ExtensionDict_Type, 0));
if (self == NULL) {
return NULL;
if (self == nullptr) {
return nullptr;
}
Py_INCREF(parent);
@@ -330,7 +331,7 @@ static PyObject* RichCompare(ExtensionDict* self, PyObject* other, int opid) {
}
bool equals = false;
if (PyObject_TypeCheck(other, &ExtensionDict_Type)) {
equals = self->parent == reinterpret_cast<ExtensionDict*>(other)->parent;;
equals = self->parent == reinterpret_cast<ExtensionDict*>(other)->parent;
}
if (equals ^ (opid == Py_EQ)) {
Py_RETURN_FALSE;
@@ -340,12 +341,12 @@ static PyObject* RichCompare(ExtensionDict* self, PyObject* other, int opid) {
}
static PySequenceMethods SeqMethods = {
(lenfunc)len, // sq_length
0, // sq_concat
0, // sq_repeat
0, // sq_item
0, // sq_slice
0, // sq_ass_item
0, // sq_ass_slice
nullptr, // sq_concat
nullptr, // sq_repeat
nullptr, // sq_item
nullptr, // sq_slice
nullptr, // sq_ass_item
nullptr, // sq_ass_slice
(objobjproc)Contains, // sq_contains
};
@@ -360,48 +361,52 @@ static PyMethodDef Methods[] = {
EDMETHOD(_FindExtensionByName, METH_O, "Finds an extension by name."),
EDMETHOD(_FindExtensionByNumber, METH_O,
"Finds an extension by field number."),
{NULL, NULL},
{nullptr, nullptr},
};
} // namespace extension_dict
PyTypeObject ExtensionDict_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) //
FULL_MODULE_NAME ".ExtensionDict", // tp_name
sizeof(ExtensionDict), // tp_basicsize
0, // tp_itemsize
(destructor)extension_dict::dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
PyVarObject_HEAD_INIT(&PyType_Type, 0) //
FULL_MODULE_NAME ".ExtensionDict", // tp_name
sizeof(ExtensionDict), // tp_basicsize
0, // tp_itemsize
(destructor)extension_dict::dealloc, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
&extension_dict::SeqMethods, // tp_as_sequence
&extension_dict::MpMethods, // tp_as_mapping
PyObject_HashNotImplemented, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"An extension dict", // tp_doc
0, // tp_traverse
0, // tp_clear
nullptr, // tp_traverse
nullptr, // tp_clear
(richcmpfunc)extension_dict::RichCompare, // tp_richcompare
0, // tp_weaklistoffset
extension_dict::GetIter, // tp_iter
0, // tp_iternext
nullptr, // tp_iternext
extension_dict::Methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
nullptr, // tp_init
};
PyObject* IterNext(PyObject* _self) {
@@ -438,37 +443,41 @@ PyTypeObject ExtensionIterator_Type = {
sizeof(extension_dict::ExtensionIterator), // tp_basicsize
0, // tp_itemsize
extension_dict::DeallocExtensionIterator, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"A scalar map iterator", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
PyObject_SelfIter, // tp_iter
IterNext, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"A scalar map iterator", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
PyObject_SelfIter, // tp_iter
IterNext, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
};
} // namespace python
} // namespace protobuf
@@ -34,10 +34,9 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_EXTENSION_DICT_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_EXTENSION_DICT_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <memory>
#include <google/protobuf/pyext/message.h>
namespace google {
+50 -45
View File
@@ -47,7 +47,7 @@ static PyObject* Repr(PyMessageFieldProperty* self) {
static PyObject* DescrGet(PyMessageFieldProperty* self, PyObject* obj,
PyObject* type) {
if (obj == NULL) {
if (obj == nullptr) {
Py_INCREF(self);
return reinterpret_cast<PyObject*>(self);
}
@@ -57,7 +57,7 @@ static PyObject* DescrGet(PyMessageFieldProperty* self, PyObject* obj,
static int DescrSet(PyMessageFieldProperty* self, PyObject* obj,
PyObject* value) {
if (value == NULL) {
if (value == nullptr) {
PyErr_SetString(PyExc_AttributeError, "Cannot delete field attribute");
return -1;
}
@@ -75,50 +75,55 @@ static PyObject* GetDoc(PyMessageFieldProperty* self, void* closure) {
}
static PyGetSetDef Getters[] = {
{"DESCRIPTOR", (getter)GetDescriptor, NULL, "Field descriptor"},
{"__doc__", (getter)GetDoc, NULL, NULL},
{NULL}};
{"DESCRIPTOR", (getter)GetDescriptor, nullptr, "Field descriptor"},
{"__doc__", (getter)GetDoc, nullptr, nullptr},
{nullptr},
};
} // namespace field
static PyTypeObject _CFieldProperty_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) // head
FULL_MODULE_NAME ".FieldProperty", // tp_name
sizeof(PyMessageFieldProperty), // tp_basicsize
0, // tp_itemsize
0, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
(reprfunc)field::Repr, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"Field property of a Message", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
field::Getters, // tp_getset
0, // tp_base
0, // tp_dict
(descrgetfunc)field::DescrGet, // tp_descr_get
(descrsetfunc)field::DescrSet, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
0, // tp_new
PyVarObject_HEAD_INIT(&PyType_Type, 0) // head
FULL_MODULE_NAME ".FieldProperty", // tp_name
sizeof(PyMessageFieldProperty), // tp_basicsize
0, // tp_itemsize
nullptr, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
(reprfunc)field::Repr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"Field property of a Message", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
field::Getters, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
(descrgetfunc)field::DescrGet, // tp_descr_get
(descrsetfunc)field::DescrSet, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
nullptr, // tp_alloc
nullptr, // tp_new
};
PyTypeObject* CFieldProperty_Type = &_CFieldProperty_Type;
@@ -126,8 +131,8 @@ PyObject* NewFieldProperty(const FieldDescriptor* field_descriptor) {
// Create a new descriptor object
PyMessageFieldProperty* property =
PyObject_New(PyMessageFieldProperty, CFieldProperty_Type);
if (property == NULL) {
return NULL;
if (property == nullptr) {
return nullptr;
}
property->field_descriptor = field_descriptor;
return reinterpret_cast<PyObject*>(property);
@@ -31,6 +31,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_FIELD_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_FIELD_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
namespace google {
@@ -187,7 +187,7 @@ static PyObject* MapKeyToPython(MapContainer* self, const MapKey& key) {
PyErr_Format(
PyExc_SystemError, "Couldn't convert type %d to value",
field_descriptor->cpp_type());
return NULL;
return nullptr;
}
}
@@ -219,7 +219,7 @@ PyObject* MapValueRefToPython(MapContainer* self, const MapValueRef& value) {
PyErr_Format(
PyExc_SystemError, "Couldn't convert type %d to value",
field_descriptor->cpp_type());
return NULL;
return nullptr;
}
}
@@ -264,7 +264,7 @@ static bool PythonToMapValueRef(MapContainer* self, PyObject* obj,
case FieldDescriptor::CPPTYPE_BOOL: {
GOOGLE_CHECK_GET_BOOL(obj, value, false);
value_ref->SetBoolValue(value);
return true;;
return true;
}
case FieldDescriptor::CPPTYPE_STRING: {
std::string str;
@@ -283,7 +283,7 @@ static bool PythonToMapValueRef(MapContainer* self, PyObject* obj,
const EnumDescriptor* enum_descriptor = field_descriptor->enum_type();
const EnumValueDescriptor* enum_value =
enum_descriptor->FindValueByNumber(value);
if (enum_value != NULL) {
if (enum_value != nullptr) {
value_ref->SetEnumValue(value);
return true;
} else {
@@ -362,7 +362,7 @@ PyObject* MapReflectionFriend::Contains(PyObject* _self, PyObject* key) {
MapKey map_key;
if (!PythonToMapKey(self, key, &map_key)) {
return NULL;
return nullptr;
}
if (reflection->ContainsMapKey(*message, self->parent_field_descriptor,
@@ -378,14 +378,14 @@ PyObject* MapReflectionFriend::Contains(PyObject* _self, PyObject* key) {
MapContainer* NewScalarMapContainer(
CMessage* parent, const google::protobuf::FieldDescriptor* parent_field_descriptor) {
if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
return NULL;
return nullptr;
}
PyObject* obj(PyType_GenericAlloc(ScalarMapContainer_Type, 0));
if (obj == NULL) {
if (obj == nullptr) {
PyErr_Format(PyExc_RuntimeError,
"Could not allocate new container.");
return NULL;
return nullptr;
}
MapContainer* self = GetMap(obj);
@@ -408,7 +408,7 @@ PyObject* MapReflectionFriend::ScalarMapGetItem(PyObject* _self,
MapValueRef value;
if (!PythonToMapKey(self, key, &map_key)) {
return NULL;
return nullptr;
}
if (reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
@@ -432,12 +432,12 @@ int MapReflectionFriend::ScalarMapSetItem(PyObject* _self, PyObject* key,
return -1;
}
self->version++;
if (v) {
// Set item to v.
reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
map_key, &value);
if (reflection->InsertOrLookupMapValue(
message, self->parent_field_descriptor, map_key, &value)) {
self->version++;
}
if (!PythonToMapValueRef(self, v, reflection->SupportsUnknownEnumValues(),
&value)) {
@@ -448,6 +448,7 @@ int MapReflectionFriend::ScalarMapSetItem(PyObject* _self, PyObject* key,
// Delete key from map.
if (reflection->DeleteMapValue(message, self->parent_field_descriptor,
map_key)) {
self->version++;
return 0;
} else {
PyErr_Format(PyExc_KeyError, "Key not present in map");
@@ -460,22 +461,22 @@ static PyObject* ScalarMapGet(PyObject* self, PyObject* args,
PyObject* kwargs) {
static const char* kwlist[] = {"key", "default", nullptr};
PyObject* key;
PyObject* default_value = NULL;
PyObject* default_value = nullptr;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O",
const_cast<char**>(kwlist), &key,
&default_value)) {
return NULL;
return nullptr;
}
ScopedPyObjectPtr is_present(MapReflectionFriend::Contains(self, key));
if (is_present.get() == NULL) {
return NULL;
if (is_present.get() == nullptr) {
return nullptr;
}
if (PyObject_IsTrue(is_present.get())) {
return MapReflectionFriend::ScalarMapGetItem(self, key);
} else {
if (default_value != NULL) {
if (default_value != nullptr) {
Py_INCREF(default_value);
return default_value;
} else {
@@ -486,8 +487,8 @@ static PyObject* ScalarMapGet(PyObject* self, PyObject* args,
PyObject* MapReflectionFriend::ScalarMapToStr(PyObject* _self) {
ScopedPyObjectPtr dict(PyDict_New());
if (dict == NULL) {
return NULL;
if (dict == nullptr) {
return nullptr;
}
ScopedPyObjectPtr key;
ScopedPyObjectPtr value;
@@ -500,15 +501,15 @@ PyObject* MapReflectionFriend::ScalarMapToStr(PyObject* _self) {
it != reflection->MapEnd(message, self->parent_field_descriptor);
++it) {
key.reset(MapKeyToPython(self, it.GetKey()));
if (key == NULL) {
return NULL;
if (key == nullptr) {
return nullptr;
}
value.reset(MapValueRefToPython(self, it.GetValueRef()));
if (value == NULL) {
return NULL;
if (value == nullptr) {
return nullptr;
}
if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
return NULL;
return nullptr;
}
}
return PyObject_Repr(dict.get());
@@ -542,7 +543,7 @@ static PyMethodDef ScalarMapMethods[] = {
{ "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
"Outputs picklable representation of the repeated field." },
*/
{NULL, NULL},
{nullptr, nullptr},
};
PyTypeObject* ScalarMapContainer_Type;
@@ -554,7 +555,7 @@ static PyType_Slot ScalarMapContainer_Type_slots[] = {
{Py_tp_methods, (void*)ScalarMapMethods},
{Py_tp_iter, (void*)MapReflectionFriend::GetIterator},
{Py_tp_repr, (void*)MapReflectionFriend::ScalarMapToStr},
{0, 0},
{0, nullptr},
};
PyType_Spec ScalarMapContainer_Type_spec = {
@@ -579,13 +580,13 @@ MessageMapContainer* NewMessageMapContainer(
CMessage* parent, const google::protobuf::FieldDescriptor* parent_field_descriptor,
CMessageClass* message_class) {
if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
return NULL;
return nullptr;
}
PyObject* obj = PyType_GenericAlloc(MessageMapContainer_Type, 0);
if (obj == NULL) {
if (obj == nullptr) {
PyErr_SetString(PyExc_RuntimeError, "Could not allocate new container.");
return NULL;
return nullptr;
}
MessageMapContainer* self = GetMessageMap(obj);
@@ -660,7 +661,7 @@ PyObject* MapReflectionFriend::MessageMapGetItem(PyObject* _self,
MapValueRef value;
if (!PythonToMapKey(self, key, &map_key)) {
return NULL;
return nullptr;
}
if (reflection->InsertOrLookupMapValue(message, self->parent_field_descriptor,
@@ -673,8 +674,8 @@ PyObject* MapReflectionFriend::MessageMapGetItem(PyObject* _self,
PyObject* MapReflectionFriend::MessageMapToStr(PyObject* _self) {
ScopedPyObjectPtr dict(PyDict_New());
if (dict == NULL) {
return NULL;
if (dict == nullptr) {
return nullptr;
}
ScopedPyObjectPtr key;
ScopedPyObjectPtr value;
@@ -687,15 +688,15 @@ PyObject* MapReflectionFriend::MessageMapToStr(PyObject* _self) {
it != reflection->MapEnd(message, self->parent_field_descriptor);
++it) {
key.reset(MapKeyToPython(self, it.GetKey()));
if (key == NULL) {
return NULL;
if (key == nullptr) {
return nullptr;
}
value.reset(GetCMessage(self, it.MutableValueRef()->MutableMessageValue()));
if (value == NULL) {
return NULL;
if (value == nullptr) {
return nullptr;
}
if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
return NULL;
return nullptr;
}
}
return PyObject_Repr(dict.get());
@@ -704,22 +705,22 @@ PyObject* MapReflectionFriend::MessageMapToStr(PyObject* _self) {
PyObject* MessageMapGet(PyObject* self, PyObject* args, PyObject* kwargs) {
static const char* kwlist[] = {"key", "default", nullptr};
PyObject* key;
PyObject* default_value = NULL;
PyObject* default_value = nullptr;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O",
const_cast<char**>(kwlist), &key,
&default_value)) {
return NULL;
return nullptr;
}
ScopedPyObjectPtr is_present(MapReflectionFriend::Contains(self, key));
if (is_present.get() == NULL) {
return NULL;
if (is_present.get() == nullptr) {
return nullptr;
}
if (PyObject_IsTrue(is_present.get())) {
return MapReflectionFriend::MessageMapGetItem(self, key);
} else {
if (default_value != NULL) {
if (default_value != nullptr) {
Py_INCREF(default_value);
return default_value;
} else {
@@ -759,7 +760,7 @@ static PyMethodDef MessageMapMethods[] = {
{ "__reduce__", (PyCFunction)Reduce, METH_NOARGS,
"Outputs picklable representation of the repeated field." },
*/
{NULL, NULL},
{nullptr, nullptr},
};
PyTypeObject* MessageMapContainer_Type;
@@ -771,7 +772,7 @@ static PyType_Slot MessageMapContainer_Type_slots[] = {
{Py_tp_methods, (void*)MessageMapMethods},
{Py_tp_iter, (void*)MapReflectionFriend::GetIterator},
{Py_tp_repr, (void*)MapReflectionFriend::MessageMapToStr},
{0, 0}};
{0, nullptr}};
PyType_Spec MessageMapContainer_Type_spec = {
FULL_MODULE_NAME ".MessageMapContainer", sizeof(MessageMapContainer), 0,
@@ -787,7 +788,7 @@ PyObject* MapReflectionFriend::GetIterator(PyObject *_self) {
MapContainer* self = GetMap(_self);
ScopedPyObjectPtr obj(PyType_GenericAlloc(&MapIterator_Type, 0));
if (obj == NULL) {
if (obj == nullptr) {
return PyErr_Format(PyExc_KeyError, "Could not allocate iterator");
}
@@ -824,8 +825,8 @@ PyObject* MapReflectionFriend::IterNext(PyObject* _self) {
"Map cleared during iteration.");
}
if (self->iter.get() == NULL) {
return NULL;
if (self->iter.get() == nullptr) {
return nullptr;
}
Message* message = self->container->GetMutableMessage();
@@ -833,7 +834,7 @@ PyObject* MapReflectionFriend::IterNext(PyObject* _self) {
if (*self->iter ==
reflection->MapEnd(message, self->container->parent_field_descriptor)) {
return NULL;
return nullptr;
}
PyObject* ret = MapKeyToPython(self->container, self->iter->GetKey());
@@ -852,60 +853,64 @@ static void DeallocMapIterator(PyObject* _self) {
}
PyTypeObject MapIterator_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
FULL_MODULE_NAME ".MapIterator", // tp_name
sizeof(MapIterator), // tp_basicsize
0, // tp_itemsize
DeallocMapIterator, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"A scalar map iterator", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
PyObject_SelfIter, // tp_iter
MapReflectionFriend::IterNext, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".MapIterator", // tp_name
sizeof(MapIterator), // tp_basicsize
0, // tp_itemsize
DeallocMapIterator, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"A scalar map iterator", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
PyObject_SelfIter, // tp_iter
MapReflectionFriend::IterNext, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
};
bool InitMapContainers() {
// ScalarMapContainer_Type derives from our MutableMapping type.
ScopedPyObjectPtr abc(PyImport_ImportModule("collections.abc"));
if (abc == NULL) {
if (abc == nullptr) {
return false;
}
ScopedPyObjectPtr mutable_mapping(
PyObject_GetAttrString(abc.get(), "MutableMapping"));
if (mutable_mapping == NULL) {
if (mutable_mapping == nullptr) {
return false;
}
Py_INCREF(mutable_mapping.get());
ScopedPyObjectPtr bases(PyTuple_Pack(1, mutable_mapping.get()));
if (bases == NULL) {
if (bases == nullptr) {
return false;
}
@@ -31,10 +31,10 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_MAP_CONTAINER_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_MAP_CONTAINER_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <cstdint>
#include <memory>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
File diff suppressed because it is too large. Load diff
@@ -34,6 +34,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <cstdint>
@@ -30,6 +30,7 @@
#include <unordered_map>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <google/protobuf/dynamic_message.h>
@@ -38,12 +39,13 @@
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) \
? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == nullptr \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
namespace google {
namespace protobuf {
@@ -54,8 +56,8 @@ namespace message_factory {
PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool) {
PyMessageFactory* factory = reinterpret_cast<PyMessageFactory*>(
PyType_GenericAlloc(type, 0));
if (factory == NULL) {
return NULL;
if (factory == nullptr) {
return nullptr;
}
DynamicMessageFactory* message_factory = new DynamicMessageFactory();
@@ -72,25 +74,25 @@ PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool)
}
PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
static const char* kwlist[] = {"pool", 0};
PyObject* pool = NULL;
static const char* kwlist[] = {"pool", nullptr};
PyObject* pool = nullptr;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
const_cast<char**>(kwlist), &pool)) {
return NULL;
return nullptr;
}
ScopedPyObjectPtr owned_pool;
if (pool == NULL || pool == Py_None) {
if (pool == nullptr || pool == Py_None) {
owned_pool.reset(PyObject_CallFunction(
reinterpret_cast<PyObject*>(&PyDescriptorPool_Type), NULL));
if (owned_pool == NULL) {
return NULL;
reinterpret_cast<PyObject*>(&PyDescriptorPool_Type), nullptr));
if (owned_pool == nullptr) {
return nullptr;
}
pool = owned_pool.get();
} else {
if (!PyObject_TypeCheck(pool, &PyDescriptorPool_Type)) {
PyErr_Format(PyExc_TypeError, "Expected a DescriptorPool, got %s",
pool->ob_type->tp_name);
return NULL;
return nullptr;
}
}
@@ -161,8 +163,8 @@ CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
}
ScopedPyObjectPtr py_descriptor(
PyMessageDescriptor_FromDescriptor(descriptor));
if (py_descriptor == NULL) {
return NULL;
if (py_descriptor == nullptr) {
return nullptr;
}
// Create a new message class.
ScopedPyObjectPtr args(Py_BuildValue(
@@ -170,24 +172,24 @@ CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
"DESCRIPTOR", py_descriptor.get(),
"__module__", Py_None,
"message_factory", self));
if (args == NULL) {
return NULL;
if (args == nullptr) {
return nullptr;
}
ScopedPyObjectPtr message_class(PyObject_CallObject(
reinterpret_cast<PyObject*>(CMessageClass_Type), args.get()));
if (message_class == NULL) {
return NULL;
if (message_class == nullptr) {
return nullptr;
}
// Create messages class for the messages used by the fields, and registers
// all extensions for these messages during the recursion.
for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) {
const Descriptor* sub_descriptor =
descriptor->field(field_idx)->message_type();
// It is NULL if the field type is not a message.
if (sub_descriptor != NULL) {
// It is null if the field type is not a message.
if (sub_descriptor != nullptr) {
CMessageClass* result = GetOrCreateMessageClass(self, sub_descriptor);
if (result == NULL) {
return NULL;
if (result == nullptr) {
return nullptr;
}
Py_DECREF(result);
}
@@ -199,17 +201,17 @@ CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
ScopedPyObjectPtr py_extended_class(
GetOrCreateMessageClass(self, extension->containing_type())
->AsPyObject());
if (py_extended_class == NULL) {
return NULL;
if (py_extended_class == nullptr) {
return nullptr;
}
ScopedPyObjectPtr py_extension(PyFieldDescriptor_FromDescriptor(extension));
if (py_extension == NULL) {
return NULL;
if (py_extension == nullptr) {
return nullptr;
}
ScopedPyObjectPtr result(cmessage::RegisterExtension(
py_extended_class.get(), py_extension.get()));
if (result == NULL) {
return NULL;
if (result == nullptr) {
return nullptr;
}
}
return reinterpret_cast<CMessageClass*>(message_class.release());
@@ -223,14 +225,15 @@ CMessageClass* GetMessageClass(PyMessageFactory* self,
if (ret == self->classes_by_descriptor->end()) {
PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
message_descriptor->full_name().c_str());
return NULL;
return nullptr;
} else {
return ret->second;
}
}
static PyMethodDef Methods[] = {
{NULL}};
{nullptr},
};
static PyObject* GetPool(PyMessageFactory* self, void* closure) {
Py_INCREF(self->pool);
@@ -238,8 +241,8 @@ static PyObject* GetPool(PyMessageFactory* self, void* closure) {
}
static PyGetSetDef Getters[] = {
{"pool", (getter)GetPool, NULL, "DescriptorPool"},
{NULL}
{"pool", (getter)GetPool, nullptr, "DescriptorPool"},
{nullptr},
};
} // namespace message_factory
@@ -250,38 +253,42 @@ PyTypeObject PyMessageFactory_Type = {
sizeof(PyMessageFactory), // tp_basicsize
0, // tp_itemsize
message_factory::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, // tp_flags
"A static Message Factory", // tp_doc
message_factory::GcTraverse, // tp_traverse
message_factory::GcClear, // tp_clear
0, // tp_richcompare
nullptr, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
nullptr, // tp_iter
nullptr, // tp_iternext
message_factory::Methods, // tp_methods
0, // tp_members
nullptr, // tp_members
message_factory::Getters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
nullptr, // tp_init
nullptr, // tp_alloc
message_factory::New, // tp_new
PyObject_GC_Del, // tp_free
};
@@ -31,6 +31,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <unordered_map>
@@ -28,6 +28,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <google/protobuf/message_lite.h>
@@ -93,28 +94,28 @@ static PyMethodDef ModuleMethods[] = {
(PyCFunction)google::protobuf::python::cmessage::SetAllowOversizeProtos, METH_O,
"Enable/disable oversize proto parsing."},
// DO NOT USE: For migration and testing only.
{NULL, NULL}};
{nullptr, nullptr}};
static struct PyModuleDef _module = {PyModuleDef_HEAD_INIT,
"_message",
module_docstring,
-1,
ModuleMethods, /* m_methods */
NULL,
NULL,
NULL,
NULL};
nullptr,
nullptr,
nullptr,
nullptr};
PyMODINIT_FUNC PyInit__message() {
PyObject* m;
m = PyModule_Create(&_module);
if (m == NULL) {
return NULL;
if (m == nullptr) {
return nullptr;
}
if (!google::protobuf::python::InitProto2MessageModule(m)) {
Py_DECREF(m);
return NULL;
return nullptr;
}
// Adds the C++ API
@@ -126,7 +127,7 @@ PyMODINIT_FUNC PyInit__message() {
})) {
PyModule_AddObject(m, "proto_API", api);
} else {
return NULL;
return nullptr;
}
return m;
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/pyext/python.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,45 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\"google/protobuf/pyext/python.proto\x12\x1fgoogle.protobuf.python.internal\"\xbc\x02\n\x0cTestAllTypes\x12\\\n\x17repeated_nested_message\x18\x01 \x03(\x0b\x32;.google.protobuf.python.internal.TestAllTypes.NestedMessage\x12\\\n\x17optional_nested_message\x18\x02 \x01(\x0b\x32;.google.protobuf.python.internal.TestAllTypes.NestedMessage\x12\x16\n\x0eoptional_int32\x18\x03 \x01(\x05\x1aX\n\rNestedMessage\x12\n\n\x02\x62\x62\x18\x01 \x01(\x05\x12;\n\x02\x63\x63\x18\x02 \x01(\x0b\x32/.google.protobuf.python.internal.ForeignMessage\"&\n\x0e\x46oreignMessage\x12\t\n\x01\x63\x18\x01 \x01(\x05\x12\t\n\x01\x64\x18\x02 \x03(\x05\"\x1d\n\x11TestAllExtensions*\x08\x08\x01\x10\x80\x80\x80\x80\x02:\x9a\x01\n!optional_nested_message_extension\x12\x32.google.protobuf.python.internal.TestAllExtensions\x18\x01 \x01(\x0b\x32;.google.protobuf.python.internal.TestAllTypes.NestedMessage:\x9a\x01\n!repeated_nested_message_extension\x12\x32.google.protobuf.python.internal.TestAllExtensions\x18\x02 \x03(\x0b\x32;.google.protobuf.python.internal.TestAllTypes.NestedMessageB\x02H\x01')
OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER = 1
optional_nested_message_extension = DESCRIPTOR.extensions_by_name['optional_nested_message_extension']
REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER = 2
repeated_nested_message_extension = DESCRIPTOR.extensions_by_name['repeated_nested_message_extension']
_TESTALLTYPES = DESCRIPTOR.message_types_by_name['TestAllTypes']
_TESTALLTYPES_NESTEDMESSAGE = _TESTALLTYPES.nested_types_by_name['NestedMessage']
_FOREIGNMESSAGE = DESCRIPTOR.message_types_by_name['ForeignMessage']
_TESTALLEXTENSIONS = DESCRIPTOR.message_types_by_name['TestAllExtensions']
TestAllTypes = _reflection.GeneratedProtocolMessageType('TestAllTypes', (_message.Message,), {
'NestedMessage' : _reflection.GeneratedProtocolMessageType('NestedMessage', (_message.Message,), {
'DESCRIPTOR' : _TESTALLTYPES_NESTEDMESSAGE,
'__module__' : 'google.protobuf.pyext.python_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestAllTypes.NestedMessage)
})
,
'DESCRIPTOR' : _TESTALLTYPES,
'__module__' : 'google.protobuf.pyext.python_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestAllTypes)
})
_sym_db.RegisterMessage(TestAllTypes)
_sym_db.RegisterMessage(TestAllTypes.NestedMessage)
ForeignMessage = _reflection.GeneratedProtocolMessageType('ForeignMessage', (_message.Message,), {
'DESCRIPTOR' : _FOREIGNMESSAGE,
'__module__' : 'google.protobuf.pyext.python_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.ForeignMessage)
})
_sym_db.RegisterMessage(ForeignMessage)
TestAllExtensions = _reflection.GeneratedProtocolMessageType('TestAllExtensions', (_message.Message,), {
'DESCRIPTOR' : _TESTALLEXTENSIONS,
'__module__' : 'google.protobuf.pyext.python_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.python.internal.TestAllExtensions)
})
_sym_db.RegisterMessage(TestAllExtensions)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.pyext.python_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
TestAllExtensions.RegisterExtension(optional_nested_message_extension)
TestAllExtensions.RegisterExtension(repeated_nested_message_extension)
@@ -40,12 +40,12 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/message.h>
#include <google/protobuf/reflection.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#include <google/protobuf/reflection.h>
#include <google/protobuf/stubs/map_util.h>
namespace google {
@@ -74,17 +74,15 @@ PyObject* Add(RepeatedCompositeContainer* self, PyObject* args,
if (cmessage::AssureWritable(self->parent) == -1) return nullptr;
Message* message = self->parent->message;
Message* sub_message =
message->GetReflection()->AddMessage(
message,
self->parent_field_descriptor,
self->child_message_class->py_message_factory->message_factory);
Message* sub_message = message->GetReflection()->AddMessage(
message, self->parent_field_descriptor,
self->child_message_class->py_message_factory->message_factory);
CMessage* cmsg = self->parent->BuildSubMessageFromPointer(
self->parent_field_descriptor, sub_message, self->child_message_class);
if (cmessage::InitAttributes(cmsg, args, kwargs) < 0) {
message->GetReflection()->RemoveLast(
message, self->parent_field_descriptor);
message->GetReflection()->RemoveLast(message,
self->parent_field_descriptor);
Py_DECREF(cmsg);
return nullptr;
}
@@ -108,8 +106,7 @@ static PyObject* AddMessage(RepeatedCompositeContainer* self, PyObject* value) {
if (py_cmsg == nullptr) return nullptr;
CMessage* cmsg = reinterpret_cast<CMessage*>(py_cmsg);
if (ScopedPyObjectPtr(cmessage::MergeFrom(cmsg, value)) == nullptr) {
reflection->RemoveLast(
message, self->parent_field_descriptor);
reflection->RemoveLast(message, self->parent_field_descriptor);
Py_DECREF(cmsg);
return nullptr;
}
@@ -152,7 +149,7 @@ static PyObject* Insert(PyObject* pself, PyObject* args) {
Py_ssize_t end_index = index;
if (end_index < 0) end_index += length;
if (end_index < 0) end_index = 0;
for (Py_ssize_t i = length; i > end_index; i --) {
for (Py_ssize_t i = length; i > end_index; i--) {
reflection->SwapElements(message, field_descriptor, i, i - 1);
}
@@ -268,8 +265,7 @@ static PyObject* SubscriptMethod(PyObject* self, PyObject* slice) {
return Subscript(reinterpret_cast<RepeatedCompositeContainer*>(self), slice);
}
int AssignSubscript(RepeatedCompositeContainer* self,
PyObject* slice,
int AssignSubscript(RepeatedCompositeContainer* self, PyObject* slice,
PyObject* value) {
if (value != nullptr) {
PyErr_SetString(PyExc_TypeError, "does not support assignment");
@@ -368,27 +364,22 @@ static void ReorderAttached(RepeatedCompositeContainer* self,
const FieldDescriptor* descriptor = self->parent_field_descriptor;
const Py_ssize_t length = Length(reinterpret_cast<PyObject*>(self));
// We need to rearrange things to match python's sort order. Because there
// was already an O(n*log(n)) step in python and a bunch of reflection, we
// expect an O(n**2) step in C++ won't hurt too much.
// We need to rearrange things to match python's sort order.
for (Py_ssize_t i = 0; i < length; ++i) {
reflection->UnsafeArenaReleaseLast(message, descriptor);
}
for (Py_ssize_t i = 0; i < length; ++i) {
Message* child_message =
reinterpret_cast<CMessage*>(PyList_GET_ITEM(child_list, i))->message;
for (Py_ssize_t j = i; j < length; ++j) {
if (child_message ==
&reflection->GetRepeatedMessage(*message, descriptor, j)) {
reflection->SwapElements(message, descriptor, i, j);
break;
}
}
reflection->UnsafeArenaAddAllocatedMessage(message, descriptor,
child_message);
}
}
// Returns 0 if successful; returns -1 and sets an exception if
// unsuccessful.
static int SortPythonMessages(RepeatedCompositeContainer* self,
PyObject* args,
PyObject* kwds) {
static int SortPythonMessages(RepeatedCompositeContainer* self, PyObject* args,
PyObject* kwds) {
ScopedPyObjectPtr child_list(
PySequence_List(reinterpret_cast<PyObject*>(self)));
if (child_list == nullptr) {
@@ -486,9 +477,8 @@ PyObject* DeepCopy(PyObject* pself, PyObject* arg) {
}
// The private constructor of RepeatedCompositeContainer objects.
RepeatedCompositeContainer *NewContainer(
CMessage* parent,
const FieldDescriptor* parent_field_descriptor,
RepeatedCompositeContainer* NewContainer(
CMessage* parent, const FieldDescriptor* parent_field_descriptor,
CMessageClass* child_message_class) {
if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) {
return nullptr;
@@ -525,9 +515,9 @@ static PySequenceMethods SqMethods = {
};
static PyMappingMethods MpMethods = {
Length, /* mp_length */
SubscriptMethod, /* mp_subscript */
AssignSubscriptMethod, /* mp_ass_subscript */
Length, /* mp_length */
SubscriptMethod, /* mp_subscript */
AssignSubscriptMethod, /* mp_ass_subscript */
};
static PyMethodDef Methods[] = {
@@ -555,14 +545,14 @@ static PyMethodDef Methods[] = {
PyTypeObject RepeatedCompositeContainer_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".RepeatedCompositeContainer", // tp_name
sizeof(RepeatedCompositeContainer), // tp_basicsize
0, // tp_itemsize
repeated_composite_container::Dealloc, // tp_dealloc
".RepeatedCompositeContainer", // tp_name
sizeof(RepeatedCompositeContainer), // tp_basicsize
0, // tp_itemsize
repeated_composite_container::Dealloc, // tp_dealloc
#if PY_VERSION_HEX >= 0x03080000
0, // tp_vectorcall_offset
0, // tp_vectorcall_offset
#else
nullptr, // tp_print
nullptr, // tp_print
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
@@ -34,12 +34,9 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_REPEATED_COMPOSITE_CONTAINER_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_REPEATED_COMPOSITE_CONTAINER_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <memory>
#include <string>
#include <vector>
#include <google/protobuf/pyext/message.h>
namespace google {
@@ -274,6 +274,11 @@ static PyObject* Subscript(PyObject* pself, PyObject* slice) {
bool return_list = false;
if (PyLong_Check(slice)) {
from = to = PyLong_AsLong(slice);
} else if (PyIndex_Check(slice)) {
from = to = PyNumber_AsSsize_t(slice, PyExc_ValueError);
if (from == -1 && PyErr_Occurred()) {
return nullptr;
}
} else if (PySlice_Check(slice)) {
length = Len(pself);
if (PySlice_GetIndicesEx(slice, length, &from, &to, &step, &slicelength) ==
@@ -34,10 +34,9 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_REPEATED_SCALAR_CONTAINER_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_REPEATED_SCALAR_CONTAINER_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <memory>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/pyext/message.h>
@@ -35,6 +35,7 @@
#include <google/protobuf/stubs/common.h>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
namespace google {
namespace protobuf {
@@ -47,7 +48,7 @@ class ScopedPythonPtr {
public:
// Takes the ownership of the specified object to ScopedPythonPtr.
// The reference count of the specified py_object is not incremented.
explicit ScopedPythonPtr(PyObjectStruct* py_object = NULL)
explicit ScopedPythonPtr(PyObjectStruct* py_object = nullptr)
: ptr_(py_object) {}
// If a PyObject is owned, decrement its reference count.
@@ -59,7 +60,7 @@ class ScopedPythonPtr {
// This function must be called with a reference that you own.
// this->reset(this->get()) is wrong!
// this->reset(this->release()) is OK.
PyObjectStruct* reset(PyObjectStruct* p = NULL) {
PyObjectStruct* reset(PyObjectStruct* p = nullptr) {
Py_XDECREF(ptr_);
ptr_ = p;
return ptr_;
@@ -69,7 +70,7 @@ class ScopedPythonPtr {
// The caller now owns the returned reference.
PyObjectStruct* release() {
PyObject* p = ptr_;
ptr_ = NULL;
ptr_ = nullptr;
return p;
}
@@ -0,0 +1,355 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/pyext/unknown_field_set.h>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <memory>
#include <set>
#include <google/protobuf/message.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/pyext/message.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
namespace google {
namespace protobuf {
namespace python {
namespace unknown_field_set {
static Py_ssize_t Len(PyObject* pself) {
PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(pself);
if (self->fields == nullptr) {
PyErr_Format(PyExc_ValueError, "UnknownFieldSet does not exist. ");
return -1;
}
return self->fields->field_count();
}
PyObject* NewPyUnknownField(PyUnknownFieldSet* parent, Py_ssize_t index);
static PyObject* Item(PyObject* pself, Py_ssize_t index) {
PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(pself);
if (self->fields == nullptr) {
PyErr_Format(PyExc_ValueError, "UnknownFieldSet does not exist. ");
return nullptr;
}
Py_ssize_t total_size = self->fields->field_count();
if (index < 0) {
index = total_size + index;
}
if (index < 0 || index >= total_size) {
PyErr_Format(PyExc_IndexError, "index (%zd) out of range", index);
return nullptr;
}
return unknown_field_set::NewPyUnknownField(self, index);
}
PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
if (args == nullptr || PyTuple_Size(args) != 1) {
PyErr_SetString(PyExc_TypeError,
"Must provide a message to create UnknownFieldSet");
return nullptr;
}
PyObject* c_message;
if (!PyArg_ParseTuple(args, "O", &c_message)) {
PyErr_SetString(PyExc_TypeError,
"Must provide a message to create UnknownFieldSet");
return nullptr;
}
if (!PyObject_TypeCheck(c_message, CMessage_Type)) {
PyErr_Format(PyExc_TypeError,
"Parameter to UnknownFieldSet() must be a message "
"got %s.",
Py_TYPE(c_message)->tp_name);
return nullptr;
}
PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(
PyType_GenericAlloc(&PyUnknownFieldSet_Type, 0));
if (self == nullptr) {
return nullptr;
}
// Top UnknownFieldSet should set parent nullptr.
self->parent = nullptr;
// Copy c_message's UnknownFieldSet.
Message* message = reinterpret_cast<CMessage*>(c_message)->message;
const Reflection* reflection = message->GetReflection();
self->fields = new google::protobuf::UnknownFieldSet;
self->fields->MergeFrom(reflection->GetUnknownFields(*message));
return reinterpret_cast<PyObject*>(self);
}
PyObject* NewPyUnknownField(PyUnknownFieldSet* parent, Py_ssize_t index) {
PyUnknownField* self = reinterpret_cast<PyUnknownField*>(
PyType_GenericAlloc(&PyUnknownField_Type, 0));
if (self == nullptr) {
return nullptr;
}
Py_INCREF(parent);
self->parent = parent;
self->index = index;
return reinterpret_cast<PyObject*>(self);
}
static void Dealloc(PyObject* pself) {
PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(pself);
if (self->parent == nullptr) {
delete self->fields;
} else {
Py_CLEAR(self->parent);
}
auto* py_type = Py_TYPE(pself);
self->~PyUnknownFieldSet();
py_type->tp_free(pself);
}
static PySequenceMethods SqMethods = {
Len, /* sq_length */
nullptr, /* sq_concat */
nullptr, /* sq_repeat */
Item, /* sq_item */
nullptr, /* sq_slice */
nullptr, /* sq_ass_item */
};
} // namespace unknown_field_set
PyTypeObject PyUnknownFieldSet_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".PyUnknownFieldSet", // tp_name
sizeof(PyUnknownFieldSet), // tp_basicsize
0, // tp_itemsize
unknown_field_set::Dealloc, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
&unknown_field_set::SqMethods, // tp_as_sequence
nullptr, // tp_as_mapping
PyObject_HashNotImplemented, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"unknown field set", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
nullptr, // tp_alloc
unknown_field_set::New, // tp_new
};
namespace unknown_field {
static PyObject* PyUnknownFieldSet_FromUnknownFieldSet(
PyUnknownFieldSet* parent, const UnknownFieldSet& fields) {
PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(
PyType_GenericAlloc(&PyUnknownFieldSet_Type, 0));
if (self == nullptr) {
return nullptr;
}
Py_INCREF(parent);
self->parent = parent;
self->fields = const_cast<UnknownFieldSet*>(&fields);
return reinterpret_cast<PyObject*>(self);
}
const UnknownField* GetUnknownField(PyUnknownField* self) {
const UnknownFieldSet* fields = self->parent->fields;
if (fields == nullptr) {
PyErr_Format(PyExc_ValueError, "UnknownField does not exist. ");
return nullptr;
}
Py_ssize_t total_size = fields->field_count();
if (self->index >= total_size) {
PyErr_Format(PyExc_ValueError, "UnknownField does not exist. ");
return nullptr;
}
return &fields->field(self->index);
}
static PyObject* GetFieldNumber(PyUnknownField* self, void* closure) {
const UnknownField* unknown_field = GetUnknownField(self);
if (unknown_field == nullptr) {
return nullptr;
}
return PyLong_FromLong(unknown_field->number());
}
using internal::WireFormatLite;
static PyObject* GetWireType(PyUnknownField* self, void* closure) {
const UnknownField* unknown_field = GetUnknownField(self);
if (unknown_field == nullptr) {
return nullptr;
}
// Assign a default value to suppress may-uninitialized warnings (errors
// when built in some places).
WireFormatLite::WireType wire_type = WireFormatLite::WIRETYPE_VARINT;
switch (unknown_field->type()) {
case UnknownField::TYPE_VARINT:
wire_type = WireFormatLite::WIRETYPE_VARINT;
break;
case UnknownField::TYPE_FIXED32:
wire_type = WireFormatLite::WIRETYPE_FIXED32;
break;
case UnknownField::TYPE_FIXED64:
wire_type = WireFormatLite::WIRETYPE_FIXED64;
break;
case UnknownField::TYPE_LENGTH_DELIMITED:
wire_type = WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
break;
case UnknownField::TYPE_GROUP:
wire_type = WireFormatLite::WIRETYPE_START_GROUP;
break;
}
return PyLong_FromLong(wire_type);
}
static PyObject* GetData(PyUnknownField* self, void* closure) {
const UnknownField* field = GetUnknownField(self);
if (field == nullptr) {
return nullptr;
}
PyObject* data = nullptr;
switch (field->type()) {
case UnknownField::TYPE_VARINT:
data = PyLong_FromUnsignedLongLong(field->varint());
break;
case UnknownField::TYPE_FIXED32:
data = PyLong_FromUnsignedLong(field->fixed32());
break;
case UnknownField::TYPE_FIXED64:
data = PyLong_FromUnsignedLongLong(field->fixed64());
break;
case UnknownField::TYPE_LENGTH_DELIMITED:
data = PyBytes_FromStringAndSize(field->length_delimited().data(),
field->GetLengthDelimitedSize());
break;
case UnknownField::TYPE_GROUP:
data =
PyUnknownFieldSet_FromUnknownFieldSet(self->parent, field->group());
break;
}
return data;
}
static void Dealloc(PyObject* pself) {
PyUnknownField* self = reinterpret_cast<PyUnknownField*>(pself);
Py_CLEAR(self->parent);
}
static PyGetSetDef Getters[] = {
{"field_number", (getter)GetFieldNumber, nullptr},
{"wire_type", (getter)GetWireType, nullptr},
{"data", (getter)GetData, nullptr},
{nullptr},
};
} // namespace unknown_field
PyTypeObject PyUnknownField_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".PyUnknownField", // tp_name
sizeof(PyUnknownField), // tp_basicsize
0, // tp_itemsize
unknown_field::Dealloc, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
PyObject_HashNotImplemented, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"unknown field", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
unknown_field::Getters, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
};
} // namespace python
} // namespace protobuf
} // namespace google
@@ -0,0 +1,78 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELD_SET_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELD_SET_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <memory>
#include <set>
#include <google/protobuf/pyext/message.h>
namespace google {
namespace protobuf {
class UnknownField;
class UnknownFieldSet;
namespace python {
struct CMessage;
struct PyUnknownFieldSet {
PyObject_HEAD;
// If parent is nullptr, it is a top UnknownFieldSet.
PyUnknownFieldSet* parent;
// Top UnknownFieldSet owns fields pointer. Sub UnknownFieldSet
// does not own fields pointer.
UnknownFieldSet* fields;
};
struct PyUnknownField {
PyObject_HEAD;
// Every Python PyUnknownField holds a reference to its parent
// PyUnknownFieldSet in order to keep it alive.
PyUnknownFieldSet* parent;
// The UnknownField index in UnknownFieldSet.
Py_ssize_t index;
};
extern PyTypeObject PyUnknownFieldSet_Type;
extern PyTypeObject PyUnknownField_Type;
} // namespace python
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELD_SET_H__
@@ -30,6 +30,7 @@
#include <google/protobuf/pyext/unknown_fields.h>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <set>
#include <memory>
@@ -49,7 +50,7 @@ namespace unknown_fields {
static Py_ssize_t Len(PyObject* pself) {
PyUnknownFields* self =
reinterpret_cast<PyUnknownFields*>(pself);
if (self->fields == NULL) {
if (self->fields == nullptr) {
PyErr_Format(PyExc_ValueError,
"UnknownFields does not exist. "
"The parent message might be cleared.");
@@ -64,7 +65,7 @@ void Clear(PyUnknownFields* self) {
it != self->sub_unknown_fields.end(); it++) {
Clear(*it);
}
self->fields = NULL;
self->fields = nullptr;
self->sub_unknown_fields.clear();
}
@@ -74,11 +75,11 @@ PyObject* NewPyUnknownFieldRef(PyUnknownFields* parent,
static PyObject* Item(PyObject* pself, Py_ssize_t index) {
PyUnknownFields* self =
reinterpret_cast<PyUnknownFields*>(pself);
if (self->fields == NULL) {
if (self->fields == nullptr) {
PyErr_Format(PyExc_ValueError,
"UnknownFields does not exist. "
"The parent message might be cleared.");
return NULL;
return nullptr;
}
Py_ssize_t total_size = self->fields->field_count();
if (index < 0) {
@@ -88,7 +89,7 @@ static PyObject* Item(PyObject* pself, Py_ssize_t index) {
PyErr_Format(PyExc_IndexError,
"index (%zd) out of range",
index);
return NULL;
return nullptr;
}
return unknown_fields::NewPyUnknownFieldRef(self, index);
@@ -97,8 +98,8 @@ static PyObject* Item(PyObject* pself, Py_ssize_t index) {
PyObject* NewPyUnknownFields(CMessage* c_message) {
PyUnknownFields* self = reinterpret_cast<PyUnknownFields*>(
PyType_GenericAlloc(&PyUnknownFields_Type, 0));
if (self == NULL) {
return NULL;
if (self == nullptr) {
return nullptr;
}
// Call "placement new" to initialize PyUnknownFields.
new (self) PyUnknownFields;
@@ -116,8 +117,8 @@ PyObject* NewPyUnknownFieldRef(PyUnknownFields* parent,
Py_ssize_t index) {
PyUnknownFieldRef* self = reinterpret_cast<PyUnknownFieldRef*>(
PyType_GenericAlloc(&PyUnknownFieldRef_Type, 0));
if (self == NULL) {
return NULL;
if (self == nullptr) {
return nullptr;
}
Py_INCREF(parent);
@@ -137,58 +138,63 @@ static void Dealloc(PyObject* pself) {
reinterpret_cast<CMessage*>(self->parent)->unknown_field_set = nullptr;
}
Py_CLEAR(self->parent);
auto* py_type = Py_TYPE(pself);
self->~PyUnknownFields();
Py_TYPE(pself)->tp_free(pself);
py_type->tp_free(pself);
}
static PySequenceMethods SqMethods = {
Len, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
Item, /* sq_item */
0, /* sq_slice */
0, /* sq_ass_item */
Len, /* sq_length */
nullptr, /* sq_concat */
nullptr, /* sq_repeat */
Item, /* sq_item */
nullptr, /* sq_slice */
nullptr, /* sq_ass_item */
};
} // namespace unknown_fields
PyTypeObject PyUnknownFields_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
FULL_MODULE_NAME ".PyUnknownFields", // tp_name
sizeof(PyUnknownFields), // tp_basicsize
0, // tp_itemsize
unknown_fields::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
&unknown_fields::SqMethods, // tp_as_sequence
0, // tp_as_mapping
PyObject_HashNotImplemented, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"unknown field set", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".PyUnknownFields", // tp_name
sizeof(PyUnknownFields), // tp_basicsize
0, // tp_itemsize
unknown_fields::Dealloc, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
&unknown_fields::SqMethods, // tp_as_sequence
nullptr, // tp_as_mapping
PyObject_HashNotImplemented, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"unknown field set", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
};
namespace unknown_field {
@@ -196,8 +202,8 @@ static PyObject* PyUnknownFields_FromUnknownFieldSet(
PyUnknownFields* parent, const UnknownFieldSet& fields) {
PyUnknownFields* self = reinterpret_cast<PyUnknownFields*>(
PyType_GenericAlloc(&PyUnknownFields_Type, 0));
if (self == NULL) {
return NULL;
if (self == nullptr) {
return nullptr;
}
// Call "placement new" to initialize PyUnknownFields.
new (self) PyUnknownFields;
@@ -212,26 +218,26 @@ static PyObject* PyUnknownFields_FromUnknownFieldSet(
const UnknownField* GetUnknownField(PyUnknownFieldRef* self) {
const UnknownFieldSet* fields = self->parent->fields;
if (fields == NULL) {
if (fields == nullptr) {
PyErr_Format(PyExc_ValueError,
"UnknownField does not exist. "
"The parent message might be cleared.");
return NULL;
return nullptr;
}
ssize_t total_size = fields->field_count();
Py_ssize_t total_size = fields->field_count();
if (self->index >= total_size) {
PyErr_Format(PyExc_ValueError,
"UnknownField does not exist. "
"The parent message might be cleared.");
return NULL;
return nullptr;
}
return &fields->field(self->index);
}
static PyObject* GetFieldNumber(PyUnknownFieldRef* self, void *closure) {
const UnknownField* unknown_field = GetUnknownField(self);
if (unknown_field == NULL) {
return NULL;
if (unknown_field == nullptr) {
return nullptr;
}
return PyLong_FromLong(unknown_field->number());
}
@@ -239,8 +245,8 @@ static PyObject* GetFieldNumber(PyUnknownFieldRef* self, void *closure) {
using internal::WireFormatLite;
static PyObject* GetWireType(PyUnknownFieldRef* self, void *closure) {
const UnknownField* unknown_field = GetUnknownField(self);
if (unknown_field == NULL) {
return NULL;
if (unknown_field == nullptr) {
return nullptr;
}
// Assign a default value to suppress may-uninitialized warnings (errors
@@ -268,19 +274,19 @@ static PyObject* GetWireType(PyUnknownFieldRef* self, void *closure) {
static PyObject* GetData(PyUnknownFieldRef* self, void *closure) {
const UnknownField* field = GetUnknownField(self);
if (field == NULL) {
return NULL;
if (field == nullptr) {
return nullptr;
}
PyObject* data = NULL;
PyObject* data = nullptr;
switch (field->type()) {
case UnknownField::TYPE_VARINT:
data = PyLong_FromLong(field->varint());
data = PyLong_FromUnsignedLongLong(field->varint());
break;
case UnknownField::TYPE_FIXED32:
data = PyLong_FromLong(field->fixed32());
data = PyLong_FromUnsignedLong(field->fixed32());
break;
case UnknownField::TYPE_FIXED64:
data = PyLong_FromLong(field->fixed64());
data = PyLong_FromUnsignedLongLong(field->fixed64());
break;
case UnknownField::TYPE_LENGTH_DELIMITED:
data = PyBytes_FromStringAndSize(field->length_delimited().data(),
@@ -301,54 +307,57 @@ static void Dealloc(PyObject* pself) {
}
static PyGetSetDef Getters[] = {
{"field_number", (getter)GetFieldNumber, NULL},
{"wire_type", (getter)GetWireType, NULL},
{"data", (getter)GetData, NULL},
{NULL}
{"field_number", (getter)GetFieldNumber, nullptr},
{"wire_type", (getter)GetWireType, nullptr},
{"data", (getter)GetData, nullptr},
{nullptr},
};
} // namespace unknown_field
PyTypeObject PyUnknownFieldRef_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
FULL_MODULE_NAME ".PyUnknownFieldRef", // tp_name
sizeof(PyUnknownFieldRef), // tp_basicsize
0, // tp_itemsize
unknown_field::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
PyObject_HashNotImplemented, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"unknown field", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
unknown_field::Getters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".PyUnknownFieldRef", // tp_name
sizeof(PyUnknownFieldRef), // tp_basicsize
0, // tp_itemsize
unknown_field::Dealloc, // tp_dealloc
#if PY_VERSION_HEX < 0x03080000
nullptr, // tp_print
#else
0, // tp_vectorcall_offset
#endif
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
PyObject_HashNotImplemented, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
"unknown field", // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
unknown_field::Getters, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
};
} // namespace python
} // namespace protobuf
} // namespace google
@@ -31,6 +31,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELDS_H__
#define GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELDS_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <memory>
@@ -36,6 +36,7 @@
#ifndef GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__
#define GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
namespace google {
@@ -133,7 +133,7 @@ class _ServiceBuilder(object):
"""
self.descriptor = service_descriptor
def BuildService(self, cls):
def BuildService(builder, cls):
"""Constructs the service class.
Args:
@@ -143,18 +143,26 @@ class _ServiceBuilder(object):
# CallMethod needs to operate with an instance of the Service class. This
# internal wrapper function exists only to be able to pass the service
# instance to the method that does the real CallMethod work.
def _WrapCallMethod(srvc, method_descriptor,
rpc_controller, request, callback):
return self._CallMethod(srvc, method_descriptor,
rpc_controller, request, callback)
self.cls = cls
# Making sure to use exact argument names from the abstract interface in
# service.py to match the type signature
def _WrapCallMethod(self, method_descriptor, rpc_controller, request, done):
return builder._CallMethod(self, method_descriptor, rpc_controller,
request, done)
def _WrapGetRequestClass(self, method_descriptor):
return builder._GetRequestClass(method_descriptor)
def _WrapGetResponseClass(self, method_descriptor):
return builder._GetResponseClass(method_descriptor)
builder.cls = cls
cls.CallMethod = _WrapCallMethod
cls.GetDescriptor = staticmethod(lambda: self.descriptor)
cls.GetDescriptor.__doc__ = "Returns the service descriptor."
cls.GetRequestClass = self._GetRequestClass
cls.GetResponseClass = self._GetResponseClass
for method in self.descriptor.methods:
setattr(cls, method.name, self._GenerateNonImplementedMethod(method))
cls.GetDescriptor = staticmethod(lambda: builder.descriptor)
cls.GetDescriptor.__doc__ = 'Returns the service descriptor.'
cls.GetRequestClass = _WrapGetRequestClass
cls.GetResponseClass = _WrapGetResponseClass
for method in builder.descriptor.methods:
setattr(cls, method.name, builder._GenerateNonImplementedMethod(method))
def _CallMethod(self, srvc, method_descriptor,
rpc_controller, request, callback):
@@ -2,10 +2,9 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/source_context.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
@@ -16,16 +15,8 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n$google/protobuf/source_context.proto\x12\x0fgoogle.protobuf\"\"\n\rSourceContext\x12\x11\n\tfile_name\x18\x01 \x01(\tB\x8a\x01\n\x13\x63om.google.protobufB\x12SourceContextProtoP\x01Z6google.golang.org/protobuf/types/known/sourcecontextpb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3')
_SOURCECONTEXT = DESCRIPTOR.message_types_by_name['SourceContext']
SourceContext = _reflection.GeneratedProtocolMessageType('SourceContext', (_message.Message,), {
'DESCRIPTOR' : _SOURCECONTEXT,
'__module__' : 'google.protobuf.source_context_pb2'
# @@protoc_insertion_point(class_scope:google.protobuf.SourceContext)
})
_sym_db.RegisterMessage(SourceContext)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.source_context_pb2', globals())
if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None
Loaded 100 of 554 files, more files were not shown because too many files have changed in this diff. Show more