Skip to content

ErrorDetail: add __eq__/__ne__ and __repr__ #5787

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

Merged
merged 1 commit into from
Jan 30, 2018
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions rest_framework/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from django.utils.translation import ungettext

from rest_framework import status
from rest_framework.compat import unicode_to_repr
from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList


Expand Down Expand Up @@ -73,6 +74,22 @@ def __new__(cls, string, code=None):
self.code = code
return self

def __eq__(self, other):
r = super(ErrorDetail, self).__eq__(other)
try:
return r and self.code == other.code
except AttributeError:
return r

def __ne__(self, other):
return not self.__eq__(other)

def __repr__(self):
return unicode_to_repr('ErrorDetail(string=%r, code=%r)' % (
six.text_type(self),
self.code,
))


class APIException(Exception):
"""
Expand Down
27 changes: 27 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,33 @@ def test_get_full_details_with_throttling(self):
'code': 'throttled'}


class ErrorDetailTests(TestCase):

def test_eq(self):
assert ErrorDetail('msg') == ErrorDetail('msg')
assert ErrorDetail('msg', 'code') == ErrorDetail('msg', code='code')

assert ErrorDetail('msg') == 'msg'
assert ErrorDetail('msg', 'code') == 'msg'

def test_ne(self):
assert ErrorDetail('msg1') != ErrorDetail('msg2')
assert ErrorDetail('msg') != ErrorDetail('msg', code='invalid')

assert ErrorDetail('msg1') != 'msg2'
assert ErrorDetail('msg1', 'code') != 'msg2'

def test_repr(self):
assert repr(ErrorDetail('msg1')) == \
'ErrorDetail(string={!r}, code=None)'.format('msg1')
assert repr(ErrorDetail('msg1', 'code')) == \
'ErrorDetail(string={!r}, code={!r})'.format('msg1', 'code')

def test_str(self):
assert str(ErrorDetail('msg1')) == 'msg1'
assert str(ErrorDetail('msg1', 'code')) == 'msg1'


class TranslationTests(TestCase):

@translation.override('fr')
Expand Down