2012-08-13 05:25:42 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2007-02-11 08:23:31 +08:00
|
|
|
import sys
|
2008-06-06 21:39:42 +08:00
|
|
|
import os
|
2009-04-11 17:20:10 +08:00
|
|
|
import re
|
2010-08-07 01:14:02 +08:00
|
|
|
import mimetypes
|
2011-02-21 18:12:23 +08:00
|
|
|
from copy import copy
|
2012-05-06 01:47:03 +08:00
|
|
|
from io import BytesIO
|
2012-07-20 21:36:52 +08:00
|
|
|
try:
|
|
|
|
from urllib.parse import unquote, urlparse, urlsplit
|
|
|
|
except ImportError: # Python 2
|
|
|
|
from urllib import unquote
|
|
|
|
from urlparse import urlparse, urlsplit
|
2008-07-02 12:34:05 +08:00
|
|
|
|
2007-02-09 21:47:36 +08:00
|
|
|
from django.conf import settings
|
2007-05-05 23:16:15 +08:00
|
|
|
from django.contrib.auth import authenticate, login
|
2006-08-27 20:24:59 +08:00
|
|
|
from django.core.handlers.base import BaseHandler
|
|
|
|
from django.core.handlers.wsgi import WSGIRequest
|
2013-01-01 17:12:06 +08:00
|
|
|
from django.core.signals import (request_started, request_finished,
|
|
|
|
got_request_exception)
|
2013-02-18 18:37:26 +08:00
|
|
|
from django.db import close_old_connections
|
2009-02-27 21:14:59 +08:00
|
|
|
from django.http import SimpleCookie, HttpRequest, QueryDict
|
2007-08-28 21:03:22 +08:00
|
|
|
from django.template import TemplateDoesNotExist
|
2006-09-02 17:26:24 +08:00
|
|
|
from django.test import signals
|
2006-08-27 20:24:59 +08:00
|
|
|
from django.utils.functional import curry
|
2012-12-17 17:47:38 +08:00
|
|
|
from django.utils.encoding import force_bytes, force_str
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
from django.utils.http import urlencode
|
2009-03-19 00:55:59 +08:00
|
|
|
from django.utils.importlib import import_module
|
2007-09-15 03:55:24 +08:00
|
|
|
from django.utils.itercompat import is_iterable
|
2012-07-20 18:18:38 +08:00
|
|
|
from django.utils import six
|
2009-03-18 18:46:55 +08:00
|
|
|
from django.test.utils import ContextList
|
2006-08-27 20:24:59 +08:00
|
|
|
|
2010-10-19 00:08:25 +08:00
|
|
|
__all__ = ('Client', 'RequestFactory', 'encode_file', 'encode_multipart')
|
|
|
|
|
2010-10-18 23:53:55 +08:00
|
|
|
|
2007-02-17 08:23:09 +08:00
|
|
|
BOUNDARY = 'BoUnDaRyStRiNg'
|
|
|
|
MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
|
2009-04-11 17:20:10 +08:00
|
|
|
CONTENT_TYPE_RE = re.compile('.*; charset=([\w\d-]+);?')
|
2008-07-02 12:34:05 +08:00
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
class FakePayload(object):
|
|
|
|
"""
|
2012-05-06 01:47:03 +08:00
|
|
|
A wrapper around BytesIO that restricts what can be read since data from
|
2008-07-01 23:10:51 +08:00
|
|
|
the network can't be seeked and cannot be read outside of its content
|
|
|
|
length. This makes sure that views can't do anything under the test client
|
|
|
|
that wouldn't work in Real Life.
|
|
|
|
"""
|
2012-10-20 21:36:24 +08:00
|
|
|
def __init__(self, content=None):
|
|
|
|
self.__content = BytesIO()
|
|
|
|
self.__len = 0
|
|
|
|
self.read_started = False
|
|
|
|
if content is not None:
|
|
|
|
self.write(content)
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return self.__len
|
2008-07-01 23:10:51 +08:00
|
|
|
|
|
|
|
def read(self, num_bytes=None):
|
2012-10-20 21:36:24 +08:00
|
|
|
if not self.read_started:
|
|
|
|
self.__content.seek(0)
|
|
|
|
self.read_started = True
|
2008-07-01 23:10:51 +08:00
|
|
|
if num_bytes is None:
|
2011-01-21 09:04:05 +08:00
|
|
|
num_bytes = self.__len or 0
|
2008-07-01 23:10:51 +08:00
|
|
|
assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data."
|
|
|
|
content = self.__content.read(num_bytes)
|
|
|
|
self.__len -= num_bytes
|
|
|
|
return content
|
|
|
|
|
2012-10-20 21:36:24 +08:00
|
|
|
def write(self, content):
|
|
|
|
if self.read_started:
|
|
|
|
raise ValueError("Unable to write a payload after he's been read")
|
|
|
|
content = force_bytes(content)
|
|
|
|
self.__content.write(content)
|
|
|
|
self.__len += len(content)
|
|
|
|
|
2008-07-02 12:34:05 +08:00
|
|
|
|
2012-12-30 22:19:22 +08:00
|
|
|
def closing_iterator_wrapper(iterable, close):
|
|
|
|
try:
|
|
|
|
for item in iterable:
|
|
|
|
yield item
|
|
|
|
finally:
|
2013-02-18 18:37:26 +08:00
|
|
|
request_finished.disconnect(close_old_connections)
|
2013-01-01 17:12:06 +08:00
|
|
|
close() # will fire request_finished
|
2013-02-18 18:37:26 +08:00
|
|
|
request_finished.connect(close_old_connections)
|
2012-12-30 22:19:22 +08:00
|
|
|
|
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
class ClientHandler(BaseHandler):
|
|
|
|
"""
|
2006-09-28 09:56:02 +08:00
|
|
|
A HTTP Handler that can be used for testing purposes.
|
2006-08-27 20:24:59 +08:00
|
|
|
Uses the WSGI interface to compose requests, but returns
|
|
|
|
the raw HttpResponse object
|
|
|
|
"""
|
2010-08-27 21:54:13 +08:00
|
|
|
def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
|
|
|
|
self.enforce_csrf_checks = enforce_csrf_checks
|
|
|
|
super(ClientHandler, self).__init__(*args, **kwargs)
|
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
def __call__(self, environ):
|
|
|
|
from django.conf import settings
|
|
|
|
|
|
|
|
# Set up middleware if needed. We couldn't do this earlier, because
|
|
|
|
# settings weren't available.
|
|
|
|
if self._request_middleware is None:
|
|
|
|
self.load_middleware()
|
|
|
|
|
2013-02-18 18:37:26 +08:00
|
|
|
request_started.disconnect(close_old_connections)
|
2013-01-01 17:12:06 +08:00
|
|
|
request_started.send(sender=self.__class__)
|
2013-02-18 18:37:26 +08:00
|
|
|
request_started.connect(close_old_connections)
|
2012-12-30 22:19:22 +08:00
|
|
|
request = WSGIRequest(environ)
|
|
|
|
# sneaky little hack so that we can easily get round
|
|
|
|
# CsrfViewMiddleware. This makes life easier, and is probably
|
|
|
|
# required for backwards compatibility with external tests against
|
|
|
|
# admin views.
|
|
|
|
request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
|
|
|
|
response = self.get_response(request)
|
|
|
|
# We're emulating a WSGI server; we must call the close method
|
|
|
|
# on completion.
|
|
|
|
if response.streaming:
|
|
|
|
response.streaming_content = closing_iterator_wrapper(
|
|
|
|
response.streaming_content, response.close)
|
|
|
|
else:
|
2013-02-18 18:37:26 +08:00
|
|
|
request_finished.disconnect(close_old_connections)
|
2013-01-01 17:12:06 +08:00
|
|
|
response.close() # will fire request_finished
|
2013-02-18 18:37:26 +08:00
|
|
|
request_finished.connect(close_old_connections)
|
2006-09-28 09:56:02 +08:00
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
return response
|
|
|
|
|
2008-08-06 23:32:46 +08:00
|
|
|
def store_rendered_templates(store, signal, sender, template, context, **kwargs):
|
2008-07-02 12:34:05 +08:00
|
|
|
"""
|
|
|
|
Stores templates and contexts that are rendered.
|
2011-02-21 18:12:23 +08:00
|
|
|
|
|
|
|
The context is copied so that it is an accurate representation at the time
|
|
|
|
of rendering.
|
2008-07-02 12:34:05 +08:00
|
|
|
"""
|
2010-10-10 10:16:33 +08:00
|
|
|
store.setdefault('templates', []).append(template)
|
2011-02-21 18:12:23 +08:00
|
|
|
store.setdefault('context', ContextList()).append(copy(context))
|
2006-08-27 20:24:59 +08:00
|
|
|
|
|
|
|
def encode_multipart(boundary, data):
|
|
|
|
"""
|
2008-07-02 12:34:05 +08:00
|
|
|
Encodes multipart POST data from a dictionary of form values.
|
2006-09-28 09:56:02 +08:00
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
The key will be used as the form data name; the value will be transmitted
|
|
|
|
as content. If the value is a file, the contents of the file will be sent
|
|
|
|
as an application/octet-stream; otherwise, str(value) will be sent.
|
|
|
|
"""
|
|
|
|
lines = []
|
2012-08-29 02:59:56 +08:00
|
|
|
to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
|
2008-07-08 06:06:32 +08:00
|
|
|
|
|
|
|
# Not by any means perfect, but good enough for our purposes.
|
|
|
|
is_file = lambda thing: hasattr(thing, "read") and callable(thing.read)
|
|
|
|
|
|
|
|
# Each bit of the multipart form data could be either a form value or a
|
|
|
|
# file, or a *list* of form values and/or files. Remember that HTTP field
|
|
|
|
# names can be duplicated!
|
2006-08-27 20:24:59 +08:00
|
|
|
for (key, value) in data.items():
|
2008-07-08 06:06:32 +08:00
|
|
|
if is_file(value):
|
|
|
|
lines.extend(encode_file(boundary, key, value))
|
2012-07-20 20:22:00 +08:00
|
|
|
elif not isinstance(value, six.string_types) and is_iterable(value):
|
2008-07-08 06:06:32 +08:00
|
|
|
for item in value:
|
|
|
|
if is_file(item):
|
|
|
|
lines.extend(encode_file(boundary, key, item))
|
|
|
|
else:
|
2012-08-13 05:25:42 +08:00
|
|
|
lines.extend([to_bytes(val) for val in [
|
|
|
|
'--%s' % boundary,
|
|
|
|
'Content-Disposition: form-data; name="%s"' % key,
|
2007-09-15 03:55:24 +08:00
|
|
|
'',
|
2012-08-13 05:25:42 +08:00
|
|
|
item
|
|
|
|
]])
|
2008-07-08 06:06:32 +08:00
|
|
|
else:
|
2012-08-13 05:25:42 +08:00
|
|
|
lines.extend([to_bytes(val) for val in [
|
|
|
|
'--%s' % boundary,
|
|
|
|
'Content-Disposition: form-data; name="%s"' % key,
|
2008-07-08 06:06:32 +08:00
|
|
|
'',
|
2012-08-13 05:25:42 +08:00
|
|
|
value
|
|
|
|
]])
|
2006-09-28 09:56:02 +08:00
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
lines.extend([
|
2012-08-13 05:25:42 +08:00
|
|
|
to_bytes('--%s--' % boundary),
|
|
|
|
b'',
|
2006-08-27 20:24:59 +08:00
|
|
|
])
|
2012-08-13 05:25:42 +08:00
|
|
|
return b'\r\n'.join(lines)
|
2006-08-27 20:24:59 +08:00
|
|
|
|
2008-07-08 06:06:32 +08:00
|
|
|
def encode_file(boundary, key, file):
|
2012-08-29 02:59:56 +08:00
|
|
|
to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
|
2010-08-07 01:14:02 +08:00
|
|
|
content_type = mimetypes.guess_type(file.name)[0]
|
|
|
|
if content_type is None:
|
|
|
|
content_type = 'application/octet-stream'
|
2008-07-08 06:06:32 +08:00
|
|
|
return [
|
2012-08-13 05:25:42 +08:00
|
|
|
to_bytes('--%s' % boundary),
|
|
|
|
to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"' \
|
|
|
|
% (key, os.path.basename(file.name))),
|
|
|
|
to_bytes('Content-Type: %s' % content_type),
|
|
|
|
b'',
|
2008-07-08 06:06:32 +08:00
|
|
|
file.read()
|
|
|
|
]
|
2008-09-17 19:32:11 +08:00
|
|
|
|
2010-10-13 07:37:47 +08:00
|
|
|
|
|
|
|
class RequestFactory(object):
|
|
|
|
"""
|
|
|
|
Class that lets you create mock Request objects for use in testing.
|
|
|
|
|
|
|
|
Usage:
|
|
|
|
|
|
|
|
rf = RequestFactory()
|
|
|
|
get_request = rf.get('/hello/')
|
|
|
|
post_request = rf.post('/submit/', {'foo': 'bar'})
|
|
|
|
|
|
|
|
Once you have a request object you can pass it to any view function,
|
|
|
|
just as if that view had been hooked up using a URLconf.
|
|
|
|
"""
|
|
|
|
def __init__(self, **defaults):
|
|
|
|
self.defaults = defaults
|
|
|
|
self.cookies = SimpleCookie()
|
2012-05-06 01:47:03 +08:00
|
|
|
self.errors = BytesIO()
|
2010-10-13 07:37:47 +08:00
|
|
|
|
|
|
|
def _base_environ(self, **request):
|
|
|
|
"""
|
|
|
|
The base environment for a request.
|
|
|
|
"""
|
2011-10-19 00:42:32 +08:00
|
|
|
# This is a minimal valid WSGI environ dictionary, plus:
|
|
|
|
# - HTTP_COOKIE: for cookie support,
|
|
|
|
# - REMOTE_ADDR: often useful, see #8551.
|
2011-10-07 04:39:15 +08:00
|
|
|
# See http://www.python.org/dev/peps/pep-3333/#environ-variables
|
2010-10-13 07:37:47 +08:00
|
|
|
environ = {
|
|
|
|
'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
|
2012-12-17 17:47:38 +08:00
|
|
|
'PATH_INFO': str('/'),
|
|
|
|
'REMOTE_ADDR': str('127.0.0.1'),
|
|
|
|
'REQUEST_METHOD': str('GET'),
|
|
|
|
'SCRIPT_NAME': str(''),
|
|
|
|
'SERVER_NAME': str('testserver'),
|
|
|
|
'SERVER_PORT': str('80'),
|
|
|
|
'SERVER_PROTOCOL': str('HTTP/1.1'),
|
2012-07-21 16:01:46 +08:00
|
|
|
'wsgi.version': (1, 0),
|
2012-12-17 17:47:38 +08:00
|
|
|
'wsgi.url_scheme': str('http'),
|
2012-07-21 16:01:46 +08:00
|
|
|
'wsgi.input': FakePayload(b''),
|
2010-10-13 07:37:47 +08:00
|
|
|
'wsgi.errors': self.errors,
|
|
|
|
'wsgi.multiprocess': True,
|
|
|
|
'wsgi.multithread': False,
|
|
|
|
'wsgi.run_once': False,
|
|
|
|
}
|
|
|
|
environ.update(self.defaults)
|
|
|
|
environ.update(request)
|
|
|
|
return environ
|
|
|
|
|
|
|
|
def request(self, **request):
|
|
|
|
"Construct a generic request object."
|
|
|
|
return WSGIRequest(self._base_environ(**request))
|
|
|
|
|
2011-08-23 08:52:45 +08:00
|
|
|
def _encode_data(self, data, content_type, ):
|
|
|
|
if content_type is MULTIPART_CONTENT:
|
|
|
|
return encode_multipart(BOUNDARY, data)
|
|
|
|
else:
|
|
|
|
# Encode the content so that the byte representation is correct.
|
|
|
|
match = CONTENT_TYPE_RE.match(content_type)
|
|
|
|
if match:
|
|
|
|
charset = match.group(1)
|
|
|
|
else:
|
|
|
|
charset = settings.DEFAULT_CHARSET
|
2012-08-29 02:59:56 +08:00
|
|
|
return force_bytes(data, encoding=charset)
|
2011-08-23 08:52:45 +08:00
|
|
|
|
2010-12-23 07:55:13 +08:00
|
|
|
def _get_path(self, parsed):
|
2012-12-17 17:47:38 +08:00
|
|
|
path = force_str(parsed[2])
|
2010-12-23 07:55:13 +08:00
|
|
|
# If there are parameters, add them
|
|
|
|
if parsed[3]:
|
2012-12-17 17:47:38 +08:00
|
|
|
path += str(";") + force_str(parsed[3])
|
2012-12-17 17:49:26 +08:00
|
|
|
path = unquote(path)
|
|
|
|
# WSGI requires latin-1 encoded strings. See get_path_info().
|
|
|
|
if six.PY3:
|
|
|
|
path = path.encode('utf-8').decode('iso-8859-1')
|
|
|
|
return path
|
2010-12-23 07:55:13 +08:00
|
|
|
|
2010-10-13 07:37:47 +08:00
|
|
|
def get(self, path, data={}, **extra):
|
2012-05-26 01:03:15 +08:00
|
|
|
"Construct a GET request."
|
2010-10-13 07:37:47 +08:00
|
|
|
|
|
|
|
parsed = urlparse(path)
|
|
|
|
r = {
|
2012-12-17 17:47:38 +08:00
|
|
|
'CONTENT_TYPE': str('text/html; charset=utf-8'),
|
2010-12-23 07:55:13 +08:00
|
|
|
'PATH_INFO': self._get_path(parsed),
|
2012-12-17 17:47:38 +08:00
|
|
|
'QUERY_STRING': urlencode(data, doseq=True) or force_str(parsed[4]),
|
|
|
|
'REQUEST_METHOD': str('GET'),
|
2010-10-13 07:37:47 +08:00
|
|
|
}
|
|
|
|
r.update(extra)
|
|
|
|
return self.request(**r)
|
|
|
|
|
|
|
|
def post(self, path, data={}, content_type=MULTIPART_CONTENT,
|
|
|
|
**extra):
|
|
|
|
"Construct a POST request."
|
|
|
|
|
2011-08-23 08:52:45 +08:00
|
|
|
post_data = self._encode_data(data, content_type)
|
2010-10-13 07:37:47 +08:00
|
|
|
|
|
|
|
parsed = urlparse(path)
|
|
|
|
r = {
|
|
|
|
'CONTENT_LENGTH': len(post_data),
|
|
|
|
'CONTENT_TYPE': content_type,
|
2010-12-23 07:55:13 +08:00
|
|
|
'PATH_INFO': self._get_path(parsed),
|
2012-12-17 17:47:38 +08:00
|
|
|
'QUERY_STRING': force_str(parsed[4]),
|
|
|
|
'REQUEST_METHOD': str('POST'),
|
2010-10-13 07:37:47 +08:00
|
|
|
'wsgi.input': FakePayload(post_data),
|
|
|
|
}
|
|
|
|
r.update(extra)
|
|
|
|
return self.request(**r)
|
|
|
|
|
|
|
|
def head(self, path, data={}, **extra):
|
|
|
|
"Construct a HEAD request."
|
|
|
|
|
|
|
|
parsed = urlparse(path)
|
|
|
|
r = {
|
2012-12-17 17:47:38 +08:00
|
|
|
'CONTENT_TYPE': str('text/html; charset=utf-8'),
|
2010-12-23 07:55:13 +08:00
|
|
|
'PATH_INFO': self._get_path(parsed),
|
2012-12-17 17:47:38 +08:00
|
|
|
'QUERY_STRING': urlencode(data, doseq=True) or force_str(parsed[4]),
|
|
|
|
'REQUEST_METHOD': str('HEAD'),
|
2010-10-13 07:37:47 +08:00
|
|
|
}
|
|
|
|
r.update(extra)
|
|
|
|
return self.request(**r)
|
|
|
|
|
2012-05-26 01:03:15 +08:00
|
|
|
def options(self, path, data='', content_type='application/octet-stream',
|
|
|
|
**extra):
|
|
|
|
"Construct an OPTIONS request."
|
|
|
|
return self.generic('OPTIONS', path, data, content_type, **extra)
|
2010-10-13 07:37:47 +08:00
|
|
|
|
2012-05-26 01:03:15 +08:00
|
|
|
def put(self, path, data='', content_type='application/octet-stream',
|
2010-10-13 07:37:47 +08:00
|
|
|
**extra):
|
|
|
|
"Construct a PUT request."
|
2012-05-26 01:03:15 +08:00
|
|
|
return self.generic('PUT', path, data, content_type, **extra)
|
2010-10-13 07:37:47 +08:00
|
|
|
|
2013-02-03 10:22:40 +08:00
|
|
|
def patch(self, path, data='', content_type='application/octet-stream',
|
|
|
|
**extra):
|
|
|
|
"Construct a PATCH request."
|
|
|
|
return self.generic('PATCH', path, data, content_type, **extra)
|
|
|
|
|
2012-05-26 01:03:15 +08:00
|
|
|
def delete(self, path, data='', content_type='application/octet-stream',
|
|
|
|
**extra):
|
|
|
|
"Construct a DELETE request."
|
|
|
|
return self.generic('DELETE', path, data, content_type, **extra)
|
2010-10-13 07:37:47 +08:00
|
|
|
|
2012-05-26 01:03:15 +08:00
|
|
|
def generic(self, method, path,
|
|
|
|
data='', content_type='application/octet-stream', **extra):
|
2010-10-13 07:37:47 +08:00
|
|
|
parsed = urlparse(path)
|
2012-08-29 02:59:56 +08:00
|
|
|
data = force_bytes(data, settings.DEFAULT_CHARSET)
|
2010-10-13 07:37:47 +08:00
|
|
|
r = {
|
2010-12-23 07:55:13 +08:00
|
|
|
'PATH_INFO': self._get_path(parsed),
|
2012-12-17 17:47:38 +08:00
|
|
|
'QUERY_STRING': force_str(parsed[4]),
|
|
|
|
'REQUEST_METHOD': str(method),
|
2010-10-13 07:37:47 +08:00
|
|
|
}
|
2012-05-26 01:03:15 +08:00
|
|
|
if data:
|
|
|
|
r.update({
|
|
|
|
'CONTENT_LENGTH': len(data),
|
2012-12-17 17:47:38 +08:00
|
|
|
'CONTENT_TYPE': str(content_type),
|
2012-05-26 01:03:15 +08:00
|
|
|
'wsgi.input': FakePayload(data),
|
|
|
|
})
|
2010-10-13 07:37:47 +08:00
|
|
|
r.update(extra)
|
|
|
|
return self.request(**r)
|
|
|
|
|
|
|
|
class Client(RequestFactory):
|
2006-08-27 20:24:59 +08:00
|
|
|
"""
|
2006-09-28 09:56:02 +08:00
|
|
|
A class that can act as a client for testing purposes.
|
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
It allows the user to compose GET and POST requests, and
|
|
|
|
obtain the response that the server gave to those requests.
|
|
|
|
The server Response objects are annotated with the details
|
|
|
|
of the contexts and templates that were rendered during the
|
|
|
|
process of serving the request.
|
|
|
|
|
|
|
|
Client objects are stateful - they will retain cookie (and
|
|
|
|
thus session) details for the lifetime of the Client instance.
|
2006-09-28 09:56:02 +08:00
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
This is not intended as a replacement for Twill/Selenium or
|
|
|
|
the like - it is here to allow testing against the
|
|
|
|
contexts and templates produced by a view, rather than the
|
|
|
|
HTML rendered to the end-user.
|
|
|
|
"""
|
2010-08-27 21:54:13 +08:00
|
|
|
def __init__(self, enforce_csrf_checks=False, **defaults):
|
2010-10-13 07:37:47 +08:00
|
|
|
super(Client, self).__init__(**defaults)
|
2010-08-27 21:54:13 +08:00
|
|
|
self.handler = ClientHandler(enforce_csrf_checks)
|
2007-02-11 08:23:31 +08:00
|
|
|
self.exc_info = None
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2008-08-06 23:32:46 +08:00
|
|
|
def store_exc_info(self, **kwargs):
|
2007-02-11 08:23:31 +08:00
|
|
|
"""
|
2008-07-02 12:34:05 +08:00
|
|
|
Stores exceptions when they are generated by a view.
|
2007-02-11 08:23:31 +08:00
|
|
|
"""
|
|
|
|
self.exc_info = sys.exc_info()
|
2006-09-28 09:56:02 +08:00
|
|
|
|
2007-05-05 23:16:15 +08:00
|
|
|
def _session(self):
|
2008-07-02 12:34:05 +08:00
|
|
|
"""
|
|
|
|
Obtains the current session variables.
|
|
|
|
"""
|
2012-03-15 10:46:07 +08:00
|
|
|
if 'django.contrib.sessions' in settings.INSTALLED_APPS:
|
2009-03-19 00:55:59 +08:00
|
|
|
engine = import_module(settings.SESSION_ENGINE)
|
2007-05-05 23:16:15 +08:00
|
|
|
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
|
|
|
|
if cookie:
|
2007-09-16 05:44:05 +08:00
|
|
|
return engine.SessionStore(cookie.value)
|
2007-05-05 23:16:15 +08:00
|
|
|
return {}
|
|
|
|
session = property(_session)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2010-10-13 07:37:47 +08:00
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
def request(self, **request):
|
|
|
|
"""
|
2006-09-28 09:56:02 +08:00
|
|
|
The master request method. Composes the environment dictionary
|
2006-08-27 20:24:59 +08:00
|
|
|
and passes to the handler, returning the result of the handler.
|
|
|
|
Assumes defaults for the query environment, which can be overridden
|
|
|
|
using the arguments to the request.
|
|
|
|
"""
|
2010-10-13 07:37:47 +08:00
|
|
|
environ = self._base_environ(**request)
|
2006-08-27 20:24:59 +08:00
|
|
|
|
2008-07-02 12:34:05 +08:00
|
|
|
# Curry a data dictionary into an instance of the template renderer
|
|
|
|
# callback function.
|
2006-08-27 20:24:59 +08:00
|
|
|
data = {}
|
|
|
|
on_template_render = curry(store_rendered_templates, data)
|
2010-04-13 10:41:37 +08:00
|
|
|
signals.template_rendered.connect(on_template_render, dispatch_uid="template-render")
|
2008-07-02 12:34:05 +08:00
|
|
|
# Capture exceptions created by the handler.
|
2010-04-13 10:41:37 +08:00
|
|
|
got_request_exception.connect(self.store_exc_info, dispatch_uid="request-exception")
|
2007-08-28 21:03:22 +08:00
|
|
|
try:
|
2010-04-13 10:41:37 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
response = self.handler(environ)
|
2012-04-29 00:09:37 +08:00
|
|
|
except TemplateDoesNotExist as e:
|
2010-04-13 10:41:37 +08:00
|
|
|
# If the view raises an exception, Django will attempt to show
|
|
|
|
# the 500.html template. If that template is not available,
|
|
|
|
# we should ignore the error in favor of re-raising the
|
|
|
|
# underlying exception that caused the 500 error. Any other
|
|
|
|
# template found to be missing during view error handling
|
|
|
|
# should be reported as-is.
|
|
|
|
if e.args != ('500.html',):
|
|
|
|
raise
|
|
|
|
|
|
|
|
# Look for a signalled exception, clear the current context
|
|
|
|
# exception data, then re-raise the signalled exception.
|
|
|
|
# Also make sure that the signalled exception is cleared from
|
|
|
|
# the local cache!
|
|
|
|
if self.exc_info:
|
|
|
|
exc_info = self.exc_info
|
|
|
|
self.exc_info = None
|
2012-08-12 05:43:45 +08:00
|
|
|
six.reraise(*exc_info)
|
2010-04-13 10:41:37 +08:00
|
|
|
|
|
|
|
# Save the client and request that stimulated the response.
|
|
|
|
response.client = self
|
|
|
|
response.request = request
|
|
|
|
|
|
|
|
# Add any rendered template detail to the response.
|
2010-10-10 10:16:33 +08:00
|
|
|
response.templates = data.get("templates", [])
|
|
|
|
response.context = data.get("context")
|
|
|
|
|
|
|
|
# Flatten a single context. Not really necessary anymore thanks to
|
|
|
|
# the __getattr__ flattening in ContextList, but has some edge-case
|
|
|
|
# backwards-compatibility implications.
|
|
|
|
if response.context and len(response.context) == 1:
|
|
|
|
response.context = response.context[0]
|
|
|
|
|
2010-04-13 10:41:37 +08:00
|
|
|
# Update persistent cookie data.
|
|
|
|
if response.cookies:
|
|
|
|
self.cookies.update(response.cookies)
|
|
|
|
|
|
|
|
return response
|
|
|
|
finally:
|
|
|
|
signals.template_rendered.disconnect(dispatch_uid="template-render")
|
|
|
|
got_request_exception.disconnect(dispatch_uid="request-exception")
|
2007-02-09 21:47:36 +08:00
|
|
|
|
2009-02-27 21:14:59 +08:00
|
|
|
def get(self, path, data={}, follow=False, **extra):
|
2008-07-02 12:34:05 +08:00
|
|
|
"""
|
|
|
|
Requests a response from the server using GET.
|
|
|
|
"""
|
2010-10-13 07:37:47 +08:00
|
|
|
response = super(Client, self).get(path, data=data, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
if follow:
|
2010-08-21 11:01:46 +08:00
|
|
|
response = self._handle_redirects(response, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
return response
|
2006-09-28 09:56:02 +08:00
|
|
|
|
2009-02-27 21:14:59 +08:00
|
|
|
def post(self, path, data={}, content_type=MULTIPART_CONTENT,
|
|
|
|
follow=False, **extra):
|
2008-07-02 12:34:05 +08:00
|
|
|
"""
|
|
|
|
Requests a response from the server using POST.
|
|
|
|
"""
|
2010-10-13 07:37:47 +08:00
|
|
|
response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
if follow:
|
2010-08-21 11:01:46 +08:00
|
|
|
response = self._handle_redirects(response, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
return response
|
2006-08-27 20:24:59 +08:00
|
|
|
|
2009-02-27 21:14:59 +08:00
|
|
|
def head(self, path, data={}, follow=False, **extra):
|
2008-10-07 17:23:40 +08:00
|
|
|
"""
|
|
|
|
Request a response from the server using HEAD.
|
|
|
|
"""
|
2010-10-13 07:37:47 +08:00
|
|
|
response = super(Client, self).head(path, data=data, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
if follow:
|
2010-08-21 11:01:46 +08:00
|
|
|
response = self._handle_redirects(response, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
return response
|
2008-10-07 17:23:40 +08:00
|
|
|
|
2012-05-26 01:03:15 +08:00
|
|
|
def options(self, path, data='', content_type='application/octet-stream',
|
|
|
|
follow=False, **extra):
|
2008-10-07 17:23:40 +08:00
|
|
|
"""
|
|
|
|
Request a response from the server using OPTIONS.
|
|
|
|
"""
|
2012-05-26 01:03:15 +08:00
|
|
|
response = super(Client, self).options(path,
|
|
|
|
data=data, content_type=content_type, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
if follow:
|
2010-08-21 11:01:46 +08:00
|
|
|
response = self._handle_redirects(response, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
return response
|
2008-10-07 17:23:40 +08:00
|
|
|
|
2012-05-26 01:03:15 +08:00
|
|
|
def put(self, path, data='', content_type='application/octet-stream',
|
2009-02-27 21:14:59 +08:00
|
|
|
follow=False, **extra):
|
2008-10-07 17:23:40 +08:00
|
|
|
"""
|
|
|
|
Send a resource to the server using PUT.
|
|
|
|
"""
|
2012-05-26 01:03:15 +08:00
|
|
|
response = super(Client, self).put(path,
|
|
|
|
data=data, content_type=content_type, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
if follow:
|
2010-08-21 11:01:46 +08:00
|
|
|
response = self._handle_redirects(response, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
return response
|
2008-10-07 17:23:40 +08:00
|
|
|
|
2013-02-03 10:22:40 +08:00
|
|
|
def patch(self, path, data='', content_type='application/octet-stream',
|
|
|
|
follow=False, **extra):
|
|
|
|
"""
|
|
|
|
Send a resource to the server using PATCH.
|
|
|
|
"""
|
|
|
|
response = super(Client, self).patch(
|
|
|
|
path, data=data, content_type=content_type, **extra)
|
|
|
|
if follow:
|
|
|
|
response = self._handle_redirects(response, **extra)
|
|
|
|
return response
|
|
|
|
|
2012-05-26 01:03:15 +08:00
|
|
|
def delete(self, path, data='', content_type='application/octet-stream',
|
|
|
|
follow=False, **extra):
|
2008-10-07 17:23:40 +08:00
|
|
|
"""
|
|
|
|
Send a DELETE request to the server.
|
|
|
|
"""
|
2012-05-26 01:03:15 +08:00
|
|
|
response = super(Client, self).delete(path,
|
|
|
|
data=data, content_type=content_type, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
if follow:
|
2010-08-21 11:01:46 +08:00
|
|
|
response = self._handle_redirects(response, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
return response
|
2008-10-07 17:23:40 +08:00
|
|
|
|
2007-05-05 23:16:15 +08:00
|
|
|
def login(self, **credentials):
|
2008-07-02 12:34:05 +08:00
|
|
|
"""
|
2010-10-13 07:37:47 +08:00
|
|
|
Sets the Factory to appear as if it has successfully logged into a site.
|
2006-09-28 09:56:02 +08:00
|
|
|
|
2007-05-05 23:16:15 +08:00
|
|
|
Returns True if login is possible; False if the provided credentials
|
2007-07-15 01:04:30 +08:00
|
|
|
are incorrect, or the user is inactive, or if the sessions framework is
|
2007-07-12 23:26:37 +08:00
|
|
|
not available.
|
2006-08-27 20:24:59 +08:00
|
|
|
"""
|
2007-05-05 23:16:15 +08:00
|
|
|
user = authenticate(**credentials)
|
2008-07-02 12:34:05 +08:00
|
|
|
if user and user.is_active \
|
2012-03-15 10:46:07 +08:00
|
|
|
and 'django.contrib.sessions' in settings.INSTALLED_APPS:
|
2009-03-19 00:55:59 +08:00
|
|
|
engine = import_module(settings.SESSION_ENGINE)
|
2007-05-05 23:16:15 +08:00
|
|
|
|
2008-07-02 12:34:05 +08:00
|
|
|
# Create a fake request to store login details.
|
2007-05-05 23:16:15 +08:00
|
|
|
request = HttpRequest()
|
2008-08-15 20:08:29 +08:00
|
|
|
if self.session:
|
|
|
|
request.session = self.session
|
|
|
|
else:
|
|
|
|
request.session = engine.SessionStore()
|
2007-05-05 23:16:15 +08:00
|
|
|
login(request, user)
|
|
|
|
|
2010-03-19 13:42:13 +08:00
|
|
|
# Save the session values.
|
|
|
|
request.session.save()
|
|
|
|
|
2008-07-02 12:34:05 +08:00
|
|
|
# Set the cookie to represent the session.
|
2008-07-02 12:48:58 +08:00
|
|
|
session_cookie = settings.SESSION_COOKIE_NAME
|
|
|
|
self.cookies[session_cookie] = request.session.session_key
|
|
|
|
cookie_data = {
|
|
|
|
'max-age': None,
|
|
|
|
'path': '/',
|
|
|
|
'domain': settings.SESSION_COOKIE_DOMAIN,
|
|
|
|
'secure': settings.SESSION_COOKIE_SECURE or None,
|
|
|
|
'expires': None,
|
|
|
|
}
|
|
|
|
self.cookies[session_cookie].update(cookie_data)
|
2007-05-05 23:16:15 +08:00
|
|
|
|
|
|
|
return True
|
|
|
|
else:
|
2006-09-02 17:26:24 +08:00
|
|
|
return False
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2007-08-17 22:20:25 +08:00
|
|
|
def logout(self):
|
2008-07-02 12:34:05 +08:00
|
|
|
"""
|
2009-03-31 06:52:48 +08:00
|
|
|
Removes the authenticated user's cookies and session object.
|
2007-08-17 22:20:25 +08:00
|
|
|
|
|
|
|
Causes the authenticated user to be logged out.
|
|
|
|
"""
|
2009-03-19 00:55:59 +08:00
|
|
|
session = import_module(settings.SESSION_ENGINE).SessionStore()
|
2009-03-31 06:52:48 +08:00
|
|
|
session_cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
|
|
|
|
if session_cookie:
|
|
|
|
session.delete(session_key=session_cookie.value)
|
2007-08-17 22:20:25 +08:00
|
|
|
self.cookies = SimpleCookie()
|
2009-02-27 21:14:59 +08:00
|
|
|
|
2010-08-21 11:01:46 +08:00
|
|
|
def _handle_redirects(self, response, **extra):
|
2009-02-27 21:14:59 +08:00
|
|
|
"Follows any redirects by requesting responses from the server using GET."
|
|
|
|
|
|
|
|
response.redirect_chain = []
|
|
|
|
while response.status_code in (301, 302, 303, 307):
|
2013-02-13 16:55:43 +08:00
|
|
|
url = response.url
|
2009-02-27 21:14:59 +08:00
|
|
|
redirect_chain = response.redirect_chain
|
|
|
|
redirect_chain.append((url, response.status_code))
|
|
|
|
|
2011-11-28 04:04:13 +08:00
|
|
|
url = urlsplit(url)
|
|
|
|
if url.scheme:
|
|
|
|
extra['wsgi.url_scheme'] = url.scheme
|
|
|
|
if url.hostname:
|
|
|
|
extra['SERVER_NAME'] = url.hostname
|
|
|
|
if url.port:
|
|
|
|
extra['SERVER_PORT'] = str(url.port)
|
2010-02-13 20:01:14 +08:00
|
|
|
|
2011-11-28 04:04:13 +08:00
|
|
|
response = self.get(url.path, QueryDict(url.query), follow=False, **extra)
|
2009-02-27 21:14:59 +08:00
|
|
|
response.redirect_chain = redirect_chain
|
|
|
|
|
|
|
|
# Prevent loops
|
|
|
|
if response.redirect_chain[-1] in response.redirect_chain[0:-1]:
|
|
|
|
break
|
|
|
|
return response
|