mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-24 22:11:32 +00:00
Add get_type() method to TypeIdRegistryMixin
This commit is contained in:
parent
d9bcfb3705
commit
11bb1e492a
@ -1 +1 @@
|
||||
from .type_id_registry import TypeIdREgistryMixin
|
||||
from .type_id_registry import TypeIdRegistryMixin
|
||||
|
@ -1,23 +1,26 @@
|
||||
import pytest
|
||||
|
||||
from .type_id_registry import TypeIdREgistryMixin
|
||||
from .type_id_registry import TypeIdRegistryMixin
|
||||
|
||||
|
||||
def test_registry():
|
||||
class A(TypeIdREgistryMixin):
|
||||
class A(TypeIdRegistryMixin):
|
||||
_type_id_registry = {}
|
||||
class B(A):
|
||||
pass
|
||||
class C(A):
|
||||
pass
|
||||
class D(B):
|
||||
pass
|
||||
|
||||
# pylint: disable=protected-access
|
||||
assert A._type_id_registry['B'] == B
|
||||
assert A._type_id_registry['C'] == C
|
||||
assert A._type_id_registry['B'] == A.get_type('B') == B
|
||||
assert A._type_id_registry['C'] == A.get_type('C') == C
|
||||
assert A._type_id_registry['D'] == A.get_type('D') == D
|
||||
|
||||
|
||||
def test_build_by_type_id():
|
||||
class D(TypeIdREgistryMixin):
|
||||
class D(TypeIdRegistryMixin):
|
||||
_type_id_registry = {}
|
||||
built = []
|
||||
class E(D):
|
||||
|
@ -2,7 +2,7 @@ from abc import ABCMeta
|
||||
from contextlib import suppress
|
||||
|
||||
|
||||
class TypeIdREgistryMeta(ABCMeta):
|
||||
class TypeIdRegistryMeta(ABCMeta):
|
||||
def __init__(cls, name, bases, attrs):
|
||||
with suppress(AttributeError):
|
||||
if cls.__name__ in cls._type_id_registry:
|
||||
@ -11,11 +11,14 @@ class TypeIdREgistryMeta(ABCMeta):
|
||||
super().__init__(name, bases, attrs)
|
||||
|
||||
|
||||
class TypeIdREgistryMixin(metaclass=TypeIdREgistryMeta):
|
||||
class TypeIdRegistryMixin(metaclass=TypeIdRegistryMeta):
|
||||
@classmethod
|
||||
def build_type(cls, type_id, *args, **kwargs):
|
||||
def get_type(cls, type_id):
|
||||
try:
|
||||
instance_type = cls._type_id_registry[type_id]
|
||||
return instance_type(*args, **kwargs)
|
||||
return cls._type_id_registry[type_id]
|
||||
except KeyError:
|
||||
raise RuntimeError(f'No type with id {type_id}!')
|
||||
|
||||
@classmethod
|
||||
def build_type(cls, type_id, *args, **kwargs):
|
||||
return cls.get_type(type_id)(*args, **kwargs)
|
||||
|
Loading…
Reference in New Issue
Block a user