Skip to content
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

Added test to simulate an error I had where an imported reference failed... #1938

Closed
Closed
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
7 changes: 6 additions & 1 deletion rest_framework/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
from django.conf import settings
from django.http import QueryDict
from django.http.multipartparser import parse_header
from django.utils import six
from django.utils.datastructures import MultiValueDict
from rest_framework import HTTP_HEADER_ENCODING
from rest_framework import exceptions
from rest_framework.compat import BytesIO
from rest_framework.settings import api_settings
import sys


def is_form_media_type(media_type):
Expand Down Expand Up @@ -223,7 +225,10 @@ def user(self):
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
self._authenticate()
try:
self._authenticate()
except AttributeError as error:
six.reraise(RuntimeError, "AttributeError: " + str(error), sys.exc_info()[2])
return self._user

@user.setter
Expand Down
22 changes: 22 additions & 0 deletions tests/test_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,28 @@ def test_user_can_login(self):
login(self.request, self.user)
self.assertEqual(self.request.user, self.user)

def test_calling_user_fails_when_attribute_error_is_raised(self):
"""
This proves that when an AttributeError is raised inside of the request.user
property, that we can handle this and report the true, underlying error.
"""
class AuthRaisesAttributeError(object):
def authenticate(self, request):
import rest_framework
rest_framework.MISSPELLED_NAME_THAT_DOESNT_EXIST

self.request = Request(factory.get('/'), authenticators=(AuthRaisesAttributeError(),))
SessionMiddleware().process_request(self.request)

login(self.request, self.user)
error_seen = None
try:
self.request.user
except RuntimeError as error:
error_seen = error

self.assertEqual("AttributeError: 'module' object has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'", error_seen.message)

def test_user_can_logout(self):
self.request.user = self.user
self.assertFalse(self.request.user.is_anonymous())
Expand Down