2013-06-29 11:05:08 +04:00
|
|
|
# -- coding: utf-8 --
|
|
|
|
|
|
|
|
from __future__ import unicode_literals
|
2013-06-30 00:02:58 +04:00
|
|
|
from django.contrib.auth.models import User
|
2013-06-29 11:05:08 +04:00
|
|
|
from django.test import TestCase
|
|
|
|
from rest_framework.compat import patterns, url
|
|
|
|
from rest_framework.decorators import api_view
|
|
|
|
from rest_framework.response import Response
|
|
|
|
from rest_framework.test import APIClient
|
|
|
|
|
|
|
|
|
2013-06-30 00:02:58 +04:00
|
|
|
@api_view(['GET', 'POST'])
|
2013-06-29 11:05:08 +04:00
|
|
|
def mirror(request):
|
|
|
|
return Response({
|
2013-06-30 00:02:58 +04:00
|
|
|
'auth': request.META.get('HTTP_AUTHORIZATION', b''),
|
|
|
|
'user': request.user.username
|
2013-06-29 11:05:08 +04:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
urlpatterns = patterns('',
|
|
|
|
url(r'^view/$', mirror),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class CheckTestClient(TestCase):
|
|
|
|
urls = 'rest_framework.tests.test_testing'
|
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
self.client = APIClient()
|
|
|
|
|
|
|
|
def test_credentials(self):
|
2013-06-30 00:02:58 +04:00
|
|
|
"""
|
|
|
|
Setting `.credentials()` adds the required headers to each request.
|
|
|
|
"""
|
2013-06-29 11:05:08 +04:00
|
|
|
self.client.credentials(HTTP_AUTHORIZATION='example')
|
2013-06-30 00:02:58 +04:00
|
|
|
for _ in range(0, 3):
|
|
|
|
response = self.client.get('/view/')
|
|
|
|
self.assertEqual(response.data['auth'], 'example')
|
|
|
|
|
2013-06-30 01:53:15 +04:00
|
|
|
def test_force_authenticate(self):
|
2013-06-30 00:02:58 +04:00
|
|
|
"""
|
2013-06-30 01:53:15 +04:00
|
|
|
Setting `.force_authenticate()` forcibly authenticates each request.
|
2013-06-30 00:02:58 +04:00
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com')
|
2013-06-30 01:53:15 +04:00
|
|
|
self.client.force_authenticate(user)
|
2013-06-29 11:05:08 +04:00
|
|
|
response = self.client.get('/view/')
|
2013-06-30 00:02:58 +04:00
|
|
|
self.assertEqual(response.data['user'], 'example')
|
|
|
|
|
|
|
|
def test_csrf_exempt_by_default(self):
|
|
|
|
"""
|
|
|
|
By default, the test client is CSRF exempt.
|
|
|
|
"""
|
|
|
|
User.objects.create_user('example', 'example@example.com', 'password')
|
|
|
|
self.client.login(username='example', password='password')
|
|
|
|
response = self.client.post('/view/')
|
|
|
|
self.assertEqual(response.status_code, 200)
|
|
|
|
|
|
|
|
def test_explicitly_enforce_csrf_checks(self):
|
|
|
|
"""
|
|
|
|
The test client can enforce CSRF checks.
|
|
|
|
"""
|
|
|
|
client = APIClient(enforce_csrf_checks=True)
|
|
|
|
User.objects.create_user('example', 'example@example.com', 'password')
|
|
|
|
client.login(username='example', password='password')
|
|
|
|
response = client.post('/view/')
|
|
|
|
expected = {'detail': 'CSRF Failed: CSRF cookie not set.'}
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
self.assertEqual(response.data, expected)
|