PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/django/test/client.py

https://github.com/andnils/django
Python | 629 lines | 556 code | 18 blank | 55 comment | 14 complexity | 3e8e1adc71c5580cb8540ee6999af293 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from __future__ import unicode_literals
  2. import sys
  3. import os
  4. import re
  5. import mimetypes
  6. from copy import copy
  7. from importlib import import_module
  8. from io import BytesIO
  9. from django.apps import apps
  10. from django.conf import settings
  11. from django.core.handlers.base import BaseHandler
  12. from django.core.handlers.wsgi import WSGIRequest
  13. from django.core.signals import (request_started, request_finished,
  14. got_request_exception)
  15. from django.db import close_old_connections
  16. from django.http import SimpleCookie, QueryDict
  17. from django.template import TemplateDoesNotExist
  18. from django.test import signals
  19. from django.utils.functional import curry
  20. from django.utils.encoding import force_bytes, force_str
  21. from django.utils.http import urlencode
  22. from django.utils.itercompat import is_iterable
  23. from django.utils import six
  24. from django.utils.six.moves.urllib.parse import unquote, urlparse, urlsplit
  25. from django.test.utils import ContextList
  26. __all__ = ('Client', 'RequestFactory', 'encode_file', 'encode_multipart')
  27. BOUNDARY = 'BoUnDaRyStRiNg'
  28. MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
  29. CONTENT_TYPE_RE = re.compile('.*; charset=([\w\d-]+);?')
  30. class FakePayload(object):
  31. """
  32. A wrapper around BytesIO that restricts what can be read since data from
  33. the network can't be seeked and cannot be read outside of its content
  34. length. This makes sure that views can't do anything under the test client
  35. that wouldn't work in Real Life.
  36. """
  37. def __init__(self, content=None):
  38. self.__content = BytesIO()
  39. self.__len = 0
  40. self.read_started = False
  41. if content is not None:
  42. self.write(content)
  43. def __len__(self):
  44. return self.__len
  45. def read(self, num_bytes=None):
  46. if not self.read_started:
  47. self.__content.seek(0)
  48. self.read_started = True
  49. if num_bytes is None:
  50. num_bytes = self.__len or 0
  51. assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data."
  52. content = self.__content.read(num_bytes)
  53. self.__len -= num_bytes
  54. return content
  55. def write(self, content):
  56. if self.read_started:
  57. raise ValueError("Unable to write a payload after he's been read")
  58. content = force_bytes(content)
  59. self.__content.write(content)
  60. self.__len += len(content)
  61. def closing_iterator_wrapper(iterable, close):
  62. try:
  63. for item in iterable:
  64. yield item
  65. finally:
  66. request_finished.disconnect(close_old_connections)
  67. close() # will fire request_finished
  68. request_finished.connect(close_old_connections)
  69. class ClientHandler(BaseHandler):
  70. """
  71. A HTTP Handler that can be used for testing purposes. Uses the WSGI
  72. interface to compose requests, but returns the raw HttpResponse object with
  73. the originating WSGIRequest attached to its ``wsgi_request`` attribute.
  74. """
  75. def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
  76. self.enforce_csrf_checks = enforce_csrf_checks
  77. super(ClientHandler, self).__init__(*args, **kwargs)
  78. def __call__(self, environ):
  79. # Set up middleware if needed. We couldn't do this earlier, because
  80. # settings weren't available.
  81. if self._request_middleware is None:
  82. self.load_middleware()
  83. request_started.disconnect(close_old_connections)
  84. request_started.send(sender=self.__class__)
  85. request_started.connect(close_old_connections)
  86. request = WSGIRequest(environ)
  87. # sneaky little hack so that we can easily get round
  88. # CsrfViewMiddleware. This makes life easier, and is probably
  89. # required for backwards compatibility with external tests against
  90. # admin views.
  91. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
  92. # Request goes through middleware.
  93. response = self.get_response(request)
  94. # Attach the originating request to the response so that it could be
  95. # later retrieved.
  96. response.wsgi_request = request
  97. # We're emulating a WSGI server; we must call the close method
  98. # on completion.
  99. if response.streaming:
  100. response.streaming_content = closing_iterator_wrapper(
  101. response.streaming_content, response.close)
  102. else:
  103. request_finished.disconnect(close_old_connections)
  104. response.close() # will fire request_finished
  105. request_finished.connect(close_old_connections)
  106. return response
  107. def store_rendered_templates(store, signal, sender, template, context, **kwargs):
  108. """
  109. Stores templates and contexts that are rendered.
  110. The context is copied so that it is an accurate representation at the time
  111. of rendering.
  112. """
  113. store.setdefault('templates', []).append(template)
  114. store.setdefault('context', ContextList()).append(copy(context))
  115. def encode_multipart(boundary, data):
  116. """
  117. Encodes multipart POST data from a dictionary of form values.
  118. The key will be used as the form data name; the value will be transmitted
  119. as content. If the value is a file, the contents of the file will be sent
  120. as an application/octet-stream; otherwise, str(value) will be sent.
  121. """
  122. lines = []
  123. to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
  124. # Not by any means perfect, but good enough for our purposes.
  125. is_file = lambda thing: hasattr(thing, "read") and callable(thing.read)
  126. # Each bit of the multipart form data could be either a form value or a
  127. # file, or a *list* of form values and/or files. Remember that HTTP field
  128. # names can be duplicated!
  129. for (key, value) in data.items():
  130. if is_file(value):
  131. lines.extend(encode_file(boundary, key, value))
  132. elif not isinstance(value, six.string_types) and is_iterable(value):
  133. for item in value:
  134. if is_file(item):
  135. lines.extend(encode_file(boundary, key, item))
  136. else:
  137. lines.extend([to_bytes(val) for val in [
  138. '--%s' % boundary,
  139. 'Content-Disposition: form-data; name="%s"' % key,
  140. '',
  141. item
  142. ]])
  143. else:
  144. lines.extend([to_bytes(val) for val in [
  145. '--%s' % boundary,
  146. 'Content-Disposition: form-data; name="%s"' % key,
  147. '',
  148. value
  149. ]])
  150. lines.extend([
  151. to_bytes('--%s--' % boundary),
  152. b'',
  153. ])
  154. return b'\r\n'.join(lines)
  155. def encode_file(boundary, key, file):
  156. to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
  157. if hasattr(file, 'content_type'):
  158. content_type = file.content_type
  159. else:
  160. content_type = mimetypes.guess_type(file.name)[0]
  161. if content_type is None:
  162. content_type = 'application/octet-stream'
  163. return [
  164. to_bytes('--%s' % boundary),
  165. to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"'
  166. % (key, os.path.basename(file.name))),
  167. to_bytes('Content-Type: %s' % content_type),
  168. b'',
  169. file.read()
  170. ]
  171. class RequestFactory(object):
  172. """
  173. Class that lets you create mock Request objects for use in testing.
  174. Usage:
  175. rf = RequestFactory()
  176. get_request = rf.get('/hello/')
  177. post_request = rf.post('/submit/', {'foo': 'bar'})
  178. Once you have a request object you can pass it to any view function,
  179. just as if that view had been hooked up using a URLconf.
  180. """
  181. def __init__(self, **defaults):
  182. self.defaults = defaults
  183. self.cookies = SimpleCookie()
  184. self.errors = BytesIO()
  185. def _base_environ(self, **request):
  186. """
  187. The base environment for a request.
  188. """
  189. # This is a minimal valid WSGI environ dictionary, plus:
  190. # - HTTP_COOKIE: for cookie support,
  191. # - REMOTE_ADDR: often useful, see #8551.
  192. # See http://www.python.org/dev/peps/pep-3333/#environ-variables
  193. environ = {
  194. 'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
  195. 'PATH_INFO': str('/'),
  196. 'REMOTE_ADDR': str('127.0.0.1'),
  197. 'REQUEST_METHOD': str('GET'),
  198. 'SCRIPT_NAME': str(''),
  199. 'SERVER_NAME': str('testserver'),
  200. 'SERVER_PORT': str('80'),
  201. 'SERVER_PROTOCOL': str('HTTP/1.1'),
  202. 'wsgi.version': (1, 0),
  203. 'wsgi.url_scheme': str('http'),
  204. 'wsgi.input': FakePayload(b''),
  205. 'wsgi.errors': self.errors,
  206. 'wsgi.multiprocess': True,
  207. 'wsgi.multithread': False,
  208. 'wsgi.run_once': False,
  209. }
  210. environ.update(self.defaults)
  211. environ.update(request)
  212. return environ
  213. def request(self, **request):
  214. "Construct a generic request object."
  215. return WSGIRequest(self._base_environ(**request))
  216. def _encode_data(self, data, content_type):
  217. if content_type is MULTIPART_CONTENT:
  218. return encode_multipart(BOUNDARY, data)
  219. else:
  220. # Encode the content so that the byte representation is correct.
  221. match = CONTENT_TYPE_RE.match(content_type)
  222. if match:
  223. charset = match.group(1)
  224. else:
  225. charset = settings.DEFAULT_CHARSET
  226. return force_bytes(data, encoding=charset)
  227. def _get_path(self, parsed):
  228. path = force_str(parsed[2])
  229. # If there are parameters, add them
  230. if parsed[3]:
  231. path += str(";") + force_str(parsed[3])
  232. path = unquote(path)
  233. # WSGI requires latin-1 encoded strings. See get_path_info().
  234. if six.PY3:
  235. path = path.encode('utf-8').decode('iso-8859-1')
  236. return path
  237. def get(self, path, data=None, secure=False, **extra):
  238. "Construct a GET request."
  239. r = {
  240. 'QUERY_STRING': urlencode(data or {}, doseq=True),
  241. }
  242. r.update(extra)
  243. return self.generic('GET', path, secure=secure, **r)
  244. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  245. secure=False, **extra):
  246. "Construct a POST request."
  247. post_data = self._encode_data(data or {}, content_type)
  248. return self.generic('POST', path, post_data, content_type,
  249. secure=secure, **extra)
  250. def head(self, path, data=None, secure=False, **extra):
  251. "Construct a HEAD request."
  252. r = {
  253. 'QUERY_STRING': urlencode(data or {}, doseq=True),
  254. }
  255. r.update(extra)
  256. return self.generic('HEAD', path, secure=secure, **r)
  257. def options(self, path, data='', content_type='application/octet-stream',
  258. secure=False, **extra):
  259. "Construct an OPTIONS request."
  260. return self.generic('OPTIONS', path, data, content_type,
  261. secure=secure, **extra)
  262. def put(self, path, data='', content_type='application/octet-stream',
  263. secure=False, **extra):
  264. "Construct a PUT request."
  265. return self.generic('PUT', path, data, content_type,
  266. secure=secure, **extra)
  267. def patch(self, path, data='', content_type='application/octet-stream',
  268. secure=False, **extra):
  269. "Construct a PATCH request."
  270. return self.generic('PATCH', path, data, content_type,
  271. secure=secure, **extra)
  272. def delete(self, path, data='', content_type='application/octet-stream',
  273. secure=False, **extra):
  274. "Construct a DELETE request."
  275. return self.generic('DELETE', path, data, content_type,
  276. secure=secure, **extra)
  277. def generic(self, method, path, data='',
  278. content_type='application/octet-stream', secure=False,
  279. **extra):
  280. """Constructs an arbitrary HTTP request."""
  281. parsed = urlparse(path)
  282. data = force_bytes(data, settings.DEFAULT_CHARSET)
  283. r = {
  284. 'PATH_INFO': self._get_path(parsed),
  285. 'REQUEST_METHOD': str(method),
  286. 'SERVER_PORT': str('443') if secure else str('80'),
  287. 'wsgi.url_scheme': str('https') if secure else str('http'),
  288. }
  289. if data:
  290. r.update({
  291. 'CONTENT_LENGTH': len(data),
  292. 'CONTENT_TYPE': str(content_type),
  293. 'wsgi.input': FakePayload(data),
  294. })
  295. r.update(extra)
  296. # If QUERY_STRING is absent or empty, we want to extract it from the URL.
  297. if not r.get('QUERY_STRING'):
  298. query_string = force_bytes(parsed[4])
  299. # WSGI requires latin-1 encoded strings. See get_path_info().
  300. if six.PY3:
  301. query_string = query_string.decode('iso-8859-1')
  302. r['QUERY_STRING'] = query_string
  303. return self.request(**r)
  304. class Client(RequestFactory):
  305. """
  306. A class that can act as a client for testing purposes.
  307. It allows the user to compose GET and POST requests, and
  308. obtain the response that the server gave to those requests.
  309. The server Response objects are annotated with the details
  310. of the contexts and templates that were rendered during the
  311. process of serving the request.
  312. Client objects are stateful - they will retain cookie (and
  313. thus session) details for the lifetime of the Client instance.
  314. This is not intended as a replacement for Twill/Selenium or
  315. the like - it is here to allow testing against the
  316. contexts and templates produced by a view, rather than the
  317. HTML rendered to the end-user.
  318. """
  319. def __init__(self, enforce_csrf_checks=False, **defaults):
  320. super(Client, self).__init__(**defaults)
  321. self.handler = ClientHandler(enforce_csrf_checks)
  322. self.exc_info = None
  323. def store_exc_info(self, **kwargs):
  324. """
  325. Stores exceptions when they are generated by a view.
  326. """
  327. self.exc_info = sys.exc_info()
  328. def _session(self):
  329. """
  330. Obtains the current session variables.
  331. """
  332. if apps.is_installed('django.contrib.sessions'):
  333. engine = import_module(settings.SESSION_ENGINE)
  334. cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
  335. if cookie:
  336. return engine.SessionStore(cookie.value)
  337. return {}
  338. session = property(_session)
  339. def request(self, **request):
  340. """
  341. The master request method. Composes the environment dictionary
  342. and passes to the handler, returning the result of the handler.
  343. Assumes defaults for the query environment, which can be overridden
  344. using the arguments to the request.
  345. """
  346. environ = self._base_environ(**request)
  347. # Curry a data dictionary into an instance of the template renderer
  348. # callback function.
  349. data = {}
  350. on_template_render = curry(store_rendered_templates, data)
  351. signal_uid = "template-render-%s" % id(request)
  352. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  353. # Capture exceptions created by the handler.
  354. got_request_exception.connect(self.store_exc_info, dispatch_uid="request-exception")
  355. try:
  356. try:
  357. response = self.handler(environ)
  358. except TemplateDoesNotExist as e:
  359. # If the view raises an exception, Django will attempt to show
  360. # the 500.html template. If that template is not available,
  361. # we should ignore the error in favor of re-raising the
  362. # underlying exception that caused the 500 error. Any other
  363. # template found to be missing during view error handling
  364. # should be reported as-is.
  365. if e.args != ('500.html',):
  366. raise
  367. # Look for a signalled exception, clear the current context
  368. # exception data, then re-raise the signalled exception.
  369. # Also make sure that the signalled exception is cleared from
  370. # the local cache!
  371. if self.exc_info:
  372. exc_info = self.exc_info
  373. self.exc_info = None
  374. six.reraise(*exc_info)
  375. # Save the client and request that stimulated the response.
  376. response.client = self
  377. response.request = request
  378. # Add any rendered template detail to the response.
  379. response.templates = data.get("templates", [])
  380. response.context = data.get("context")
  381. # Flatten a single context. Not really necessary anymore thanks to
  382. # the __getattr__ flattening in ContextList, but has some edge-case
  383. # backwards-compatibility implications.
  384. if response.context and len(response.context) == 1:
  385. response.context = response.context[0]
  386. # Update persistent cookie data.
  387. if response.cookies:
  388. self.cookies.update(response.cookies)
  389. return response
  390. finally:
  391. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  392. got_request_exception.disconnect(dispatch_uid="request-exception")
  393. def get(self, path, data=None, follow=False, secure=False, **extra):
  394. """
  395. Requests a response from the server using GET.
  396. """
  397. response = super(Client, self).get(path, data=data, secure=secure,
  398. **extra)
  399. if follow:
  400. response = self._handle_redirects(response, **extra)
  401. return response
  402. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  403. follow=False, secure=False, **extra):
  404. """
  405. Requests a response from the server using POST.
  406. """
  407. response = super(Client, self).post(path, data=data,
  408. content_type=content_type,
  409. secure=secure, **extra)
  410. if follow:
  411. response = self._handle_redirects(response, **extra)
  412. return response
  413. def head(self, path, data=None, follow=False, secure=False, **extra):
  414. """
  415. Request a response from the server using HEAD.
  416. """
  417. response = super(Client, self).head(path, data=data, secure=secure,
  418. **extra)
  419. if follow:
  420. response = self._handle_redirects(response, **extra)
  421. return response
  422. def options(self, path, data='', content_type='application/octet-stream',
  423. follow=False, secure=False, **extra):
  424. """
  425. Request a response from the server using OPTIONS.
  426. """
  427. response = super(Client, self).options(path, data=data,
  428. content_type=content_type,
  429. secure=secure, **extra)
  430. if follow:
  431. response = self._handle_redirects(response, **extra)
  432. return response
  433. def put(self, path, data='', content_type='application/octet-stream',
  434. follow=False, secure=False, **extra):
  435. """
  436. Send a resource to the server using PUT.
  437. """
  438. response = super(Client, self).put(path, data=data,
  439. content_type=content_type,
  440. secure=secure, **extra)
  441. if follow:
  442. response = self._handle_redirects(response, **extra)
  443. return response
  444. def patch(self, path, data='', content_type='application/octet-stream',
  445. follow=False, secure=False, **extra):
  446. """
  447. Send a resource to the server using PATCH.
  448. """
  449. response = super(Client, self).patch(path, data=data,
  450. content_type=content_type,
  451. secure=secure, **extra)
  452. if follow:
  453. response = self._handle_redirects(response, **extra)
  454. return response
  455. def delete(self, path, data='', content_type='application/octet-stream',
  456. follow=False, secure=False, **extra):
  457. """
  458. Send a DELETE request to the server.
  459. """
  460. response = super(Client, self).delete(path, data=data,
  461. content_type=content_type,
  462. secure=secure, **extra)
  463. if follow:
  464. response = self._handle_redirects(response, **extra)
  465. return response
  466. def login(self, **credentials):
  467. """
  468. Sets the Factory to appear as if it has successfully logged into a site.
  469. Returns True if login is possible; False if the provided credentials
  470. are incorrect, or the user is inactive, or if the sessions framework is
  471. not available.
  472. """
  473. from django.contrib.auth import authenticate, login
  474. user = authenticate(**credentials)
  475. if (user and user.is_active and
  476. apps.is_installed('django.contrib.sessions')):
  477. engine = import_module(settings.SESSION_ENGINE)
  478. # Create a fake request that goes through request middleware
  479. request = self.request().wsgi_request
  480. if self.session:
  481. request.session = self.session
  482. else:
  483. request.session = engine.SessionStore()
  484. login(request, user)
  485. # Save the session values.
  486. request.session.save()
  487. # Set the cookie to represent the session.
  488. session_cookie = settings.SESSION_COOKIE_NAME
  489. self.cookies[session_cookie] = request.session.session_key
  490. cookie_data = {
  491. 'max-age': None,
  492. 'path': '/',
  493. 'domain': settings.SESSION_COOKIE_DOMAIN,
  494. 'secure': settings.SESSION_COOKIE_SECURE or None,
  495. 'expires': None,
  496. }
  497. self.cookies[session_cookie].update(cookie_data)
  498. return True
  499. else:
  500. return False
  501. def logout(self):
  502. """
  503. Removes the authenticated user's cookies and session object.
  504. Causes the authenticated user to be logged out.
  505. """
  506. from django.contrib.auth import get_user_model, logout
  507. # Create a fake request that goes through request middleware
  508. request = self.request().wsgi_request
  509. engine = import_module(settings.SESSION_ENGINE)
  510. UserModel = get_user_model()
  511. if self.session:
  512. request.session = self.session
  513. uid = self.session.get("_auth_user_id")
  514. if uid:
  515. request.user = UserModel._default_manager.get(pk=uid)
  516. else:
  517. request.session = engine.SessionStore()
  518. logout(request)
  519. self.cookies = SimpleCookie()
  520. def _handle_redirects(self, response, **extra):
  521. "Follows any redirects by requesting responses from the server using GET."
  522. response.redirect_chain = []
  523. while response.status_code in (301, 302, 303, 307):
  524. url = response.url
  525. redirect_chain = response.redirect_chain
  526. redirect_chain.append((url, response.status_code))
  527. url = urlsplit(url)
  528. if url.scheme:
  529. extra['wsgi.url_scheme'] = url.scheme
  530. if url.hostname:
  531. extra['SERVER_NAME'] = url.hostname
  532. if url.port:
  533. extra['SERVER_PORT'] = str(url.port)
  534. response = self.get(url.path, QueryDict(url.query), follow=False, **extra)
  535. response.redirect_chain = redirect_chain
  536. # Prevent loops
  537. if response.redirect_chain[-1] in response.redirect_chain[0:-1]:
  538. break
  539. return response