Skip to content

Commit

Permalink
fix(base): do not fail repr() on lazy objects
Browse files Browse the repository at this point in the history
  • Loading branch information
nejch authored and JohnVillalovos committed Jun 20, 2022
1 parent 41ceaca commit 1efb123
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
15 changes: 11 additions & 4 deletions gitlab/base.py
Expand Up @@ -162,15 +162,15 @@ def pprint(self) -> None:
def __repr__(self) -> str:
name = self.__class__.__name__

if (self._id_attr and self._repr_attr) and (self._id_attr != self._repr_attr):
if (self._id_attr and self._repr_value) and (self._id_attr != self._repr_attr):
return (
f"<{name} {self._id_attr}:{self.get_id()} "
f"{self._repr_attr}:{getattr(self, self._repr_attr)}>"
f"{self._repr_attr}:{self._repr_value}>"
)
if self._id_attr:
return f"<{name} {self._id_attr}:{self.get_id()}>"
if self._repr_attr:
return f"<{name} {self._repr_attr}:{getattr(self, self._repr_attr)}>"
if self._repr_value:
return f"<{name} {self._repr_attr}:{self._repr_value}>"

return f"<{name}>"

Expand Down Expand Up @@ -229,6 +229,13 @@ def get_id(self) -> Optional[Union[int, str]]:
return None
return getattr(self, self._id_attr)

@property
def _repr_value(self) -> Optional[str]:
"""Safely returns the human-readable resource name if present."""
if self._repr_attr is None or not hasattr(self, self._repr_attr):
return None
return getattr(self, self._repr_attr)

@property
def encoded_id(self) -> Optional[Union[int, str]]:
"""Ensure that the ID is url-encoded so that it can be safely used in a URL
Expand Down
4 changes: 4 additions & 0 deletions tests/unit/test_base.py
Expand Up @@ -251,15 +251,19 @@ def test_dunder_str(self, fake_manager):
"<ReprObject id:1 name:fake>",
),
("name", "name", {"name": "fake"}, "<ReprObject name:fake>"),
("id", "name", {"id": 1}, "<ReprObject id:1>"),
(None, None, {}, "<ReprObject>"),
(None, "name", {"name": "fake"}, "<ReprObject name:fake>"),
(None, "name", {}, "<ReprObject>"),
],
ids=[
"GetMixin with id",
"GetMixin with id and _repr_attr",
"GetMixin with _repr_attr matching _id_attr",
"GetMixin with _repr_attr without _repr_attr value defined",
"GetWithoutIDMixin",
"GetWithoutIDMixin with _repr_attr",
"GetWithoutIDMixin with _repr_attr without _repr_attr value defined",
],
)
def test_dunder_repr(self, fake_manager, id_attr, repr_attr, attrs, expected_repr):
Expand Down

0 comments on commit 1efb123

Please sign in to comment.