Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

model._string_constraints: don't overwrite existing attributes in case of a conflict #152

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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])
Loading