| 1 |
""" |
| 2 |
Tests for content parsing, and form-overloaded content parsing. |
| 3 |
""" |
| 4 |
import copy |
| 5 |
import os.path |
| 6 |
import tempfile |
| 7 |
|
| 8 |
import pytest |
| 9 |
from django.contrib.auth import authenticate, login, logout |
| 10 |
from django.contrib.auth.middleware import AuthenticationMiddleware |
| 11 |
from django.contrib.auth.models import User |
| 12 |
from django.contrib.sessions.middleware import SessionMiddleware |
| 13 |
from django.core.exceptions import RequestDataTooBig |
| 14 |
from django.core.files.uploadedfile import SimpleUploadedFile |
| 15 |
from django.test import TestCase, override_settings |
| 16 |
from django.urls import path |
| 17 |
|
| 18 |
from rest_framework import status |
| 19 |
from rest_framework.authentication import SessionAuthentication |
| 20 |
from rest_framework.parsers import ( |
| 21 |
BaseParser, FormParser, JSONParser, MultiPartParser |
| 22 |
) |
| 23 |
from rest_framework.request import Request, WrappedAttributeError |
| 24 |
from rest_framework.response import Response |
| 25 |
from rest_framework.test import APIClient, APIRequestFactory |
| 26 |
from rest_framework.views import APIView |
| 27 |
|
| 28 |
factory = APIRequestFactory() |
| 29 |
|
| 30 |
|
| 31 |
class TestInitializer(TestCase): |
| 32 |
def test_request_type(self): |
| 33 |
request = Request(factory.get('/')) |
| 34 |
|
| 35 |
message = ( |
| 36 |
'The `request` argument must be an instance of ' |
| 37 |
'`django.http.HttpRequest`, not `rest_framework.request.Request`.' |
| 38 |
) |
| 39 |
with self.assertRaisesMessage(AssertionError, message): |
| 40 |
Request(request) |
| 41 |
|
| 42 |
|
| 43 |
class PlainTextParser(BaseParser): |
| 44 |
media_type = 'text/plain' |
| 45 |
|
| 46 |
def parse(self, stream, media_type=None, parser_context=None): |
| 47 |
""" |
| 48 |
Returns a 2-tuple of `(data, files)`. |
| 49 |
|
| 50 |
`data` will simply be a string representing the body of the request. |
| 51 |
`files` will always be `None`. |
| 52 |
""" |
| 53 |
return stream.read() |
| 54 |
|
| 55 |
|
| 56 |
class TestContentParsing(TestCase): |
| 57 |
def test_standard_behaviour_determines_no_content_GET(self): |
| 58 |
""" |
| 59 |
Ensure request.data returns empty QueryDict for GET request. |
| 60 |
""" |
| 61 |
request = Request(factory.get('/')) |
| 62 |
assert request.data == {} |
| 63 |
|
| 64 |
def test_standard_behaviour_determines_no_content_HEAD(self): |
| 65 |
""" |
| 66 |
Ensure request.data returns empty QueryDict for HEAD request. |
| 67 |
""" |
| 68 |
request = Request(factory.head('/')) |
| 69 |
assert request.data == {} |
| 70 |
|
| 71 |
def test_request_DATA_with_form_content(self): |
| 72 |
""" |
| 73 |
Ensure request.data returns content for POST request with form content. |
| 74 |
""" |
| 75 |
data = {'qwerty': 'uiop'} |
| 76 |
request = Request(factory.post('/', data)) |
| 77 |
request.parsers = (FormParser(), MultiPartParser()) |
| 78 |
assert list(request.data.items()) == list(data.items()) |
| 79 |
|
| 80 |
def test_request_DATA_with_text_content(self): |
| 81 |
""" |
| 82 |
Ensure request.data returns content for POST request with |
| 83 |
non-form content. |
| 84 |
""" |
| 85 |
content = b'qwerty' |
| 86 |
content_type = 'text/plain' |
| 87 |
request = Request(factory.post('/', content, content_type=content_type)) |
| 88 |
request.parsers = (PlainTextParser(),) |
| 89 |
assert request.data == content |
| 90 |
|
| 91 |
def test_request_POST_with_form_content(self): |
| 92 |
""" |
| 93 |
Ensure request.POST returns content for POST request with form content. |
| 94 |
""" |
| 95 |
data = {'qwerty': 'uiop'} |
| 96 |
request = Request(factory.post('/', data)) |
| 97 |
request.parsers = (FormParser(), MultiPartParser()) |
| 98 |
assert list(request.POST.items()) == list(data.items()) |
| 99 |
|
| 100 |
def test_request_POST_with_files(self): |
| 101 |
""" |
| 102 |
Ensure request.POST returns no content for POST request with file content. |
| 103 |
""" |
| 104 |
upload = SimpleUploadedFile("file.txt", b"file_content") |
| 105 |
request = Request(factory.post('/', {'upload': upload})) |
| 106 |
request.parsers = (FormParser(), MultiPartParser()) |
| 107 |
assert list(request.POST) == [] |
| 108 |
assert list(request.FILES) == ['upload'] |
| 109 |
|
| 110 |
def test_standard_behaviour_determines_form_content_PUT(self): |
| 111 |
""" |
| 112 |
Ensure request.data returns content for PUT request with form content. |
| 113 |
""" |
| 114 |
data = {'qwerty': 'uiop'} |
| 115 |
request = Request(factory.put('/', data)) |
| 116 |
request.parsers = (FormParser(), MultiPartParser()) |
| 117 |
assert list(request.data.items()) == list(data.items()) |
| 118 |
|
| 119 |
def test_standard_behaviour_determines_non_form_content_PUT(self): |
| 120 |
""" |
| 121 |
Ensure request.data returns content for PUT request with |
| 122 |
non-form content. |
| 123 |
""" |
| 124 |
content = b'qwerty' |
| 125 |
content_type = 'text/plain' |
| 126 |
request = Request(factory.put('/', content, content_type=content_type)) |
| 127 |
request.parsers = (PlainTextParser(), ) |
| 128 |
assert request.data == content |
| 129 |
|
| 130 |
def test_calling_data_fails_when_attribute_error_is_raised(self): |
| 131 |
""" |
| 132 |
Ensure attribute errors raised when parsing are properly re-raised. |
| 133 |
""" |
| 134 |
expected_message = "Internal error" |
| 135 |
|
| 136 |
class BrokenParser: |
| 137 |
media_type = "application/json" |
| 138 |
|
| 139 |
def parse(self, *args, **kwargs): |
| 140 |
raise AttributeError(expected_message) |
| 141 |
|
| 142 |
http_request = factory.post('/', data={}, format="json") |
| 143 |
request = Request(http_request) |
| 144 |
request.parsers = (BrokenParser,) |
| 145 |
|
| 146 |
with self.assertRaisesMessage(WrappedAttributeError, expected_message): |
| 147 |
request.data |
| 148 |
|
| 149 |
|
| 150 |
class TestDataUploadMaxMemorySize(TestCase): |
| 151 |
expected_message = 'Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.' |
| 152 |
|
| 153 |
@override_settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10) |
| 154 |
def test_request_data_with_oversized_json_raises_error(self): |
| 155 |
request = Request(factory.post( |
| 156 |
'/', |
| 157 |
b'{"qwerty": "uiop"}', |
| 158 |
content_type='application/json' |
| 159 |
)) |
| 160 |
request.parsers = (JSONParser(),) |
| 161 |
|
| 162 |
with self.assertRaisesMessage(RequestDataTooBig, self.expected_message): |
| 163 |
request.data |
| 164 |
|
| 165 |
@override_settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10) |
| 166 |
def test_request_data_with_oversized_form_raises_error(self): |
| 167 |
request = Request(factory.post( |
| 168 |
'/', |
| 169 |
b'qwerty=uiop&asdf=ghjkl', |
| 170 |
content_type='application/x-www-form-urlencoded' |
| 171 |
)) |
| 172 |
request.parsers = (FormParser(),) |
| 173 |
|
| 174 |
with self.assertRaisesMessage(RequestDataTooBig, self.expected_message): |
| 175 |
request.data |
| 176 |
|
| 177 |
@override_settings(DATA_UPLOAD_MAX_MEMORY_SIZE=1024) |
| 178 |
def test_request_data_with_small_bodies_continues_to_parse(self): |
| 179 |
json_request = Request(factory.post( |
| 180 |
'/', |
| 181 |
b'{"qwerty": "uiop"}', |
| 182 |
content_type='application/json' |
| 183 |
)) |
| 184 |
json_request.parsers = (JSONParser(),) |
| 185 |
assert json_request.data == {'qwerty': 'uiop'} |
| 186 |
|
| 187 |
form_request = Request(factory.post( |
| 188 |
'/', |
| 189 |
b'qwerty=uiop', |
| 190 |
content_type='application/x-www-form-urlencoded' |
| 191 |
)) |
| 192 |
form_request.parsers = (FormParser(),) |
| 193 |
assert form_request.data['qwerty'] == 'uiop' |
| 194 |
|
| 195 |
@override_settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10) |
| 196 |
def test_request_data_with_multipart_file_upload_is_unchanged(self): |
| 197 |
upload = SimpleUploadedFile('file.txt', b'x' * 32) |
| 198 |
request = Request(factory.post('/', {'upload': upload})) |
| 199 |
request.parsers = (FormParser(), MultiPartParser()) |
| 200 |
|
| 201 |
assert request.data['upload'].size == 32 |
| 202 |
|
| 203 |
@override_settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10) |
| 204 |
def test_request_data_with_custom_parser_keeps_streaming_path(self): |
| 205 |
content = b'x' * 32 |
| 206 |
request = Request(factory.post('/', content, content_type='text/plain')) |
| 207 |
request.parsers = (PlainTextParser(),) |
| 208 |
|
| 209 |
assert request.data == content |
| 210 |
assert not hasattr(request._request, '_body') |
| 211 |
|
| 212 |
|
| 213 |
class MockView(APIView): |
| 214 |
authentication_classes = (SessionAuthentication,) |
| 215 |
|
| 216 |
def post(self, request): |
| 217 |
if request.POST.get('example') is not None: |
| 218 |
return Response(status=status.HTTP_200_OK) |
| 219 |
|
| 220 |
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) |
| 221 |
|
| 222 |
|
| 223 |
class EchoView(APIView): |
| 224 |
def post(self, request): |
| 225 |
response = Response(status=status.HTTP_200_OK, data=request.data) |
| 226 |
response._request = request # test client sets `request` input |
| 227 |
return response |
| 228 |
|
| 229 |
|
| 230 |
class FileUploadView(APIView): |
| 231 |
def post(self, request): |
| 232 |
filenames = [file.temporary_file_path() for file in request.FILES.values()] |
| 233 |
|
| 234 |
for filename in filenames: |
| 235 |
assert os.path.exists(filename) |
| 236 |
|
| 237 |
return Response(status=status.HTTP_200_OK, data=filenames) |
| 238 |
|
| 239 |
|
| 240 |
urlpatterns = [ |
| 241 |
path('', MockView.as_view()), |
| 242 |
path('echo/', EchoView.as_view()), |
| 243 |
path('upload/', FileUploadView.as_view()) |
| 244 |
] |
| 245 |
|
| 246 |
|
| 247 |
@override_settings( |
| 248 |
ROOT_URLCONF='tests.test_request', |
| 249 |
FILE_UPLOAD_HANDLERS=['django.core.files.uploadhandler.TemporaryFileUploadHandler']) |
| 250 |
class FileUploadTests(TestCase): |
| 251 |
|
| 252 |
def test_fileuploads_closed_at_request_end(self): |
| 253 |
with tempfile.NamedTemporaryFile() as f: |
| 254 |
response = self.client.post('/upload/', {'file': f}) |
| 255 |
|
| 256 |
# sanity check that file was processed |
| 257 |
assert len(response.data) == 1 |
| 258 |
|
| 259 |
for file in response.data: |
| 260 |
assert not os.path.exists(file) |
| 261 |
|
| 262 |
|
| 263 |
@override_settings(ROOT_URLCONF='tests.test_request') |
| 264 |
class TestContentParsingWithAuthentication(TestCase): |
| 265 |
def setUp(self): |
| 266 |
self.csrf_client = APIClient(enforce_csrf_checks=True) |
| 267 |
self.username = 'john' |
| 268 |
self.email = '[email protected]' |
| 269 |
self.password = 'password' |
| 270 |
self.user = User.objects.create_user(self.username, self.email, self.password) |
| 271 |
|
| 272 |
def test_user_logged_in_authentication_has_POST_when_not_logged_in(self): |
| 273 |
""" |
| 274 |
Ensures request.POST exists after SessionAuthentication when user |
| 275 |
doesn't log in. |
| 276 |
""" |
| 277 |
content = {'example': 'example'} |
| 278 |
|
| 279 |
response = self.client.post('/', content) |
| 280 |
assert status.HTTP_200_OK == response.status_code |
| 281 |
|
| 282 |
response = self.csrf_client.post('/', content) |
| 283 |
assert status.HTTP_200_OK == response.status_code |
| 284 |
|
| 285 |
|
| 286 |
class TestUserSetter(TestCase): |
| 287 |
|
| 288 |
def setUp(self): |
| 289 |
# Pass request object through session middleware so session is |
| 290 |
# available to login and logout functions |
| 291 |
self.wrapped_request = factory.get('/') |
| 292 |
self.request = Request(self.wrapped_request) |
| 293 |
|
| 294 |
def dummy_get_response(request): # pragma: no cover |
| 295 |
return None |
| 296 |
|
| 297 |
SessionMiddleware(dummy_get_response).process_request(self.wrapped_request) |
| 298 |
AuthenticationMiddleware(dummy_get_response).process_request(self.wrapped_request) |
| 299 |
|
| 300 |
User.objects.create_user('ringo', '[email protected]', 'yellow') |
| 301 |
self.user = authenticate(username='ringo', password='yellow') |
| 302 |
|
| 303 |
def test_user_can_be_set(self): |
| 304 |
self.request.user = self.user |
| 305 |
assert self.request.user == self.user |
| 306 |
|
| 307 |
def test_user_can_login(self): |
| 308 |
login(self.request, self.user) |
| 309 |
assert self.request.user == self.user |
| 310 |
|
| 311 |
def test_user_can_logout(self): |
| 312 |
self.request.user = self.user |
| 313 |
assert not self.request.user.is_anonymous |
| 314 |
logout(self.request) |
| 315 |
assert self.request.user.is_anonymous |
| 316 |
|
| 317 |
def test_logged_in_user_is_set_on_wrapped_request(self): |
| 318 |
login(self.request, self.user) |
| 319 |
assert self.wrapped_request.user == self.user |
| 320 |
|
| 321 |
def test_calling_user_fails_when_attribute_error_is_raised(self): |
| 322 |
""" |
| 323 |
This proves that when an AttributeError is raised inside of the request.user |
| 324 |
property, that we can handle this and report the true, underlying error. |
| 325 |
""" |
| 326 |
class AuthRaisesAttributeError: |
| 327 |
def authenticate(self, request): |
| 328 |
self.MISSPELLED_NAME_THAT_DOESNT_EXIST |
| 329 |
|
| 330 |
request = Request(self.wrapped_request, authenticators=(AuthRaisesAttributeError(),)) |
| 331 |
|
| 332 |
# The middleware processes the underlying Django request, sets anonymous user |
| 333 |
assert self.wrapped_request.user.is_anonymous |
| 334 |
|
| 335 |
# The DRF request object does not have a user and should run authenticators |
| 336 |
expected = r"no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'" |
| 337 |
with pytest.raises(WrappedAttributeError, match=expected): |
| 338 |
request.user |
| 339 |
|
| 340 |
with pytest.raises(WrappedAttributeError, match=expected): |
| 341 |
hasattr(request, 'user') |
| 342 |
|
| 343 |
with pytest.raises(WrappedAttributeError, match=expected): |
| 344 |
login(request, self.user) |
| 345 |
|
| 346 |
|
| 347 |
class TestAuthSetter(TestCase): |
| 348 |
def test_auth_can_be_set(self): |
| 349 |
request = Request(factory.get('/')) |
| 350 |
request.auth = 'DUMMY' |
| 351 |
assert request.auth == 'DUMMY' |
| 352 |
|
| 353 |
|
| 354 |
class TestSecure(TestCase): |
| 355 |
|
| 356 |
def test_default_secure_false(self): |
| 357 |
request = Request(factory.get('/', secure=False)) |
| 358 |
assert request.scheme == 'http' |
| 359 |
|
| 360 |
def test_default_secure_true(self): |
| 361 |
request = Request(factory.get('/', secure=True)) |
| 362 |
assert request.scheme == 'https' |
| 363 |
|
| 364 |
|
| 365 |
class TestHttpRequest(TestCase): |
| 366 |
def test_repr(self): |
| 367 |
http_request = factory.get('/path') |
| 368 |
request = Request(http_request) |
| 369 |
|
| 370 |
assert repr(request) == "<rest_framework.request.Request: GET '/path'>" |
| 371 |
|
| 372 |
def test_attribute_access_proxy(self): |
| 373 |
http_request = factory.get('/') |
| 374 |
request = Request(http_request) |
| 375 |
|
| 376 |
inner_sentinel = object() |
| 377 |
http_request.inner_property = inner_sentinel |
| 378 |
assert request.inner_property is inner_sentinel |
| 379 |
|
| 380 |
outer_sentinel = object() |
| 381 |
request.inner_property = outer_sentinel |
| 382 |
assert request.inner_property is outer_sentinel |
| 383 |
|
| 384 |
def test_exception_proxy(self): |
| 385 |
# ensure the exception message is not for the underlying WSGIRequest |
| 386 |
http_request = factory.get('/') |
| 387 |
request = Request(http_request) |
| 388 |
|
| 389 |
message = "'Request' object has no attribute 'inner_property'" |
| 390 |
with self.assertRaisesMessage(AttributeError, message): |
| 391 |
request.inner_property |
| 392 |
|
| 393 |
@override_settings(ROOT_URLCONF='tests.test_request') |
| 394 |
def test_duplicate_request_json_data_access(self): |
| 395 |
""" |
| 396 |
JSON data is read via Django's request.body, so duplicate processing |
| 397 |
can reuse the cached body. |
| 398 |
""" |
| 399 |
response = APIClient().post('/echo/', data={'a': 'b'}, format='json') |
| 400 |
request = response._request |
| 401 |
|
| 402 |
assert request.content_type.startswith('application/json') |
| 403 |
assert response.data == {'a': 'b'} |
| 404 |
|
| 405 |
response = EchoView.as_view()(request._request) |
| 406 |
assert response.data == {'a': 'b'} |
| 407 |
|
| 408 |
@override_settings(ROOT_URLCONF='tests.test_request') |
| 409 |
def test_duplicate_request_form_data_access(self): |
| 410 |
""" |
| 411 |
Form data is copied to the underlying django request for middleware |
| 412 |
and file closing reasons. Duplicate processing of a request with form |
| 413 |
data is 'safe' in so far as accessing `request.POST` does not trigger |
| 414 |
the duplicate stream parse exception. |
| 415 |
""" |
| 416 |
response = APIClient().post('/echo/', data={'a': 'b'}) |
| 417 |
request = response._request |
| 418 |
|
| 419 |
# ensure that request stream was consumed by form parser |
| 420 |
assert request.content_type.startswith('multipart/form-data') |
| 421 |
assert response.data == {'a': ['b']} |
| 422 |
|
| 423 |
# pass same HttpRequest to view, form data set on underlying request |
| 424 |
response = EchoView.as_view()(request._request) |
| 425 |
request = response._request |
| 426 |
|
| 427 |
# ensure that request stream was consumed by form parser |
| 428 |
assert request.content_type.startswith('multipart/form-data') |
| 429 |
assert response.data == {'a': ['b']} |
| 430 |
|
| 431 |
|
| 432 |
class TestDeepcopy(TestCase): |
| 433 |
|
| 434 |
def test_deepcopy_works(self): |
| 435 |
request = Request(factory.get('/', secure=False)) |
| 436 |
copy.deepcopy(request) |
| 437 |
|
| 438 |
|
| 439 |
class TestTyping(TestCase): |
| 440 |
def test_request_is_subscriptable(self): |
| 441 |
assert Request is Request["foo"] |