PageRenderTime 49ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/test/client.py

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