2022-03-24 12:57:42 +03:00
|
|
|
import itertools
|
2015-06-25 23:55:51 +03:00
|
|
|
from io import BytesIO
|
2022-03-24 12:57:42 +03:00
|
|
|
from unittest.mock import patch
|
2015-06-25 23:55:51 +03:00
|
|
|
|
2021-09-22 11:00:49 +03:00
|
|
|
import django
|
2013-06-30 00:02:58 +04:00
|
|
|
from django.contrib.auth.models import User
|
2022-03-24 12:57:42 +03:00
|
|
|
from django.http import HttpResponseRedirect
|
2014-10-03 10:42:49 +04:00
|
|
|
from django.shortcuts import redirect
|
2016-06-01 17:31:00 +03:00
|
|
|
from django.test import TestCase, override_settings
|
2020-09-08 17:32:27 +03:00
|
|
|
from django.urls import path
|
2015-06-25 23:55:51 +03:00
|
|
|
|
2016-10-12 17:46:24 +03:00
|
|
|
from rest_framework import fields, serializers
|
2022-09-15 11:35:48 +03:00
|
|
|
from rest_framework.authtoken.models import Token
|
2013-06-29 11:05:08 +04:00
|
|
|
from rest_framework.decorators import api_view
|
|
|
|
from rest_framework.response import Response
|
2015-06-25 23:55:51 +03:00
|
|
|
from rest_framework.test import (
|
2018-01-02 13:14:25 +03:00
|
|
|
APIClient, APIRequestFactory, URLPatternsTestCase, force_authenticate
|
2015-06-25 23:55:51 +03:00
|
|
|
)
|
2013-06-29 11:05:08 +04:00
|
|
|
|
|
|
|
|
2022-03-24 12:57:42 +03:00
|
|
|
@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
|
2013-07-01 16:59:05 +04:00
|
|
|
def view(request):
|
2022-09-15 11:35:48 +03:00
|
|
|
data = {'auth': request.META.get('HTTP_AUTHORIZATION', b'')}
|
|
|
|
if request.user:
|
|
|
|
data['user'] = request.user.username
|
|
|
|
if request.auth:
|
|
|
|
data['token'] = request.auth.key
|
|
|
|
return Response(data)
|
2013-06-29 11:05:08 +04:00
|
|
|
|
|
|
|
|
2013-08-23 14:21:45 +04:00
|
|
|
@api_view(['GET', 'POST'])
|
|
|
|
def session_view(request):
|
|
|
|
active_session = request.session.get('active_session', False)
|
|
|
|
request.session['active_session'] = True
|
|
|
|
return Response({
|
|
|
|
'active_session': active_session
|
|
|
|
})
|
|
|
|
|
|
|
|
|
2014-10-03 10:42:49 +04:00
|
|
|
@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
|
|
|
|
def redirect_view(request):
|
|
|
|
return redirect('/view/')
|
|
|
|
|
|
|
|
|
2022-03-24 12:57:42 +03:00
|
|
|
@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
|
|
|
|
def redirect_307_308_view(request, code):
|
|
|
|
return HttpResponseRedirect('/view/', status=code)
|
|
|
|
|
|
|
|
|
2016-10-12 17:46:24 +03:00
|
|
|
class BasicSerializer(serializers.Serializer):
|
|
|
|
flag = fields.BooleanField(default=lambda: True)
|
|
|
|
|
|
|
|
|
|
|
|
@api_view(['POST'])
|
|
|
|
def post_view(request):
|
|
|
|
serializer = BasicSerializer(data=request.data)
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
return Response(serializer.validated_data)
|
|
|
|
|
|
|
|
|
2015-06-11 01:45:23 +03:00
|
|
|
urlpatterns = [
|
2020-09-08 17:32:27 +03:00
|
|
|
path('view/', view),
|
|
|
|
path('session-view/', session_view),
|
|
|
|
path('redirect-view/', redirect_view),
|
2022-03-24 12:57:42 +03:00
|
|
|
path('redirect-view/<int:code>/', redirect_307_308_view),
|
2020-09-08 17:32:27 +03:00
|
|
|
path('post-view/', post_view)
|
2015-06-11 01:45:23 +03:00
|
|
|
]
|
2013-06-29 11:05:08 +04:00
|
|
|
|
|
|
|
|
2016-06-01 17:31:00 +03:00
|
|
|
@override_settings(ROOT_URLCONF='tests.test_testing')
|
2013-07-01 16:59:05 +04:00
|
|
|
class TestAPITestClient(TestCase):
|
2013-06-29 11:05:08 +04:00
|
|
|
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/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['auth'] == 'example'
|
2013-06-30 00:02:58 +04:00
|
|
|
|
2022-09-15 11:35:48 +03:00
|
|
|
def test_force_authenticate_with_user(self):
|
2013-06-30 00:02:58 +04:00
|
|
|
"""
|
2022-09-15 11:35:48 +03:00
|
|
|
Setting `.force_authenticate()` with a user forcibly authenticates each
|
|
|
|
request with that user.
|
2013-06-30 00:02:58 +04:00
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com')
|
2022-09-15 11:35:48 +03:00
|
|
|
|
|
|
|
self.client.force_authenticate(user=user)
|
2013-06-29 11:05:08 +04:00
|
|
|
response = self.client.get('/view/')
|
2022-09-15 11:35:48 +03:00
|
|
|
|
|
|
|
assert response.data['user'] == 'example'
|
|
|
|
assert 'token' not in response.data
|
|
|
|
|
|
|
|
def test_force_authenticate_with_token(self):
|
|
|
|
"""
|
|
|
|
Setting `.force_authenticate()` with a token forcibly authenticates each
|
|
|
|
request with that token.
|
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com')
|
|
|
|
token = Token.objects.create(key='xyz', user=user)
|
|
|
|
|
|
|
|
self.client.force_authenticate(token=token)
|
|
|
|
response = self.client.get('/view/')
|
|
|
|
|
|
|
|
assert response.data['token'] == 'xyz'
|
|
|
|
assert 'user' not in response.data
|
|
|
|
|
|
|
|
def test_force_authenticate_with_user_and_token(self):
|
|
|
|
"""
|
|
|
|
Setting `.force_authenticate()` with a user and token forcibly
|
|
|
|
authenticates each request with that user and token.
|
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com')
|
|
|
|
token = Token.objects.create(key='xyz', user=user)
|
|
|
|
|
|
|
|
self.client.force_authenticate(user=user, token=token)
|
|
|
|
response = self.client.get('/view/')
|
|
|
|
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['user'] == 'example'
|
2022-09-15 11:35:48 +03:00
|
|
|
assert response.data['token'] == 'xyz'
|
2013-06-30 00:02:58 +04:00
|
|
|
|
2013-08-23 14:21:45 +04:00
|
|
|
def test_force_authenticate_with_sessions(self):
|
|
|
|
"""
|
|
|
|
Setting `.force_authenticate()` forcibly authenticates each request.
|
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com')
|
|
|
|
self.client.force_authenticate(user)
|
|
|
|
|
|
|
|
# First request does not yet have an active session
|
|
|
|
response = self.client.get('/session-view/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['active_session'] is False
|
2013-08-23 14:21:45 +04:00
|
|
|
|
2016-08-08 11:32:22 +03:00
|
|
|
# Subsequent requests have an active session
|
2013-08-23 14:21:45 +04:00
|
|
|
response = self.client.get('/session-view/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['active_session'] is True
|
2013-08-23 14:21:45 +04:00
|
|
|
|
2022-09-15 11:35:48 +03:00
|
|
|
# Force authenticating with `None` user and token should also logout
|
|
|
|
# the user session.
|
|
|
|
self.client.force_authenticate(user=None, token=None)
|
2013-08-23 14:21:45 +04:00
|
|
|
response = self.client.get('/session-view/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['active_session'] is False
|
2013-08-23 14:21:45 +04:00
|
|
|
|
2013-06-30 00:02:58 +04:00
|
|
|
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/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.status_code == 200
|
2013-06-30 00:02:58 +04:00
|
|
|
|
|
|
|
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.'}
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.status_code == 403
|
|
|
|
assert response.data == expected
|
2013-07-01 16:59:05 +04:00
|
|
|
|
2014-04-07 16:59:27 +04:00
|
|
|
def test_can_logout(self):
|
|
|
|
"""
|
2014-12-12 16:13:08 +03:00
|
|
|
`logout()` resets stored credentials
|
2014-04-07 16:59:27 +04:00
|
|
|
"""
|
|
|
|
self.client.credentials(HTTP_AUTHORIZATION='example')
|
|
|
|
response = self.client.get('/view/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['auth'] == 'example'
|
2014-04-07 16:59:27 +04:00
|
|
|
self.client.logout()
|
|
|
|
response = self.client.get('/view/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['auth'] == b''
|
2014-04-07 16:59:27 +04:00
|
|
|
|
2014-12-12 16:13:08 +03:00
|
|
|
def test_logout_resets_force_authenticate(self):
|
|
|
|
"""
|
|
|
|
`logout()` resets any `force_authenticate`
|
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com', 'password')
|
|
|
|
self.client.force_authenticate(user)
|
|
|
|
response = self.client.get('/view/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['user'] == 'example'
|
2014-12-12 16:13:08 +03:00
|
|
|
self.client.logout()
|
|
|
|
response = self.client.get('/view/')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['user'] == ''
|
2014-12-12 16:13:08 +03:00
|
|
|
|
2014-10-03 10:42:49 +04:00
|
|
|
def test_follow_redirect(self):
|
|
|
|
"""
|
|
|
|
Follow redirect by setting follow argument.
|
|
|
|
"""
|
2022-03-24 12:57:42 +03:00
|
|
|
for method in ('get', 'post', 'put', 'patch', 'delete', 'options'):
|
|
|
|
with self.subTest(method=method):
|
|
|
|
req_method = getattr(self.client, method)
|
|
|
|
response = req_method('/redirect-view/')
|
|
|
|
assert response.status_code == 302
|
|
|
|
response = req_method('/redirect-view/', follow=True)
|
|
|
|
assert response.redirect_chain is not None
|
|
|
|
assert response.status_code == 200
|
|
|
|
|
|
|
|
def test_follow_307_308_preserve_kwargs(self, *mocked_methods):
|
|
|
|
"""
|
|
|
|
Follow redirect by setting follow argument, and make sure the following
|
|
|
|
method called with appropriate kwargs.
|
|
|
|
"""
|
|
|
|
methods = ('get', 'post', 'put', 'patch', 'delete', 'options')
|
|
|
|
codes = (307, 308)
|
|
|
|
for method, code in itertools.product(methods, codes):
|
|
|
|
subtest_ctx = self.subTest(method=method, code=code)
|
|
|
|
patch_ctx = patch.object(self.client, method, side_effect=getattr(self.client, method))
|
|
|
|
with subtest_ctx, patch_ctx as req_method:
|
|
|
|
kwargs = {'data': {'example': 'test'}, 'format': 'json'}
|
|
|
|
response = req_method('/redirect-view/%s/' % code, follow=True, **kwargs)
|
|
|
|
assert response.redirect_chain is not None
|
|
|
|
assert response.status_code == 200
|
|
|
|
for _, call_args, call_kwargs in req_method.mock_calls:
|
|
|
|
assert all(call_kwargs[k] == kwargs[k] for k in kwargs if k in call_kwargs)
|
2014-10-03 10:42:49 +04:00
|
|
|
|
2015-07-14 16:49:44 +03:00
|
|
|
def test_invalid_multipart_data(self):
|
|
|
|
"""
|
|
|
|
MultiPart encoding cannot support nested data, so raise a helpful
|
|
|
|
error if the user attempts to do so.
|
|
|
|
"""
|
|
|
|
self.assertRaises(
|
|
|
|
AssertionError, self.client.post,
|
|
|
|
path='/view/', data={'valid': 123, 'invalid': {'a': 123}}
|
|
|
|
)
|
|
|
|
|
2016-10-12 17:46:24 +03:00
|
|
|
def test_empty_post_uses_default_boolean_value(self):
|
|
|
|
response = self.client.post(
|
|
|
|
'/post-view/',
|
|
|
|
data=None,
|
|
|
|
content_type='application/json'
|
|
|
|
)
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.status_code == 200
|
|
|
|
assert response.data == {"flag": True}
|
2016-10-12 17:46:24 +03:00
|
|
|
|
2013-07-01 16:59:05 +04:00
|
|
|
|
|
|
|
class TestAPIRequestFactory(TestCase):
|
|
|
|
def test_csrf_exempt_by_default(self):
|
|
|
|
"""
|
|
|
|
By default, the test client is CSRF exempt.
|
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com', 'password')
|
|
|
|
factory = APIRequestFactory()
|
|
|
|
request = factory.post('/view/')
|
|
|
|
request.user = user
|
|
|
|
response = view(request)
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.status_code == 200
|
2013-07-01 16:59:05 +04:00
|
|
|
|
|
|
|
def test_explicitly_enforce_csrf_checks(self):
|
|
|
|
"""
|
|
|
|
The test client can enforce CSRF checks.
|
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com', 'password')
|
|
|
|
factory = APIRequestFactory(enforce_csrf_checks=True)
|
|
|
|
request = factory.post('/view/')
|
|
|
|
request.user = user
|
|
|
|
response = view(request)
|
|
|
|
expected = {'detail': 'CSRF Failed: CSRF cookie not set.'}
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.status_code == 403
|
|
|
|
assert response.data == expected
|
2013-07-01 16:59:05 +04:00
|
|
|
|
2024-04-12 05:11:40 +03:00
|
|
|
def test_transform_factory_django_request_to_drf_request(self):
|
|
|
|
from rest_framework.views import APIView
|
|
|
|
|
|
|
|
factory = APIRequestFactory()
|
|
|
|
|
|
|
|
class DummyView(APIView):
|
|
|
|
...
|
|
|
|
|
|
|
|
request = factory.get('/', {'demo': 'test'})
|
|
|
|
DRF_request = DummyView().initialize_request(request)
|
|
|
|
assert DRF_request.query_params == {'demo': ['test']}
|
|
|
|
assert not hasattr(DRF_request, 'accepted_media_type')
|
|
|
|
|
|
|
|
DummyView().initial(DRF_request)
|
|
|
|
assert DRF_request.accepted_media_type == 'application/json'
|
|
|
|
|
|
|
|
request = factory.post('/', {'example': 'test'})
|
|
|
|
DRF_request = DummyView().initialize_request(request)
|
|
|
|
assert DRF_request.data.get('example') == 'test'
|
|
|
|
|
2013-07-01 16:59:05 +04:00
|
|
|
def test_invalid_format(self):
|
|
|
|
"""
|
|
|
|
Attempting to use a format that is not configured will raise an
|
|
|
|
assertion error.
|
|
|
|
"""
|
|
|
|
factory = APIRequestFactory()
|
2014-08-19 16:28:07 +04:00
|
|
|
self.assertRaises(
|
|
|
|
AssertionError, factory.post,
|
2013-07-01 16:59:05 +04:00
|
|
|
path='/view/', data={'example': 1}, format='xml'
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_force_authenticate(self):
|
|
|
|
"""
|
|
|
|
Setting `force_authenticate()` forcibly authenticates the request.
|
|
|
|
"""
|
|
|
|
user = User.objects.create_user('example', 'example@example.com')
|
|
|
|
factory = APIRequestFactory()
|
|
|
|
request = factory.get('/view')
|
|
|
|
force_authenticate(request, user=user)
|
|
|
|
response = view(request)
|
2017-03-10 12:00:00 +03:00
|
|
|
assert response.data['user'] == 'example'
|
2014-01-28 19:54:50 +04:00
|
|
|
|
|
|
|
def test_upload_file(self):
|
|
|
|
# This is a 1x1 black png
|
|
|
|
simple_png = BytesIO(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\x9cc````\x00\x00\x00\x05\x00\x01\xa5\xf6E@\x00\x00\x00\x00IEND\xaeB`\x82')
|
|
|
|
simple_png.name = 'test.png'
|
|
|
|
factory = APIRequestFactory()
|
|
|
|
factory.post('/', data={'image': simple_png})
|
2014-03-07 19:11:51 +04:00
|
|
|
|
|
|
|
def test_request_factory_url_arguments(self):
|
|
|
|
"""
|
|
|
|
This is a non regression test against #1461
|
|
|
|
"""
|
|
|
|
factory = APIRequestFactory()
|
|
|
|
request = factory.get('/view/?demo=test')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert dict(request.GET) == {'demo': ['test']}
|
2014-03-07 19:11:51 +04:00
|
|
|
request = factory.get('/view/', {'demo': 'test'})
|
2017-03-10 12:00:00 +03:00
|
|
|
assert dict(request.GET) == {'demo': ['test']}
|
2016-09-02 19:00:03 +03:00
|
|
|
|
|
|
|
def test_request_factory_url_arguments_with_unicode(self):
|
|
|
|
factory = APIRequestFactory()
|
|
|
|
request = factory.get('/view/?demo=testé')
|
2017-03-10 12:00:00 +03:00
|
|
|
assert dict(request.GET) == {'demo': ['testé']}
|
2016-09-02 19:00:03 +03:00
|
|
|
request = factory.get('/view/', {'demo': 'testé'})
|
2017-03-10 12:00:00 +03:00
|
|
|
assert dict(request.GET) == {'demo': ['testé']}
|
2017-08-22 22:02:18 +03:00
|
|
|
|
|
|
|
def test_empty_request_content_type(self):
|
|
|
|
factory = APIRequestFactory()
|
|
|
|
request = factory.post(
|
|
|
|
'/post-view/',
|
|
|
|
data=None,
|
|
|
|
content_type='application/json',
|
|
|
|
)
|
2017-08-31 04:36:05 +03:00
|
|
|
assert request.META['CONTENT_TYPE'] == 'application/json'
|
2018-01-02 13:14:25 +03:00
|
|
|
|
|
|
|
|
2021-09-22 11:00:49 +03:00
|
|
|
def check_urlpatterns(cls):
|
|
|
|
assert urlpatterns is not cls.urlpatterns
|
|
|
|
|
|
|
|
|
2018-01-02 13:14:25 +03:00
|
|
|
class TestUrlPatternTestCase(URLPatternsTestCase):
|
|
|
|
urlpatterns = [
|
2020-09-08 17:32:27 +03:00
|
|
|
path('', view),
|
2018-01-02 13:14:25 +03:00
|
|
|
]
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
assert urlpatterns is not cls.urlpatterns
|
2019-04-30 18:53:44 +03:00
|
|
|
super().setUpClass()
|
2018-01-02 13:14:25 +03:00
|
|
|
assert urlpatterns is cls.urlpatterns
|
|
|
|
|
2021-09-22 11:00:49 +03:00
|
|
|
if django.VERSION > (4, 0):
|
|
|
|
cls.addClassCleanup(
|
|
|
|
check_urlpatterns,
|
|
|
|
cls
|
|
|
|
)
|
|
|
|
|
|
|
|
if django.VERSION < (4, 0):
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
|
|
|
assert urlpatterns is cls.urlpatterns
|
|
|
|
super().tearDownClass()
|
|
|
|
assert urlpatterns is not cls.urlpatterns
|
2018-01-02 13:14:25 +03:00
|
|
|
|
|
|
|
def test_urlpatterns(self):
|
|
|
|
assert self.client.get('/').status_code == 200
|
|
|
|
|
|
|
|
|
|
|
|
class TestExistingPatterns(TestCase):
|
|
|
|
def test_urlpatterns(self):
|
|
|
|
# sanity test to ensure that this test module does not have a '/' route
|
|
|
|
assert self.client.get('/').status_code == 404
|