Upgrade linux protobuf from 3.19.1 -> 21.12
This commit is contained in:
1 parent
4a3e40193e
commit
01a4bb004a
554 files changed
+34981
-37969
No files matched your search
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user