Convert ListField error indexes to str

Before this commit, child validation errors returned from ListField
would be held in a dictionary with the list index as an integer key.
This commit changes it so that the key is converted to str before being
used as a key.

The motivation for this is that rapidjson (an alternative python json
package) doesn't allow converting dicts with anything other than str
keys (i.e., it does not do any type conversion). Other json packages
(json, ujson, simplejson) tend to allow this and just do the type
conversion themselves. With this fix, json, ujson and simplejson will
continue to work as before, but rapidjson will become compatible
out-of-the-box without having to process the dictionary before rendering
to json.

One could perhaps argue that this conversion should rather be done in
rapidjson itself, or perhaps in glue/adapter code (e.g. in some
RapidJSONRenderer implementation); but then again, this seems like an
easy fix that hopefully doesn't break much, and saves a potentially
costly tree traversal in the renderer.

Existing tests have been updated to match this change in behavior. I
guess a new test using rapidjson could be useful, but I don't know what
DRF's policy is on integration tests that interface with third-party
libraries is.
This commit is contained in:
Sigve Sebastian Farstad 2019-01-28 13:37:12 +01:00
parent 87ade870c3
commit a5044cf4d2
2 changed files with 5 additions and 5 deletions

View File

@ -1681,7 +1681,7 @@ class ListField(Field):
try:
result.append(self.child.run_validation(item))
except ValidationError as e:
errors[idx] = e.detail
errors[str(idx)] = e.detail
if not errors:
return result

View File

@ -1880,7 +1880,7 @@ class TestListField(FieldValues):
]
invalid_inputs = [
('not a list', ['Expected a list of items but got type "str".']),
([1, 2, 'error', 'error'], {2: ['A valid integer is required.'], 3: ['A valid integer is required.']}),
([1, 2, 'error', 'error'], {'2': ['A valid integer is required.'], '3': ['A valid integer is required.']}),
({'one': 'two'}, ['Expected a list of items but got type "dict".'])
]
outputs = [
@ -1916,9 +1916,9 @@ class TestNestedListField(FieldValues):
([[]], [[]])
]
invalid_inputs = [
(['not a list'], {0: ['Expected a list of items but got type "str".']}),
([[1, 2, 'error'], ['error']], {0: {2: ['A valid integer is required.']}, 1: {0: ['A valid integer is required.']}}),
([{'one': 'two'}], {0: ['Expected a list of items but got type "dict".']})
(['not a list'], {'0': ['Expected a list of items but got type "str".']}),
([[1, 2, 'error'], ['error']], {'0': {'2': ['A valid integer is required.']}, '1': {'0': ['A valid integer is required.']}}),
([{'one': 'two'}], {'0': ['Expected a list of items but got type "dict".']})
]
outputs = [
([[1, 2], [3]], [[1, 2], [3]]),