Skip to content

Commit

Permalink
model._string_constraints: don't overwrite existing attributes in cas…
Browse files Browse the repository at this point in the history
…e of a conflict

Currently a string constraints decorator silently overwrites existing
attributes in case of a naming conflict. This behavior is changed such
that the decorator checks for existing attributes beforehand and raises
an exception in case of a conflict.
Futhermore, tests for this behavior are added.
  • Loading branch information
jkhsjdhjs authored and s-heppner committed Nov 14, 2023
1 parent 1d87d2d commit bc2ff75
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions basyx/aas/model/_string_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ def _setter(self, value: Optional[str]) -> None:
constraint_check_fn(value)
setattr(self, "_" + pub_attr_name, value)

if hasattr(decorated_class, pub_attr_name):
raise AttributeError(f"{decorated_class.__name__} already has an attribute named '{pub_attr_name}'")
setattr(decorated_class, pub_attr_name, property(_getter, _setter))
return decorated_class

Expand Down
16 changes: 16 additions & 0 deletions test/model/test_string_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,19 @@ def test_ignore_none_values(self) -> None:
dc = self.DummyClass(None) # type: ignore
self.assertIsNone(dc.some_attr)
dc.some_attr = None # type: ignore

def test_attribute_name_conflict(self) -> None:
# We don't want to overwrite existing attributes in case of a name conflict
with self.assertRaises(AttributeError) as cm:
@_string_constraints.constrain_revision_type("foo")
class DummyClass:
foo = property()
self.assertEqual("DummyClass already has an attribute named 'foo'", cm.exception.args[0])

with self.assertRaises(AttributeError) as cm:
@_string_constraints.constrain_label_type("bar")
class DummyClass2:
@property
def bar(self):
return "baz"
self.assertEqual("DummyClass2 already has an attribute named 'bar'", cm.exception.args[0])

0 comments on commit bc2ff75

Please sign in to comment.