def setUpClass(cls):
FinalABCMeta = final_meta_factory(ABCMeta)
class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
a = final('ABCWithFinal: a')
b = 'ABCWithFinal: b'
@final
def f(self):
return 'ABCWithFinal: f'
def g(self):
return 'ABCWithFinal: g'
@abstractmethod
def h(self):
raise NotImplementedError('h')
cls.class_ = ABCWithFinal
python类with_metaclass()的实例源码
def test_subclass_setattr(self):
"""
Tests that subclasses don't destroy the __setattr__.
"""
class ClassWithFinal(with_metaclass(FinalMeta, object)):
@final
def f(self):
return 'ClassWithFinal: f'
class SubClass(ClassWithFinal):
def __init__(self):
self.a = 'a'
SubClass()
self.assertEqual(SubClass().a, 'a')
self.assertEqual(SubClass().f(), 'ClassWithFinal: f')
def with_metaclasses(metaclasses, *bases):
"""Make a class inheriting from ``bases`` whose metaclass inherits from
all of ``metaclasses``.
Like :func:`six.with_metaclass`, but allows multiple metaclasses.
Parameters
----------
metaclasses : iterable[type]
A tuple of types to use as metaclasses.
*bases : tuple[type]
A tuple of types to use as bases.
Returns
-------
base : type
A subtype of ``bases`` whose metaclass is a subtype of ``metaclasses``.
Notes
-----
The metaclasses must be written to support cooperative multiple
inheritance. This means that they must delegate all calls to ``super()``
instead of inlining their super class by name.
"""
return six.with_metaclass(compose_types(*metaclasses), *bases)
def setUpClass(cls):
FinalABCMeta = compose_types(FinalMeta, ABCMeta)
class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
a = final('ABCWithFinal: a')
b = 'ABCWithFinal: b'
@final
def f(self):
return 'ABCWithFinal: f'
def g(self):
return 'ABCWithFinal: g'
@abstractmethod
def h(self):
raise NotImplementedError('h')
cls.class_ = ABCWithFinal
def test_subclass_setattr(self):
"""
Tests that subclasses don't destroy the __setattr__.
"""
class ClassWithFinal(with_metaclass(FinalMeta, object)):
@final
def f(self):
return 'ClassWithFinal: f'
class SubClass(ClassWithFinal):
def __init__(self):
self.a = 'a'
SubClass()
self.assertEqual(SubClass().a, 'a')
self.assertEqual(SubClass().f(), 'ClassWithFinal: f')
def test_with_metaclass():
class Meta(type):
pass
class X(six.with_metaclass(Meta)):
pass
assert type(X) is Meta
assert issubclass(X, object)
class Base(object):
pass
class X(six.with_metaclass(Meta, Base)):
pass
assert type(X) is Meta
assert issubclass(X, Base)
class Base2(object):
pass
class X(six.with_metaclass(Meta, Base, Base2)):
pass
assert type(X) is Meta
assert issubclass(X, Base)
assert issubclass(X, Base2)
assert X.__mro__ == (X, Base, Base2, object)
def test_with_metaclass():
class Meta(type):
pass
class X(six.with_metaclass(Meta)):
pass
assert type(X) is Meta
assert issubclass(X, object)
class Base(object):
pass
class X(six.with_metaclass(Meta, Base)):
pass
assert type(X) is Meta
assert issubclass(X, Base)
class Base2(object):
pass
class X(six.with_metaclass(Meta, Base, Base2)):
pass
assert type(X) is Meta
assert issubclass(X, Base)
assert issubclass(X, Base2)
assert X.__mro__ == (X, Base, Base2, object)
def test_with_metaclass_prepare():
"""Test that with_metaclass causes Meta.__prepare__ to be called with the correct arguments."""
class MyDict(dict):
pass
class Meta(type):
@classmethod
def __prepare__(cls, name, bases):
namespace = MyDict(super().__prepare__(name, bases), cls=cls, bases=bases)
namespace['namespace'] = namespace
return namespace
class Base(object):
pass
bases = (Base,)
class X(six.with_metaclass(Meta, *bases)):
pass
assert getattr(X, 'cls', type) is Meta
assert getattr(X, 'bases', ()) == bases
assert isinstance(getattr(X, 'namespace', {}), MyDict)
def testParsingFlatClassWithExplicitClassDeclaration(self):
"""Test that the generated class can parse a flat message."""
# TODO(xiaofeng): This test fails with cpp implemetnation in the call
# of six.with_metaclass(). The other two callsites of with_metaclass
# in this file are both excluded from cpp test, so it might be expected
# to fail. Need someone more familiar with the python code to take a
# look at this.
if api_implementation.Type() != 'python':
return
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
msg_descriptor = descriptor.MakeDescriptor(
file_descriptor.message_type[0])
class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = msg_descriptor
msg = MessageClass()
msg_str = (
'flat: 0 '
'flat: 1 '
'flat: 2 ')
text_format.Merge(msg_str, msg)
self.assertEqual(msg.flat, [0, 1, 2])
def setUpClass(cls):
class ClassWithFinal(with_metaclass(FinalMeta, object)):
a = final('ClassWithFinal: a')
b = 'ClassWithFinal: b'
@final
def f(self):
return 'ClassWithFinal: f'
def g(self):
return 'ClassWithFinal: g'
cls.class_ = ClassWithFinal
def test_final_classmethod(self):
class ClassWithClassMethod(with_metaclass(FinalMeta, object)):
count = 0
@final
@classmethod
def f(cls):
cls.count += 1
return cls.count
with self.assertRaises(TypeError):
class ClassOverridingClassMethod(ClassWithClassMethod):
@classmethod
def f(cls):
return "Oh Noes!"
with self.assertRaises(TypeError):
ClassWithClassMethod.f = lambda cls: 0
self.assertEqual(ClassWithClassMethod.f(), 1)
self.assertEqual(ClassWithClassMethod.f(), 2)
self.assertEqual(ClassWithClassMethod.f(), 3)
instance = ClassWithClassMethod()
with self.assertRaises(TypeError):
instance.f = lambda cls: 0
self.assertEqual(ClassWithClassMethod.f(), 4)
self.assertEqual(ClassWithClassMethod.f(), 5)
self.assertEqual(ClassWithClassMethod.f(), 6)
def setUpClass(cls):
class ClassWithFinal(with_metaclass(FinalMeta, object)):
a = final('ClassWithFinal: a')
b = 'ClassWithFinal: b'
@final
def f(self):
return 'ClassWithFinal: f'
def g(self):
return 'ClassWithFinal: g'
cls.class_ = ClassWithFinal
def test_final_classmethod(self):
class ClassWithClassMethod(with_metaclass(FinalMeta, object)):
count = 0
@final
@classmethod
def f(cls):
cls.count += 1
return cls.count
with self.assertRaises(TypeError):
class ClassOverridingClassMethod(ClassWithClassMethod):
@classmethod
def f(cls):
return "Oh Noes!"
with self.assertRaises(TypeError):
ClassWithClassMethod.f = lambda cls: 0
self.assertEqual(ClassWithClassMethod.f(), 1)
self.assertEqual(ClassWithClassMethod.f(), 2)
self.assertEqual(ClassWithClassMethod.f(), 3)
instance = ClassWithClassMethod()
with self.assertRaises(TypeError):
instance.f = lambda cls: 0
self.assertEqual(ClassWithClassMethod.f(), 4)
self.assertEqual(ClassWithClassMethod.f(), 5)
self.assertEqual(ClassWithClassMethod.f(), 6)
def method_binding_meta(template, *bases):
"""Adds all bound functions from the ComponentTemplate to the class being constructed.
This returns a metaclass similar to the with_metaclass of the six library.
Args:
template (ComponentTemplate): the component config with the bound_methods attribute which we will all add
to the attributes of the to creating class.
"""
class ApplyMethodBinding(type):
def __new__(mcs, name, bases, attributes):
attributes.update(template.bound_methods)
return super(ApplyMethodBinding, mcs).__new__(mcs, name, bases, attributes)
return with_metaclass(ApplyMethodBinding, *bases)
def singleton_particle(*bases):
"""Defines a singleton instance immediately when defining the class. The
name of the class will refer the instance instead.
"""
return with_metaclass(SingletonParticleMeta, SingletonParticle, *bases)
def test_singleton_error():
with pytest.raises(TypeError):
class Fail(with_metaclass(SingletonParticleMeta, object)):
pass
reflection_test.py 文件源码
项目:Vector-Tiles-Reader-QGIS-Plugin
作者: geometalab
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def testHandWrittenReflection(self):
# Hand written extensions are only supported by the pure-Python
# implementation of the API.
if api_implementation.Type() != 'python':
return
FieldDescriptor = descriptor.FieldDescriptor
foo_field_descriptor = FieldDescriptor(
name='foo_field', full_name='MyProto.foo_field',
index=0, number=1, type=FieldDescriptor.TYPE_INT64,
cpp_type=FieldDescriptor.CPPTYPE_INT64,
label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
containing_type=None, message_type=None, enum_type=None,
is_extension=False, extension_scope=None,
options=descriptor_pb2.FieldOptions())
mydescriptor = descriptor.Descriptor(
name='MyProto', full_name='MyProto', filename='ignored',
containing_type=None, nested_types=[], enum_types=[],
fields=[foo_field_descriptor], extensions=[],
options=descriptor_pb2.MessageOptions())
class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = mydescriptor
myproto_instance = MyProtoClass()
self.assertEqual(0, myproto_instance.foo_field)
self.assertTrue(not myproto_instance.HasField('foo_field'))
myproto_instance.foo_field = 23
self.assertEqual(23, myproto_instance.foo_field)
self.assertTrue(myproto_instance.HasField('foo_field'))
reflection_test.py 文件源码
项目:Vector-Tiles-Reader-QGIS-Plugin
作者: geometalab
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def testParsingFlatClassWithExplicitClassDeclaration(self):
"""Test that the generated class can parse a flat message."""
# TODO(xiaofeng): This test fails with cpp implemetnation in the call
# of six.with_metaclass(). The other two callsites of with_metaclass
# in this file are both excluded from cpp test, so it might be expected
# to fail. Need someone more familiar with the python code to take a
# look at this.
if api_implementation.Type() != 'python':
return
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
msg_descriptor = descriptor.MakeDescriptor(
file_descriptor.message_type[0])
class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = msg_descriptor
msg = MessageClass()
msg_str = (
'flat: 0 '
'flat: 1 '
'flat: 2 ')
text_format.Merge(msg_str, msg)
self.assertEqual(msg.flat, [0, 1, 2])
def test_add_logger_meta():
class DummyClass(six.with_metaclass(AddLoggerMeta, object)):
pass
assert isinstance(DummyClass.logger, logging.Logger)
assert DummyClass.logger.name == 'tests.test_utils_logging.DummyClass'
def testHandWrittenReflection(self):
# Hand written extensions are only supported by the pure-Python
# implementation of the API.
if api_implementation.Type() != 'python':
return
FieldDescriptor = descriptor.FieldDescriptor
foo_field_descriptor = FieldDescriptor(
name='foo_field', full_name='MyProto.foo_field',
index=0, number=1, type=FieldDescriptor.TYPE_INT64,
cpp_type=FieldDescriptor.CPPTYPE_INT64,
label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
containing_type=None, message_type=None, enum_type=None,
is_extension=False, extension_scope=None,
options=descriptor_pb2.FieldOptions())
mydescriptor = descriptor.Descriptor(
name='MyProto', full_name='MyProto', filename='ignored',
containing_type=None, nested_types=[], enum_types=[],
fields=[foo_field_descriptor], extensions=[],
options=descriptor_pb2.MessageOptions())
class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = mydescriptor
myproto_instance = MyProtoClass()
self.assertEqual(0, myproto_instance.foo_field)
self.assertTrue(not myproto_instance.HasField('foo_field'))
myproto_instance.foo_field = 23
self.assertEqual(23, myproto_instance.foo_field)
self.assertTrue(myproto_instance.HasField('foo_field'))
def testParsingFlatClassWithExplicitClassDeclaration(self):
"""Test that the generated class can parse a flat message."""
# TODO(xiaofeng): This test fails with cpp implemetnation in the call
# of six.with_metaclass(). The other two callsites of with_metaclass
# in this file are both excluded from cpp test, so it might be expected
# to fail. Need someone more familiar with the python code to take a
# look at this.
if api_implementation.Type() != 'python':
return
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
msg_descriptor = descriptor.MakeDescriptor(
file_descriptor.message_type[0])
class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = msg_descriptor
msg = MessageClass()
msg_str = (
'flat: 0 '
'flat: 1 '
'flat: 2 ')
text_format.Merge(msg_str, msg)
self.assertEqual(msg.flat, [0, 1, 2])
def testHandWrittenReflection(self):
# Hand written extensions are only supported by the pure-Python
# implementation of the API.
if api_implementation.Type() != 'python':
return
FieldDescriptor = descriptor.FieldDescriptor
foo_field_descriptor = FieldDescriptor(
name='foo_field', full_name='MyProto.foo_field',
index=0, number=1, type=FieldDescriptor.TYPE_INT64,
cpp_type=FieldDescriptor.CPPTYPE_INT64,
label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
containing_type=None, message_type=None, enum_type=None,
is_extension=False, extension_scope=None,
options=descriptor_pb2.FieldOptions())
mydescriptor = descriptor.Descriptor(
name='MyProto', full_name='MyProto', filename='ignored',
containing_type=None, nested_types=[], enum_types=[],
fields=[foo_field_descriptor], extensions=[],
options=descriptor_pb2.MessageOptions())
class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = mydescriptor
myproto_instance = MyProtoClass()
self.assertEqual(0, myproto_instance.foo_field)
self.assertTrue(not myproto_instance.HasField('foo_field'))
myproto_instance.foo_field = 23
self.assertEqual(23, myproto_instance.foo_field)
self.assertTrue(myproto_instance.HasField('foo_field'))
def testParsingFlatClassWithExplicitClassDeclaration(self):
"""Test that the generated class can parse a flat message."""
# TODO(xiaofeng): This test fails with cpp implemetnation in the call
# of six.with_metaclass(). The other two callsites of with_metaclass
# in this file are both excluded from cpp test, so it might be expected
# to fail. Need someone more familiar with the python code to take a
# look at this.
if api_implementation.Type() != 'python':
return
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
msg_descriptor = descriptor.MakeDescriptor(
file_descriptor.message_type[0])
class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = msg_descriptor
msg = MessageClass()
msg_str = (
'flat: 0 '
'flat: 1 '
'flat: 2 ')
text_format.Merge(msg_str, msg)
self.assertEqual(msg.flat, [0, 1, 2])
def _get_subfield_superclass():
# hardcore trick to support django < 1.3 - there was something wrong with
# inheritance and SubfieldBase before django 1.3
# see https://github.com/django/django/commit/222c73261650201f5ce99e8dd4b1ce0d30a69eb4
if django.VERSION < (1,3):
return models.Field
return six.with_metaclass(models.SubfieldBase, models.Field)
def test_with_metaclass():
class Meta(type):
pass
class X(six.with_metaclass(Meta)):
pass
assert type(X) is Meta
assert issubclass(X, object)
class Base(object):
pass
class X(six.with_metaclass(Meta, Base)):
pass
assert type(X) is Meta
assert issubclass(X, Base)
class Base2(object):
pass
class X(six.with_metaclass(Meta, Base, Base2)):
pass
assert type(X) is Meta
assert issubclass(X, Base)
assert issubclass(X, Base2)
assert X.__mro__ == (X, Base, Base2, object)
class X(six.with_metaclass(Meta)):
pass
class MetaSub(Meta):
pass
class Y(six.with_metaclass(MetaSub, X)):
pass
assert type(Y) is MetaSub
assert Y.__mro__ == (Y, X, object)
def testHandWrittenReflection(self):
# Hand written extensions are only supported by the pure-Python
# implementation of the API.
if api_implementation.Type() != 'python':
return
FieldDescriptor = descriptor.FieldDescriptor
foo_field_descriptor = FieldDescriptor(
name='foo_field', full_name='MyProto.foo_field',
index=0, number=1, type=FieldDescriptor.TYPE_INT64,
cpp_type=FieldDescriptor.CPPTYPE_INT64,
label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
containing_type=None, message_type=None, enum_type=None,
is_extension=False, extension_scope=None,
options=descriptor_pb2.FieldOptions())
mydescriptor = descriptor.Descriptor(
name='MyProto', full_name='MyProto', filename='ignored',
containing_type=None, nested_types=[], enum_types=[],
fields=[foo_field_descriptor], extensions=[],
options=descriptor_pb2.MessageOptions())
class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = mydescriptor
myproto_instance = MyProtoClass()
self.assertEqual(0, myproto_instance.foo_field)
self.assertTrue(not myproto_instance.HasField('foo_field'))
myproto_instance.foo_field = 23
self.assertEqual(23, myproto_instance.foo_field)
self.assertTrue(myproto_instance.HasField('foo_field'))
def testParsingFlatClassWithExplicitClassDeclaration(self):
"""Test that the generated class can parse a flat message."""
# TODO(xiaofeng): This test fails with cpp implemetnation in the call
# of six.with_metaclass(). The other two callsites of with_metaclass
# in this file are both excluded from cpp test, so it might be expected
# to fail. Need someone more familiar with the python code to take a
# look at this.
if api_implementation.Type() != 'python':
return
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
msg_descriptor = descriptor.MakeDescriptor(
file_descriptor.message_type[0])
class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = msg_descriptor
msg = MessageClass()
msg_str = (
'flat: 0 '
'flat: 1 '
'flat: 2 ')
text_format.Merge(msg_str, msg)
self.assertEqual(msg.flat, [0, 1, 2])
def testHandWrittenReflection(self):
# Hand written extensions are only supported by the pure-Python
# implementation of the API.
if api_implementation.Type() != 'python':
return
FieldDescriptor = descriptor.FieldDescriptor
foo_field_descriptor = FieldDescriptor(
name='foo_field', full_name='MyProto.foo_field',
index=0, number=1, type=FieldDescriptor.TYPE_INT64,
cpp_type=FieldDescriptor.CPPTYPE_INT64,
label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
containing_type=None, message_type=None, enum_type=None,
is_extension=False, extension_scope=None,
options=descriptor_pb2.FieldOptions())
mydescriptor = descriptor.Descriptor(
name='MyProto', full_name='MyProto', filename='ignored',
containing_type=None, nested_types=[], enum_types=[],
fields=[foo_field_descriptor], extensions=[],
options=descriptor_pb2.MessageOptions())
class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
DESCRIPTOR = mydescriptor
myproto_instance = MyProtoClass()
self.assertEqual(0, myproto_instance.foo_field)
self.assertTrue(not myproto_instance.HasField('foo_field'))
myproto_instance.foo_field = 23
self.assertEqual(23, myproto_instance.foo_field)
self.assertTrue(myproto_instance.HasField('foo_field'))
def test_field_inheritance(self):
class Mock(object):
a = {}
RegisteredCreator.inherit_fields = True
RegisteredCreator.register = BaseRegister()
class Test(six.with_metaclass(RegisteredCreator, Mock)):
pass
self.assertEqual(Mock.a, Test.a)
RegisteredCreator.inherit_fields = False
def test_serializer_field_inheritance(self):
class Mock(object):
a = {}
SerializerCreator.inherit_fields = True
class Test(six.with_metaclass(SerializerCreator, Mock)):
__abstract__ = True
self.assertEqual(Mock.a, Test.a)
SerializerCreator.inherit_fields = False