2015-06-11 01:45:23 +03:00
|
|
|
from django.conf.urls import url
|
2014-12-16 17:41:16 +03:00
|
|
|
from django.contrib.auth.models import User
|
2016-06-01 17:31:00 +03:00
|
|
|
from django.test import override_settings
|
2015-06-25 23:55:51 +03:00
|
|
|
|
2014-12-16 17:41:16 +03:00
|
|
|
from rest_framework.authentication import TokenAuthentication
|
|
|
|
from rest_framework.authtoken.models import Token
|
|
|
|
from rest_framework.test import APITestCase
|
|
|
|
from rest_framework.views import APIView
|
|
|
|
|
2015-06-11 01:45:23 +03:00
|
|
|
urlpatterns = [
|
2014-12-16 17:41:16 +03:00
|
|
|
url(r'^$', APIView.as_view(authentication_classes=(TokenAuthentication,))),
|
2015-06-11 01:45:23 +03:00
|
|
|
]
|
2014-12-16 17:41:16 +03:00
|
|
|
|
|
|
|
|
|
|
|
class MyMiddleware(object):
|
|
|
|
|
|
|
|
def process_response(self, request, response):
|
|
|
|
assert hasattr(request, 'user'), '`user` is not set on request'
|
|
|
|
assert request.user.is_authenticated(), '`user` is not authenticated'
|
|
|
|
return response
|
|
|
|
|
|
|
|
|
2016-06-01 17:31:00 +03:00
|
|
|
@override_settings(ROOT_URLCONF='tests.test_middleware')
|
2014-12-16 17:41:16 +03:00
|
|
|
class TestMiddleware(APITestCase):
|
|
|
|
def test_middleware_can_access_user_when_processing_response(self):
|
|
|
|
user = User.objects.create_user('john', 'john@example.com', 'password')
|
|
|
|
key = 'abcd1234'
|
|
|
|
Token.objects.create(key=key, user=user)
|
|
|
|
|
|
|
|
with self.settings(
|
|
|
|
MIDDLEWARE_CLASSES=('tests.test_middleware.MyMiddleware',)
|
|
|
|
):
|
|
|
|
auth = 'Token ' + key
|
|
|
|
self.client.get('/', HTTP_AUTHORIZATION=auth)
|