Skip to content

Commit f58e7ee

Browse files
author
Zach Moody
committed
Fixes #221 - Account for changes in choices field
NetBox 2.7 changes the structure of the objects returned in choice fields temporarily until v2.8 is released. This PR causes these fields to serialize to `value` when both `id` and `value` fields are present.
1 parent 479f0db commit f58e7ee

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

pynetbox/core/response.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@ def get_return(lookup, return_fields=None):
2525
"""Returns simple representations for items passed to lookup.
2626
2727
Used to return a "simple" representation of objects and collections
28-
sent to it via lookup. If lookup is an IPNetwork object immediately
29-
return the string representation. Otherwise, we look to see if
28+
sent to it via lookup. Otherwise, we look to see if
3029
lookup is a "choices" field (dict with only 'id' and 'value')
3130
or a nested_return. Finally, we check if it's a Record, if
3231
so simply return a string. Order is important due to nested_return
@@ -41,6 +40,10 @@ def get_return(lookup, return_fields=None):
4140
return lookup[i]
4241
else:
4342
if hasattr(lookup, i):
43+
# check if this is a "choices" field record
44+
# from a NetBox 2.7 server.
45+
if sorted(dict(lookup)) == sorted(["id", "value", "label"]):
46+
return getattr(lookup, "value")
4447
return getattr(lookup, i)
4548

4649
if isinstance(lookup, Record):

tests/unit/test_response.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,43 @@ def test_dict(self):
112112
test = Record(test_values, None, None)
113113
self.assertEqual(dict(test), test_values)
114114

115+
def test_choices_idempotence_prev27(self):
116+
test_values = {
117+
"id": 123,
118+
"choices_test": {
119+
"value": 1,
120+
"label": "test",
121+
},
122+
}
123+
test = Record(test_values, None, None)
124+
test.choices_test = 1
125+
self.assertFalse(test._diff())
126+
127+
def test_choices_idempotence_v27(self):
128+
test_values = {
129+
"id": 123,
130+
"choices_test": {
131+
"value": "test",
132+
"label": "test",
133+
"id": 1,
134+
},
135+
}
136+
test = Record(test_values, None, None)
137+
test.choices_test = "test"
138+
self.assertFalse(test._diff())
139+
140+
def test_choices_idempotence_v28(self):
141+
test_values = {
142+
"id": 123,
143+
"choices_test": {
144+
"value": "test",
145+
"label": "test",
146+
},
147+
}
148+
test = Record(test_values, None, None)
149+
test.choices_test = "test"
150+
self.assertFalse(test._diff())
151+
115152
def test_hash(self):
116153
endpoint = Mock()
117154
endpoint.name = "test-endpoint"

0 commit comments

Comments
 (0)