2013-07-01 16:59:05 +04:00
|
|
|
# Note that we import as `DjangoRequestFactory` and `DjangoClient` in order
|
2013-06-28 20:50:30 +04:00
|
|
|
# to make it harder for the user to import the wrong thing without realizing.
|
2016-10-10 15:03:46 +03:00
|
|
|
import io
|
2018-01-02 13:14:25 +03:00
|
|
|
from importlib import import_module
|
2016-10-10 15:03:46 +03:00
|
|
|
|
2013-06-28 20:50:30 +04:00
|
|
|
from django.conf import settings
|
2016-10-10 15:03:46 +03:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
|
|
|
from django.core.handlers.wsgi import WSGIHandler
|
2018-01-02 13:14:25 +03:00
|
|
|
from django.test import override_settings, testcases
|
2015-06-25 23:55:51 +03:00
|
|
|
from django.test.client import Client as DjangoClient
|
|
|
|
from django.test.client import ClientHandler
|
2018-02-14 23:12:14 +03:00
|
|
|
from django.test.client import RequestFactory as DjangoRequestFactory
|
2015-07-30 17:43:39 +03:00
|
|
|
from django.utils.encoding import force_bytes
|
2014-01-30 17:26:21 +04:00
|
|
|
from django.utils.http import urlencode
|
2015-06-18 16:38:29 +03:00
|
|
|
|
2016-10-10 15:03:46 +03:00
|
|
|
from rest_framework.compat import coreapi, requests
|
2013-07-01 16:59:05 +04:00
|
|
|
from rest_framework.settings import api_settings
|
|
|
|
|
|
|
|
|
|
|
|
def force_authenticate(request, user=None, token=None):
|
|
|
|
request._force_auth_user = user
|
|
|
|
request._force_auth_token = token
|
2013-06-28 20:17:39 +04:00
|
|
|
|
|
|
|
|
2016-10-10 15:03:46 +03:00
|
|
|
if requests is not None:
|
|
|
|
class HeaderDict(requests.packages.urllib3._collections.HTTPHeaderDict):
|
|
|
|
def get_all(self, key, default):
|
|
|
|
return self.getheaders(key)
|
|
|
|
|
2019-04-30 18:53:44 +03:00
|
|
|
class MockOriginalResponse:
|
2016-10-10 15:03:46 +03:00
|
|
|
def __init__(self, headers):
|
|
|
|
self.msg = HeaderDict(headers)
|
|
|
|
self.closed = False
|
|
|
|
|
|
|
|
def isclosed(self):
|
|
|
|
return self.closed
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
self.closed = True
|
|
|
|
|
|
|
|
class DjangoTestAdapter(requests.adapters.HTTPAdapter):
|
|
|
|
"""
|
|
|
|
A transport adapter for `requests`, that makes requests via the
|
|
|
|
Django WSGI app, rather than making actual HTTP requests over the network.
|
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
|
|
self.app = WSGIHandler()
|
|
|
|
self.factory = DjangoRequestFactory()
|
|
|
|
|
|
|
|
def get_environ(self, request):
|
|
|
|
"""
|
|
|
|
Given a `requests.PreparedRequest` instance, return a WSGI environ dict.
|
|
|
|
"""
|
|
|
|
method = request.method
|
|
|
|
url = request.url
|
|
|
|
kwargs = {}
|
|
|
|
|
|
|
|
# Set request content, if any exists.
|
|
|
|
if request.body is not None:
|
|
|
|
if hasattr(request.body, 'read'):
|
|
|
|
kwargs['data'] = request.body.read()
|
|
|
|
else:
|
|
|
|
kwargs['data'] = request.body
|
|
|
|
if 'content-type' in request.headers:
|
|
|
|
kwargs['content_type'] = request.headers['content-type']
|
|
|
|
|
|
|
|
# Set request headers.
|
|
|
|
for key, value in request.headers.items():
|
|
|
|
key = key.upper()
|
|
|
|
if key in ('CONNECTION', 'CONTENT-LENGTH', 'CONTENT-TYPE'):
|
|
|
|
continue
|
|
|
|
kwargs['HTTP_%s' % key.replace('-', '_')] = value
|
|
|
|
|
|
|
|
return self.factory.generic(method, url, **kwargs).environ
|
|
|
|
|
|
|
|
def send(self, request, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Make an outgoing request to the Django WSGI application.
|
|
|
|
"""
|
|
|
|
raw_kwargs = {}
|
|
|
|
|
|
|
|
def start_response(wsgi_status, wsgi_headers):
|
|
|
|
status, _, reason = wsgi_status.partition(' ')
|
|
|
|
raw_kwargs['status'] = int(status)
|
|
|
|
raw_kwargs['reason'] = reason
|
|
|
|
raw_kwargs['headers'] = wsgi_headers
|
|
|
|
raw_kwargs['version'] = 11
|
|
|
|
raw_kwargs['preload_content'] = False
|
|
|
|
raw_kwargs['original_response'] = MockOriginalResponse(wsgi_headers)
|
|
|
|
|
|
|
|
# Make the outgoing request via WSGI.
|
|
|
|
environ = self.get_environ(request)
|
|
|
|
wsgi_response = self.app(environ, start_response)
|
|
|
|
|
|
|
|
# Build the underlying urllib3.HTTPResponse
|
|
|
|
raw_kwargs['body'] = io.BytesIO(b''.join(wsgi_response))
|
|
|
|
raw = requests.packages.urllib3.HTTPResponse(**raw_kwargs)
|
|
|
|
|
|
|
|
# Build the requests.Response
|
|
|
|
return self.build_response(request, raw)
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class RequestsClient(requests.Session):
|
|
|
|
def __init__(self, *args, **kwargs):
|
2019-04-30 18:53:44 +03:00
|
|
|
super().__init__(*args, **kwargs)
|
2016-10-10 15:03:46 +03:00
|
|
|
adapter = DjangoTestAdapter()
|
|
|
|
self.mount('http://', adapter)
|
|
|
|
self.mount('https://', adapter)
|
|
|
|
|
|
|
|
def request(self, method, url, *args, **kwargs):
|
2017-02-01 15:20:06 +03:00
|
|
|
if not url.startswith('http'):
|
2016-10-10 15:03:46 +03:00
|
|
|
raise ValueError('Missing "http:" or "https:". Use a fully qualified URL, eg "http://testserver%s"' % url)
|
2019-04-30 18:53:44 +03:00
|
|
|
return super().request(method, url, *args, **kwargs)
|
2016-10-10 15:03:46 +03:00
|
|
|
|
|
|
|
else:
|
|
|
|
def RequestsClient(*args, **kwargs):
|
|
|
|
raise ImproperlyConfigured('requests must be installed in order to use RequestsClient.')
|
|
|
|
|
|
|
|
|
|
|
|
if coreapi is not None:
|
|
|
|
class CoreAPIClient(coreapi.Client):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self._session = RequestsClient()
|
|
|
|
kwargs['transports'] = [coreapi.transports.HTTPTransport(session=self.session)]
|
2019-04-30 18:53:44 +03:00
|
|
|
return super().__init__(*args, **kwargs)
|
2016-10-10 15:03:46 +03:00
|
|
|
|
|
|
|
@property
|
|
|
|
def session(self):
|
|
|
|
return self._session
|
|
|
|
|
|
|
|
else:
|
|
|
|
def CoreAPIClient(*args, **kwargs):
|
|
|
|
raise ImproperlyConfigured('coreapi must be installed in order to use CoreAPIClient.')
|
|
|
|
|
|
|
|
|
2013-06-28 20:50:30 +04:00
|
|
|
class APIRequestFactory(DjangoRequestFactory):
|
2013-07-01 16:59:05 +04:00
|
|
|
renderer_classes_list = api_settings.TEST_REQUEST_RENDERER_CLASSES
|
|
|
|
default_format = api_settings.TEST_REQUEST_DEFAULT_FORMAT
|
|
|
|
|
|
|
|
def __init__(self, enforce_csrf_checks=False, **defaults):
|
|
|
|
self.enforce_csrf_checks = enforce_csrf_checks
|
|
|
|
self.renderer_classes = {}
|
|
|
|
for cls in self.renderer_classes_list:
|
|
|
|
self.renderer_classes[cls.format] = cls
|
2019-04-30 18:53:44 +03:00
|
|
|
super().__init__(**defaults)
|
2013-06-28 20:17:39 +04:00
|
|
|
|
2013-06-28 20:50:30 +04:00
|
|
|
def _encode_data(self, data, format=None, content_type=None):
|
|
|
|
"""
|
|
|
|
Encode the data returning a two tuple of (bytes, content_type)
|
|
|
|
"""
|
2013-06-28 20:17:39 +04:00
|
|
|
|
2014-09-08 04:16:20 +04:00
|
|
|
if data is None:
|
2014-05-30 19:53:26 +04:00
|
|
|
return ('', content_type)
|
2013-06-28 20:17:39 +04:00
|
|
|
|
2013-06-28 20:50:30 +04:00
|
|
|
assert format is None or content_type is None, (
|
|
|
|
'You may not set both `format` and `content_type`.'
|
|
|
|
)
|
2013-06-28 20:17:39 +04:00
|
|
|
|
2013-06-28 20:50:30 +04:00
|
|
|
if content_type:
|
|
|
|
# Content type specified explicitly, treat data as a raw bytestring
|
2015-07-30 17:43:39 +03:00
|
|
|
ret = force_bytes(data, settings.DEFAULT_CHARSET)
|
2013-06-28 20:50:30 +04:00
|
|
|
|
|
|
|
else:
|
|
|
|
format = format or self.default_format
|
2013-07-01 16:59:05 +04:00
|
|
|
|
2014-08-19 16:28:07 +04:00
|
|
|
assert format in self.renderer_classes, (
|
2019-04-30 18:53:44 +03:00
|
|
|
"Invalid format '{}'. Available formats are {}. "
|
2014-08-19 16:28:07 +04:00
|
|
|
"Set TEST_REQUEST_RENDERER_CLASSES to enable "
|
|
|
|
"extra request formats.".format(
|
2013-07-01 16:59:05 +04:00
|
|
|
format,
|
2018-01-08 12:49:46 +03:00
|
|
|
', '.join(["'" + fmt + "'" for fmt in self.renderer_classes])
|
2013-07-01 16:59:05 +04:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Use format and render the data into a bytestring
|
2013-06-28 20:17:39 +04:00
|
|
|
renderer = self.renderer_classes[format]()
|
2013-06-28 20:50:30 +04:00
|
|
|
ret = renderer.render(data)
|
|
|
|
|
|
|
|
# Determine the content-type header from the renderer
|
2020-07-07 11:58:32 +03:00
|
|
|
content_type = renderer.media_type
|
|
|
|
if renderer.charset:
|
|
|
|
content_type = "{}; charset={}".format(
|
|
|
|
content_type, renderer.charset
|
|
|
|
)
|
2013-06-28 20:50:30 +04:00
|
|
|
|
2013-06-28 20:17:39 +04:00
|
|
|
# Coerce text to bytes if required.
|
2019-04-30 18:53:44 +03:00
|
|
|
if isinstance(ret, str):
|
2019-05-31 01:05:27 +03:00
|
|
|
ret = ret.encode(renderer.charset)
|
2013-06-28 20:17:39 +04:00
|
|
|
|
2013-06-28 20:50:30 +04:00
|
|
|
return ret, content_type
|
2013-06-28 20:17:39 +04:00
|
|
|
|
2014-01-30 17:26:21 +04:00
|
|
|
def get(self, path, data=None, **extra):
|
|
|
|
r = {
|
|
|
|
'QUERY_STRING': urlencode(data or {}, doseq=True),
|
|
|
|
}
|
2014-03-07 19:11:51 +04:00
|
|
|
if not data and '?' in path:
|
2016-09-02 19:00:03 +03:00
|
|
|
# Fix to support old behavior where you have the arguments in the
|
|
|
|
# url. See #1461.
|
|
|
|
query_string = force_bytes(path.split('?')[1])
|
2019-04-30 18:53:44 +03:00
|
|
|
query_string = query_string.decode('iso-8859-1')
|
2016-09-02 19:00:03 +03:00
|
|
|
r['QUERY_STRING'] = query_string
|
2014-01-30 17:26:21 +04:00
|
|
|
r.update(extra)
|
|
|
|
return self.generic('GET', path, **r)
|
2014-01-28 21:53:58 +04:00
|
|
|
|
2013-06-28 20:17:39 +04:00
|
|
|
def post(self, path, data=None, format=None, content_type=None, **extra):
|
|
|
|
data, content_type = self._encode_data(data, format, content_type)
|
|
|
|
return self.generic('POST', path, data, content_type, **extra)
|
|
|
|
|
|
|
|
def put(self, path, data=None, format=None, content_type=None, **extra):
|
|
|
|
data, content_type = self._encode_data(data, format, content_type)
|
|
|
|
return self.generic('PUT', path, data, content_type, **extra)
|
|
|
|
|
|
|
|
def patch(self, path, data=None, format=None, content_type=None, **extra):
|
|
|
|
data, content_type = self._encode_data(data, format, content_type)
|
|
|
|
return self.generic('PATCH', path, data, content_type, **extra)
|
2013-06-28 20:50:30 +04:00
|
|
|
|
|
|
|
def delete(self, path, data=None, format=None, content_type=None, **extra):
|
|
|
|
data, content_type = self._encode_data(data, format, content_type)
|
|
|
|
return self.generic('DELETE', path, data, content_type, **extra)
|
|
|
|
|
|
|
|
def options(self, path, data=None, format=None, content_type=None, **extra):
|
|
|
|
data, content_type = self._encode_data(data, format, content_type)
|
|
|
|
return self.generic('OPTIONS', path, data, content_type, **extra)
|
|
|
|
|
2017-08-31 04:36:05 +03:00
|
|
|
def generic(self, method, path, data='',
|
|
|
|
content_type='application/octet-stream', secure=False, **extra):
|
|
|
|
# Include the CONTENT_TYPE, regardless of whether or not data is empty.
|
|
|
|
if content_type is not None:
|
|
|
|
extra['CONTENT_TYPE'] = str(content_type)
|
|
|
|
|
2019-04-30 18:53:44 +03:00
|
|
|
return super().generic(
|
2017-08-31 04:36:05 +03:00
|
|
|
method, path, data, content_type, secure, **extra)
|
|
|
|
|
2013-07-01 16:59:05 +04:00
|
|
|
def request(self, **kwargs):
|
2019-04-30 18:53:44 +03:00
|
|
|
request = super().request(**kwargs)
|
2013-07-01 16:59:05 +04:00
|
|
|
request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
|
|
|
|
return request
|
|
|
|
|
2013-06-28 20:50:30 +04:00
|
|
|
|
2013-06-30 00:02:58 +04:00
|
|
|
class ForceAuthClientHandler(ClientHandler):
|
|
|
|
"""
|
|
|
|
A patched version of ClientHandler that can enforce authentication
|
|
|
|
on the outgoing requests.
|
|
|
|
"""
|
|
|
|
|
2013-06-29 11:05:08 +04:00
|
|
|
def __init__(self, *args, **kwargs):
|
2013-07-01 16:59:05 +04:00
|
|
|
self._force_user = None
|
|
|
|
self._force_token = None
|
2019-04-30 18:53:44 +03:00
|
|
|
super().__init__(*args, **kwargs)
|
2013-06-30 00:02:58 +04:00
|
|
|
|
|
|
|
def get_response(self, request):
|
|
|
|
# This is the simplest place we can hook into to patch the
|
|
|
|
# request object.
|
2013-07-01 16:59:05 +04:00
|
|
|
force_authenticate(request, self._force_user, self._force_token)
|
2019-04-30 18:53:44 +03:00
|
|
|
return super().get_response(request)
|
2013-06-30 00:02:58 +04:00
|
|
|
|
|
|
|
|
|
|
|
class APIClient(APIRequestFactory, DjangoClient):
|
|
|
|
def __init__(self, enforce_csrf_checks=False, **defaults):
|
2019-04-30 18:53:44 +03:00
|
|
|
super().__init__(**defaults)
|
2013-06-30 00:02:58 +04:00
|
|
|
self.handler = ForceAuthClientHandler(enforce_csrf_checks)
|
2013-06-29 11:05:08 +04:00
|
|
|
self._credentials = {}
|
|
|
|
|
|
|
|
def credentials(self, **kwargs):
|
2013-06-30 00:34:47 +04:00
|
|
|
"""
|
|
|
|
Sets headers that will be used on every outgoing request.
|
|
|
|
"""
|
2013-06-29 11:05:08 +04:00
|
|
|
self._credentials = kwargs
|
|
|
|
|
2013-06-30 01:53:15 +04:00
|
|
|
def force_authenticate(self, user=None, token=None):
|
2013-06-30 00:34:47 +04:00
|
|
|
"""
|
|
|
|
Forcibly authenticates outgoing requests with the given
|
|
|
|
user and/or token.
|
|
|
|
"""
|
2013-07-01 16:59:05 +04:00
|
|
|
self.handler._force_user = user
|
|
|
|
self.handler._force_token = token
|
2013-08-23 14:21:45 +04:00
|
|
|
if user is None:
|
|
|
|
self.logout() # Also clear any possible session info if required
|
2013-06-30 00:34:47 +04:00
|
|
|
|
2013-07-01 16:59:05 +04:00
|
|
|
def request(self, **kwargs):
|
2013-06-30 00:34:47 +04:00
|
|
|
# Ensure that any credentials set get added to every request.
|
2013-07-01 16:59:05 +04:00
|
|
|
kwargs.update(self._credentials)
|
2019-04-30 18:53:44 +03:00
|
|
|
return super().request(**kwargs)
|
2013-07-15 14:38:38 +04:00
|
|
|
|
2014-10-03 10:42:49 +04:00
|
|
|
def get(self, path, data=None, follow=False, **extra):
|
2019-04-30 18:53:44 +03:00
|
|
|
response = super().get(path, data=data, **extra)
|
2014-10-03 10:42:49 +04:00
|
|
|
if follow:
|
|
|
|
response = self._handle_redirects(response, **extra)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def post(self, path, data=None, format=None, content_type=None,
|
|
|
|
follow=False, **extra):
|
2019-04-30 18:53:44 +03:00
|
|
|
response = super().post(
|
2014-10-03 10:42:49 +04:00
|
|
|
path, data=data, format=format, content_type=content_type, **extra)
|
|
|
|
if follow:
|
|
|
|
response = self._handle_redirects(response, **extra)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def put(self, path, data=None, format=None, content_type=None,
|
|
|
|
follow=False, **extra):
|
2019-04-30 18:53:44 +03:00
|
|
|
response = super().put(
|
2014-10-03 10:42:49 +04:00
|
|
|
path, data=data, format=format, content_type=content_type, **extra)
|
|
|
|
if follow:
|
|
|
|
response = self._handle_redirects(response, **extra)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def patch(self, path, data=None, format=None, content_type=None,
|
|
|
|
follow=False, **extra):
|
2019-04-30 18:53:44 +03:00
|
|
|
response = super().patch(
|
2014-10-03 10:42:49 +04:00
|
|
|
path, data=data, format=format, content_type=content_type, **extra)
|
|
|
|
if follow:
|
|
|
|
response = self._handle_redirects(response, **extra)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def delete(self, path, data=None, format=None, content_type=None,
|
|
|
|
follow=False, **extra):
|
2019-04-30 18:53:44 +03:00
|
|
|
response = super().delete(
|
2014-10-03 10:42:49 +04:00
|
|
|
path, data=data, format=format, content_type=content_type, **extra)
|
|
|
|
if follow:
|
|
|
|
response = self._handle_redirects(response, **extra)
|
|
|
|
return response
|
|
|
|
|
|
|
|
def options(self, path, data=None, format=None, content_type=None,
|
|
|
|
follow=False, **extra):
|
2019-04-30 18:53:44 +03:00
|
|
|
response = super().options(
|
2014-10-03 10:42:49 +04:00
|
|
|
path, data=data, format=format, content_type=content_type, **extra)
|
|
|
|
if follow:
|
|
|
|
response = self._handle_redirects(response, **extra)
|
|
|
|
return response
|
|
|
|
|
2014-04-07 16:59:27 +04:00
|
|
|
def logout(self):
|
|
|
|
self._credentials = {}
|
2014-12-12 16:13:08 +03:00
|
|
|
|
|
|
|
# Also clear any `force_authenticate`
|
|
|
|
self.handler._force_user = None
|
|
|
|
self.handler._force_token = None
|
|
|
|
|
2015-02-20 22:12:39 +03:00
|
|
|
if self.session:
|
2019-04-30 18:53:44 +03:00
|
|
|
super().logout()
|
2014-04-07 16:59:27 +04:00
|
|
|
|
2013-07-15 14:38:38 +04:00
|
|
|
|
|
|
|
class APITransactionTestCase(testcases.TransactionTestCase):
|
|
|
|
client_class = APIClient
|
|
|
|
|
|
|
|
|
|
|
|
class APITestCase(testcases.TestCase):
|
|
|
|
client_class = APIClient
|
|
|
|
|
|
|
|
|
2016-02-18 22:35:45 +03:00
|
|
|
class APISimpleTestCase(testcases.SimpleTestCase):
|
|
|
|
client_class = APIClient
|
|
|
|
|
2013-07-16 00:54:13 +04:00
|
|
|
|
2016-02-18 22:35:45 +03:00
|
|
|
class APILiveServerTestCase(testcases.LiveServerTestCase):
|
|
|
|
client_class = APIClient
|
2018-01-02 13:14:25 +03:00
|
|
|
|
|
|
|
|
|
|
|
class URLPatternsTestCase(testcases.SimpleTestCase):
|
|
|
|
"""
|
|
|
|
Isolate URL patterns on a per-TestCase basis. For example,
|
|
|
|
|
|
|
|
class ATestCase(URLPatternsTestCase):
|
|
|
|
urlpatterns = [...]
|
|
|
|
|
|
|
|
def test_something(self):
|
|
|
|
...
|
|
|
|
|
|
|
|
class AnotherTestCase(URLPatternsTestCase):
|
|
|
|
urlpatterns = [...]
|
|
|
|
|
|
|
|
def test_something_else(self):
|
|
|
|
...
|
|
|
|
"""
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
# Get the module of the TestCase subclass
|
|
|
|
cls._module = import_module(cls.__module__)
|
|
|
|
cls._override = override_settings(ROOT_URLCONF=cls.__module__)
|
|
|
|
|
|
|
|
if hasattr(cls._module, 'urlpatterns'):
|
|
|
|
cls._module_urlpatterns = cls._module.urlpatterns
|
|
|
|
|
|
|
|
cls._module.urlpatterns = cls.urlpatterns
|
|
|
|
|
|
|
|
cls._override.enable()
|
2019-04-30 18:53:44 +03:00
|
|
|
super().setUpClass()
|
2018-01-02 13:14:25 +03:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
2019-04-30 18:53:44 +03:00
|
|
|
super().tearDownClass()
|
2018-01-02 13:14:25 +03:00
|
|
|
cls._override.disable()
|
|
|
|
|
|
|
|
if hasattr(cls, '_module_urlpatterns'):
|
|
|
|
cls._module.urlpatterns = cls._module_urlpatterns
|
|
|
|
else:
|
|
|
|
del cls._module.urlpatterns
|