Skip to content

Commit

Permalink
Merge pull request #419 from markkuleinio/use-display-field
Browse files Browse the repository at this point in the history
Use `display` field in `Record.__str__()` to support future models
  • Loading branch information
zachmoody committed Dec 11, 2021
2 parents c702fd1 + 1d0d6e1 commit 13f0915
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion pynetbox/core/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,12 @@ def __getitem__(self, k):
return dict(self)[k]

def __str__(self):
return getattr(self, "name", None) or getattr(self, "label", None) or ""
return (
getattr(self, "name", None)
or getattr(self, "label", None)
or getattr(self, "display", None)
or ""
)

def __repr__(self):
return str(self)
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/users/unknown_model.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"id": 1,
"display": "Unknown object"
}
17 changes: 17 additions & 0 deletions tests/test_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ class UsersTestCase(Generic.Tests):
)
def test_repr(self, _):
test = nb.users.get(1)
self.assertEqual(type(test), pynetbox.models.users.Users)
self.assertEqual(str(test), "user1")


Expand All @@ -105,3 +106,19 @@ def test_username(self, _):
self.assertEqual(len(permission.users), 1)
user = permission.users[0]
self.assertEqual(str(user), "user1")


class UnknownModelTestCase(unittest.TestCase):
""" This test validates that an unknown model is returned as Record object
and that the __str__() method correctly uses the 'display' field of the
object (introduced as a standard field in NetBox 2.11.0).
"""

@patch(
"requests.sessions.Session.get",
return_value=Response(fixture="users/unknown_model.json"),
)
def test_unknown_model(self, _):
unknown_obj = nb.unknown_model.get(1)
self.assertEqual(type(unknown_obj), pynetbox.core.response.Record)
self.assertEqual(str(unknown_obj), "Unknown object")

0 comments on commit 13f0915

Please sign in to comment.