Perform type check on passed request argument (#5618)

* Add test for wrapped request instance

* Add 'request' argument type check to Request init

* Fix metadata tests' request object
This commit is contained in:
Ryan P Kilby 2017-11-23 02:57:31 -05:00 committed by Carlton Gibson
parent c2c9225782
commit a91361dd2f
3 changed files with 20 additions and 3 deletions

View File

@ -11,7 +11,7 @@ The wrapped request then offers a richer API, in particular :
from __future__ import unicode_literals from __future__ import unicode_literals
from django.conf import settings from django.conf import settings
from django.http import QueryDict from django.http import HttpRequest, QueryDict
from django.http.multipartparser import parse_header from django.http.multipartparser import parse_header
from django.http.request import RawPostDataException from django.http.request import RawPostDataException
from django.utils import six from django.utils import six
@ -132,6 +132,12 @@ class Request(object):
def __init__(self, request, parsers=None, authenticators=None, def __init__(self, request, parsers=None, authenticators=None,
negotiator=None, parser_context=None): negotiator=None, parser_context=None):
assert isinstance(request, HttpRequest), (
'The `request` argument must be an instance of '
'`django.http.HttpRequest`, not `{}.{}`.'
.format(request.__class__.__module__, request.__class__.__name__)
)
self._request = request self._request = request
self.parsers = parsers or () self.parsers = parsers or ()
self.authenticators = authenticators or () self.authenticators = authenticators or ()

View File

@ -9,12 +9,11 @@ from rest_framework import (
exceptions, metadata, serializers, status, versioning, views exceptions, metadata, serializers, status, versioning, views
) )
from rest_framework.renderers import BrowsableAPIRenderer from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory from rest_framework.test import APIRequestFactory
from .models import BasicModel from .models import BasicModel
request = Request(APIRequestFactory().options('/')) request = APIRequestFactory().options('/')
class TestMetadata: class TestMetadata:

View File

@ -25,6 +25,18 @@ from rest_framework.views import APIView
factory = APIRequestFactory() factory = APIRequestFactory()
class TestInitializer(TestCase):
def test_request_type(self):
request = Request(factory.get('/'))
message = (
'The `request` argument must be an instance of '
'`django.http.HttpRequest`, not `rest_framework.request.Request`.'
)
with self.assertRaisesMessage(AssertionError, message):
Request(request)
class PlainTextParser(BaseParser): class PlainTextParser(BaseParser):
media_type = 'text/plain' media_type = 'text/plain'