Skip to content

Commit 8538fd4

Browse files
committed
Check for collisions in typ strings
1 parent dfa7581 commit 8538fd4

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

gemd/entity/dict_serializable.py

+3
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ def __new__(mcs, name, bases, *args,
2626
def __init__(cls, name, bases, *args, typ: str = None, skip: Set[str] = frozenset(), **kwargs):
2727
super().__init__(name, bases, *args, **kwargs)
2828
if typ is not None:
29+
if typ in cls._class and not issubclass(cls, cls._class.get(typ)):
30+
raise ValueError(f"{cls} attempted to take typ {typ} from {cls._class.get(typ)}, "
31+
f"which is not its ancestor.")
2932
cls.typ = typ
3033
cls._class[typ] = cls
3134
elif not hasattr(cls, "typ"):

gemd/entity/tests/test_entity.py

+18
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,21 @@ class TestConditionTemplate(
144144
pass
145145

146146
TestConditionTemplate(name="Me", bounds=MolecularStructureBounds())
147+
148+
149+
def test_derived_collision():
150+
"""Test that an exception is thrown when multiple classes claim the same typ."""
151+
# One parent
152+
class Parent(DictSerializable, typ="mine"):
153+
pass
154+
155+
# First kid is fine
156+
class ElderChild(Parent, typ="mine"):
157+
pass
158+
159+
# Mapping transferred
160+
assert DictSerializable.class_mapping["mine"] is ElderChild
161+
162+
with pytest.raises(ValueError, match="mine"):
163+
class SecondChild(Parent, typ="mine"):
164+
pass

0 commit comments

Comments
 (0)