Skip to content

Commit 75d755a

Browse files
committed
Add error handling for a raised AttributeError inside of a property call for "request.user".
1 parent 36fe656 commit 75d755a

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

rest_framework/request.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,10 @@ def user(self):
223223
by the authentication classes provided to the request.
224224
"""
225225
if not hasattr(self, '_user'):
226-
self._authenticate()
226+
try:
227+
self._authenticate()
228+
except AttributeError as error:
229+
raise RuntimeError("AttributeError: " + error.message)
227230
return self._user
228231

229232
@user.setter

tests/test_request.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -333,24 +333,27 @@ def test_user_can_login(self):
333333
login(self.request, self.user)
334334
self.assertEqual(self.request.user, self.user)
335335

336-
def test_calling_user_fails_when_exception_is_raised(self):
337-
class AuthRaisesError(object):
336+
def test_calling_user_fails_when_attribute_error_is_raised(self):
337+
"""
338+
This proves that when an AttributeError is raised inside of the request.user
339+
property, that we can handle this and report the true, underlying error.
340+
"""
341+
class AuthRaisesAttributeError(object):
338342
def authenticate(self, request):
339-
raise AttributeError('We should see this error!')
340-
# import rest_framework
341-
# rest_framework.MISSPELLED_NAME_THAT_DOESNT_EXIST
343+
import rest_framework
344+
rest_framework.MISSPELLED_NAME_THAT_DOESNT_EXIST
342345

343-
self.request = Request(factory.get('/'), authenticators=(AuthRaisesError(),))
346+
self.request = Request(factory.get('/'), authenticators=(AuthRaisesAttributeError(),))
344347
SessionMiddleware().process_request(self.request)
345348

346349
login(self.request, self.user)
347350
error_seen = None
348351
try:
349352
self.request.user
350-
except AttributeError as error:
353+
except RuntimeError as error:
351354
error_seen = error
352355

353-
self.assertEqual('We should see this error!', error_seen.message)
356+
self.assertEqual("AttributeError: 'module' object has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'", error_seen.message)
354357

355358
def test_user_can_logout(self):
356359
self.request.user = self.user

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy