client.py 23 KB

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