This commit is contained in:
@@ -1,10 +1,10 @@
|
|||||||
import pytest
|
import pytest
|
||||||
import sys
|
from abc import abstractmethod
|
||||||
import os
|
from slic.utils.metaclasses import combine_classes, RegistryABC
|
||||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
from slic.core.registry import instances
|
||||||
from slic.utils.metaclasses import *
|
|
||||||
|
|
||||||
# Base classes
|
|
||||||
|
# Test combine two simple classes with unique methods
|
||||||
class A:
|
class A:
|
||||||
def method_a(self):
|
def method_a(self):
|
||||||
return "A"
|
return "A"
|
||||||
@@ -13,20 +13,37 @@ class B:
|
|||||||
def method_b(self):
|
def method_b(self):
|
||||||
return "B"
|
return "B"
|
||||||
|
|
||||||
# Combine A and B into a single metaclass
|
def test_combine_classes_combines_methods():
|
||||||
CombinedMeta = combine_classes(A, B)
|
# Dynamically combine A and B using combine_classes
|
||||||
|
Combined = combine_classes(A, B)
|
||||||
|
obj = Combined()
|
||||||
|
|
||||||
# Use it as metaclass for a new class
|
# Check that both methods are available
|
||||||
class MyCombinedClass(metaclass=CombinedMeta):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def test_combine_classes_as_metaclass():
|
|
||||||
|
|
||||||
obj = MyCombinedClass()
|
|
||||||
|
|
||||||
# Verify that methods from both base classes are available
|
|
||||||
assert isinstance(obj, MyCombinedClass)
|
|
||||||
assert isinstance(obj, A) # via metaclass
|
|
||||||
assert isinstance(obj, B) # via metaclass
|
|
||||||
assert obj.method_a() == "A"
|
assert obj.method_a() == "A"
|
||||||
assert obj.method_b() == "B"
|
assert obj.method_b() == "B"
|
||||||
|
|
||||||
|
|
||||||
|
# Test validate that RegistryABC correctly inherits from ABCMeta and RegistryMeta
|
||||||
|
def test_registryabc_combines_registrymeta_and_abcmeta():
|
||||||
|
# Define an abstract class using RegistryABC
|
||||||
|
class AbstractThing(RegistryABC):
|
||||||
|
@abstractmethod
|
||||||
|
def doit(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Cannot instantiate abstract class without implementing abstract methods
|
||||||
|
with pytest.raises(TypeError):
|
||||||
|
AbstractThing()
|
||||||
|
|
||||||
|
# Define a concrete subclass that implements the abstract method
|
||||||
|
class ConcreteThing(AbstractThing):
|
||||||
|
def doit(self):
|
||||||
|
return "yes"
|
||||||
|
|
||||||
|
obj = ConcreteThing()
|
||||||
|
|
||||||
|
# ABCMeta behavior: abstract method works
|
||||||
|
assert obj.doit() == "yes"
|
||||||
|
|
||||||
|
# RegistryMeta behavior: instance is automatically registered
|
||||||
|
assert obj in instances(AbstractThing)
|
||||||
|
|||||||
Reference in New Issue
Block a user