Skip to content

Commit

Permalink
get_error_detail: use error_list to get code(s)
Browse files Browse the repository at this point in the history
Upstream PR: encode#5785
  • Loading branch information
blueyed committed Feb 20, 2018
1 parent 1e71bb5 commit 0c66e93
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
5 changes: 3 additions & 2 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,9 @@ def get_error_detail(exc_info):
"""
code = getattr(exc_info, 'code', None) or 'invalid'
return [
ErrorDetail(msg, code=code)
for msg in exc_info.messages
ErrorDetail(error.message % (error.params or ()),
code=error.code if error.code else code)
for error in exc_info.error_list
]


Expand Down
20 changes: 20 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from decimal import ROUND_DOWN, ROUND_UP, Decimal

import pytest
from django.core.exceptions import ValidationError as DjangoValidationError
from django.http import QueryDict
from django.test import TestCase, override_settings
from django.utils import six
Expand Down Expand Up @@ -2108,3 +2109,22 @@ class ExampleSerializer(serializers.Serializer):
"'ExampleSerializer', because it is the same as the default "
"method name. Remove the `method_name` argument."
)


class TestValidationErrorCode:
@pytest.mark.parametrize('use_list', (False, True))
def test_validationerror_code(self, use_list):

class ExampleSerializer(serializers.Serializer):
password = serializers.CharField()

def validate_password(self, obj):
err = DjangoValidationError('exc_msg', code='exc_code')
if use_list:
err = DjangoValidationError([err])
raise err

serializer = ExampleSerializer(data={'password': 123})
serializer.is_valid()
assert serializer.errors == {'password': ['exc_msg']}
assert serializer.errors['password'][0].code == 'exc_code'

0 comments on commit 0c66e93

Please sign in to comment.