Skip to content

Commit 769bc13

Browse files
blueyedcarltongibson
authored andcommitted
ErrorDetail: add __eq__/__ne__ and __repr__ (#5787)
This adds `__eq__` to handle `code` in comparisons. When comparing an ErrorDetail to a string (missing `code` there) the ErrorDetail's `code` is ignored, but otherwise it is taken into account.
1 parent 2677f59 commit 769bc13

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

rest_framework/exceptions.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from django.utils.translation import ungettext
1515

1616
from rest_framework import status
17+
from rest_framework.compat import unicode_to_repr
1718
from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
1819

1920

@@ -73,6 +74,22 @@ def __new__(cls, string, code=None):
7374
self.code = code
7475
return self
7576

77+
def __eq__(self, other):
78+
r = super(ErrorDetail, self).__eq__(other)
79+
try:
80+
return r and self.code == other.code
81+
except AttributeError:
82+
return r
83+
84+
def __ne__(self, other):
85+
return not self.__eq__(other)
86+
87+
def __repr__(self):
88+
return unicode_to_repr('ErrorDetail(string=%r, code=%r)' % (
89+
six.text_type(self),
90+
self.code,
91+
))
92+
7693

7794
class APIException(Exception):
7895
"""

tests/test_exceptions.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,33 @@ def test_get_full_details_with_throttling(self):
5353
'code': 'throttled'}
5454

5555

56+
class ErrorDetailTests(TestCase):
57+
58+
def test_eq(self):
59+
assert ErrorDetail('msg') == ErrorDetail('msg')
60+
assert ErrorDetail('msg', 'code') == ErrorDetail('msg', code='code')
61+
62+
assert ErrorDetail('msg') == 'msg'
63+
assert ErrorDetail('msg', 'code') == 'msg'
64+
65+
def test_ne(self):
66+
assert ErrorDetail('msg1') != ErrorDetail('msg2')
67+
assert ErrorDetail('msg') != ErrorDetail('msg', code='invalid')
68+
69+
assert ErrorDetail('msg1') != 'msg2'
70+
assert ErrorDetail('msg1', 'code') != 'msg2'
71+
72+
def test_repr(self):
73+
assert repr(ErrorDetail('msg1')) == \
74+
'ErrorDetail(string={!r}, code=None)'.format('msg1')
75+
assert repr(ErrorDetail('msg1', 'code')) == \
76+
'ErrorDetail(string={!r}, code={!r})'.format('msg1', 'code')
77+
78+
def test_str(self):
79+
assert str(ErrorDetail('msg1')) == 'msg1'
80+
assert str(ErrorDetail('msg1', 'code')) == 'msg1'
81+
82+
5683
class TranslationTests(TestCase):
5784

5885
@translation.override('fr')

0 commit comments

Comments
 (0)