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

Use display field in Record.__str__() to support future models #419

Merged
merged 2 commits into from
Dec 11, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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")