Skip to content

Commit

Permalink
Handle tuples same as lists in ValidationError detail context (encode…
Browse files Browse the repository at this point in the history
  • Loading branch information
seppeljordan authored Jan 6, 2021
1 parent 3db8877 commit 19655ed
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
6 changes: 4 additions & 2 deletions rest_framework/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def _get_error_details(data, default_code=None):
Descend into a nested data structure, forcing any
lazy translation strings or strings into `ErrorDetail`.
"""
if isinstance(data, list):
if isinstance(data, (list, tuple)):
ret = [
_get_error_details(item, default_code) for item in data
]
Expand Down Expand Up @@ -150,7 +150,9 @@ def __init__(self, detail=None, code=None):

# For validation failures, we may collect many errors together,
# so the details should always be coerced to a list if not already.
if not isinstance(detail, dict) and not isinstance(detail, list):
if isinstance(detail, tuple):
detail = list(detail)
elif not isinstance(detail, dict) and not isinstance(detail, list):
detail = [detail]

self.detail = _get_error_details(detail, code)
Expand Down
10 changes: 10 additions & 0 deletions tests/test_validation_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from rest_framework import serializers, status
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.test import APIRequestFactory
Expand Down Expand Up @@ -99,3 +100,12 @@ def test_function_based_view_exception_handler(self):
response = view(request)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.data == self.expected_response_data


class TestValidationErrorConvertsTuplesToLists(TestCase):
def test_validation_error_details(self):
error = ValidationError(detail=('message1', 'message2'))
assert isinstance(error.detail, list)
assert len(error.detail) == 2
assert str(error.detail[0]) == 'message1'
assert str(error.detail[1]) == 'message2'

0 comments on commit 19655ed

Please sign in to comment.