client.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. import json
  2. import mimetypes
  3. import os
  4. import sys
  5. from copy import copy
  6. from functools import partial
  7. from http import HTTPStatus
  8. from importlib import import_module
  9. from io import BytesIO
  10. from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit
  11. from asgiref.sync import sync_to_async
  12. from django.conf import settings
  13. from django.core.handlers.asgi import ASGIRequest
  14. from django.core.handlers.base import BaseHandler
  15. from django.core.handlers.wsgi import WSGIRequest
  16. from django.core.serializers.json import DjangoJSONEncoder
  17. from django.core.signals import (
  18. got_request_exception, request_finished, request_started,
  19. )
  20. from django.db import close_old_connections
  21. from django.http import HttpRequest, QueryDict, SimpleCookie
  22. from django.test import signals
  23. from django.test.utils import ContextList
  24. from django.urls import resolve
  25. from django.utils.encoding import force_bytes
  26. from django.utils.functional import SimpleLazyObject
  27. from django.utils.http import urlencode
  28. from django.utils.itercompat import is_iterable
  29. from django.utils.regex_helper import _lazy_re_compile
  30. __all__ = (
  31. 'AsyncClient', 'AsyncRequestFactory', 'Client', 'RedirectCycleError',
  32. 'RequestFactory', 'encode_file', 'encode_multipart',
  33. )
  34. BOUNDARY = 'BoUnDaRyStRiNg'
  35. MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
  36. CONTENT_TYPE_RE = _lazy_re_compile(r'.*; charset=([\w\d-]+);?')
  37. # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8
  38. JSON_CONTENT_TYPE_RE = _lazy_re_compile(r'^application\/(.+\+)?json')
  39. class RedirectCycleError(Exception):
  40. """The test client has been asked to follow a redirect loop."""
  41. def __init__(self, message, last_response):
  42. super().__init__(message)
  43. self.last_response = last_response
  44. self.redirect_chain = last_response.redirect_chain
  45. class FakePayload:
  46. """
  47. A wrapper around BytesIO that restricts what can be read since data from
  48. the network can't be sought and cannot be read outside of its content
  49. length. This makes sure that views can't do anything under the test client
  50. that wouldn't work in real life.
  51. """
  52. def __init__(self, content=None):
  53. self.__content = BytesIO()
  54. self.__len = 0
  55. self.read_started = False
  56. if content is not None:
  57. self.write(content)
  58. def __len__(self):
  59. return self.__len
  60. def read(self, num_bytes=None):
  61. if not self.read_started:
  62. self.__content.seek(0)
  63. self.read_started = True
  64. if num_bytes is None:
  65. num_bytes = self.__len or 0
  66. assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data."
  67. content = self.__content.read(num_bytes)
  68. self.__len -= num_bytes
  69. return content
  70. def write(self, content):
  71. if self.read_started:
  72. raise ValueError("Unable to write a payload after it's been read")
  73. content = force_bytes(content)
  74. self.__content.write(content)
  75. self.__len += len(content)
  76. def closing_iterator_wrapper(iterable, close):
  77. try:
  78. yield from iterable
  79. finally:
  80. request_finished.disconnect(close_old_connections)
  81. close() # will fire request_finished
  82. request_finished.connect(close_old_connections)
  83. def conditional_content_removal(request, response):
  84. """
  85. Simulate the behavior of most Web servers by removing the content of
  86. responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
  87. compliance with RFC 7230, section 3.3.3.
  88. """
  89. if 100 <= response.status_code < 200 or response.status_code in (204, 304):
  90. if response.streaming:
  91. response.streaming_content = []
  92. else:
  93. response.content = b''
  94. if request.method == 'HEAD':
  95. if response.streaming:
  96. response.streaming_content = []
  97. else:
  98. response.content = b''
  99. return response
  100. class ClientHandler(BaseHandler):
  101. """
  102. A HTTP Handler that can be used for testing purposes. Use the WSGI
  103. interface to compose requests, but return the raw HttpResponse object with
  104. the originating WSGIRequest attached to its ``wsgi_request`` attribute.
  105. """
  106. def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
  107. self.enforce_csrf_checks = enforce_csrf_checks
  108. super().__init__(*args, **kwargs)
  109. def __call__(self, environ):
  110. # Set up middleware if needed. We couldn't do this earlier, because
  111. # settings weren't available.
  112. if self._middleware_chain is None:
  113. self.load_middleware()
  114. request_started.disconnect(close_old_connections)
  115. request_started.send(sender=self.__class__, environ=environ)
  116. request_started.connect(close_old_connections)
  117. request = WSGIRequest(environ)
  118. # sneaky little hack so that we can easily get round
  119. # CsrfViewMiddleware. This makes life easier, and is probably
  120. # required for backwards compatibility with external tests against
  121. # admin views.
  122. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
  123. # Request goes through middleware.
  124. response = self.get_response(request)
  125. # Simulate behaviors of most Web servers.
  126. conditional_content_removal(request, response)
  127. # Attach the originating request to the response so that it could be
  128. # later retrieved.
  129. response.wsgi_request = request
  130. # Emulate a WSGI server by calling the close method on completion.
  131. if response.streaming:
  132. response.streaming_content = closing_iterator_wrapper(
  133. response.streaming_content, response.close)
  134. else:
  135. request_finished.disconnect(close_old_connections)
  136. response.close() # will fire request_finished
  137. request_finished.connect(close_old_connections)
  138. return response
  139. class AsyncClientHandler(BaseHandler):
  140. """An async version of ClientHandler."""
  141. def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
  142. self.enforce_csrf_checks = enforce_csrf_checks
  143. super().__init__(*args, **kwargs)
  144. async def __call__(self, scope):
  145. # Set up middleware if needed. We couldn't do this earlier, because
  146. # settings weren't available.
  147. if self._middleware_chain is None:
  148. self.load_middleware(is_async=True)
  149. # Extract body file from the scope, if provided.
  150. if '_body_file' in scope:
  151. body_file = scope.pop('_body_file')
  152. else:
  153. body_file = FakePayload('')
  154. request_started.disconnect(close_old_connections)
  155. await sync_to_async(request_started.send, thread_sensitive=False)(sender=self.__class__, scope=scope)
  156. request_started.connect(close_old_connections)
  157. request = ASGIRequest(scope, body_file)
  158. # Sneaky little hack so that we can easily get round
  159. # CsrfViewMiddleware. This makes life easier, and is probably required
  160. # for backwards compatibility with external tests against admin views.
  161. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
  162. # Request goes through middleware.
  163. response = await self.get_response_async(request)
  164. # Simulate behaviors of most Web servers.
  165. conditional_content_removal(request, response)
  166. # Attach the originating ASGI request to the response so that it could
  167. # be later retrieved.
  168. response.asgi_request = request
  169. # Emulate a server by calling the close method on completion.
  170. if response.streaming:
  171. response.streaming_content = await sync_to_async(closing_iterator_wrapper, thread_sensitive=False)(
  172. response.streaming_content,
  173. response.close,
  174. )
  175. else:
  176. request_finished.disconnect(close_old_connections)
  177. # Will fire request_finished.
  178. await sync_to_async(response.close, thread_sensitive=False)()
  179. request_finished.connect(close_old_connections)
  180. return response
  181. def store_rendered_templates(store, signal, sender, template, context, **kwargs):
  182. """
  183. Store templates and contexts that are rendered.
  184. The context is copied so that it is an accurate representation at the time
  185. of rendering.
  186. """
  187. store.setdefault('templates', []).append(template)
  188. if 'context' not in store:
  189. store['context'] = ContextList()
  190. store['context'].append(copy(context))
  191. def encode_multipart(boundary, data):
  192. """
  193. Encode multipart POST data from a dictionary of form values.
  194. The key will be used as the form data name; the value will be transmitted
  195. as content. If the value is a file, the contents of the file will be sent
  196. as an application/octet-stream; otherwise, str(value) will be sent.
  197. """
  198. lines = []
  199. def to_bytes(s):
  200. return force_bytes(s, settings.DEFAULT_CHARSET)
  201. # Not by any means perfect, but good enough for our purposes.
  202. def is_file(thing):
  203. return hasattr(thing, "read") and callable(thing.read)
  204. # Each bit of the multipart form data could be either a form value or a
  205. # file, or a *list* of form values and/or files. Remember that HTTP field
  206. # names can be duplicated!
  207. for (key, value) in data.items():
  208. if value is None:
  209. raise TypeError(
  210. "Cannot encode None for key '%s' as POST data. Did you mean "
  211. "to pass an empty string or omit the value?" % key
  212. )
  213. elif is_file(value):
  214. lines.extend(encode_file(boundary, key, value))
  215. elif not isinstance(value, str) and is_iterable(value):
  216. for item in value:
  217. if is_file(item):
  218. lines.extend(encode_file(boundary, key, item))
  219. else:
  220. lines.extend(to_bytes(val) for val in [
  221. '--%s' % boundary,
  222. 'Content-Disposition: form-data; name="%s"' % key,
  223. '',
  224. item
  225. ])
  226. else:
  227. lines.extend(to_bytes(val) for val in [
  228. '--%s' % boundary,
  229. 'Content-Disposition: form-data; name="%s"' % key,
  230. '',
  231. value
  232. ])
  233. lines.extend([
  234. to_bytes('--%s--' % boundary),
  235. b'',
  236. ])
  237. return b'\r\n'.join(lines)
  238. def encode_file(boundary, key, file):
  239. def to_bytes(s):
  240. return force_bytes(s, settings.DEFAULT_CHARSET)
  241. # file.name might not be a string. For example, it's an int for
  242. # tempfile.TemporaryFile().
  243. file_has_string_name = hasattr(file, 'name') and isinstance(file.name, str)
  244. filename = os.path.basename(file.name) if file_has_string_name else ''
  245. if hasattr(file, 'content_type'):
  246. content_type = file.content_type
  247. elif filename:
  248. content_type = mimetypes.guess_type(filename)[0]
  249. else:
  250. content_type = None
  251. if content_type is None:
  252. content_type = 'application/octet-stream'
  253. filename = filename or key
  254. return [
  255. to_bytes('--%s' % boundary),
  256. to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"'
  257. % (key, filename)),
  258. to_bytes('Content-Type: %s' % content_type),
  259. b'',
  260. to_bytes(file.read())
  261. ]
  262. class RequestFactory:
  263. """
  264. Class that lets you create mock Request objects for use in testing.
  265. Usage:
  266. rf = RequestFactory()
  267. get_request = rf.get('/hello/')
  268. post_request = rf.post('/submit/', {'foo': 'bar'})
  269. Once you have a request object you can pass it to any view function,
  270. just as if that view had been hooked up using a URLconf.
  271. """
  272. def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
  273. self.json_encoder = json_encoder
  274. self.defaults = defaults
  275. self.cookies = SimpleCookie()
  276. self.errors = BytesIO()
  277. def _base_environ(self, **request):
  278. """
  279. The base environment for a request.
  280. """
  281. # This is a minimal valid WSGI environ dictionary, plus:
  282. # - HTTP_COOKIE: for cookie support,
  283. # - REMOTE_ADDR: often useful, see #8551.
  284. # See https://www.python.org/dev/peps/pep-3333/#environ-variables
  285. return {
  286. 'HTTP_COOKIE': '; '.join(sorted(
  287. '%s=%s' % (morsel.key, morsel.coded_value)
  288. for morsel in self.cookies.values()
  289. )),
  290. 'PATH_INFO': '/',
  291. 'REMOTE_ADDR': '127.0.0.1',
  292. 'REQUEST_METHOD': 'GET',
  293. 'SCRIPT_NAME': '',
  294. 'SERVER_NAME': 'testserver',
  295. 'SERVER_PORT': '80',
  296. 'SERVER_PROTOCOL': 'HTTP/1.1',
  297. 'wsgi.version': (1, 0),
  298. 'wsgi.url_scheme': 'http',
  299. 'wsgi.input': FakePayload(b''),
  300. 'wsgi.errors': self.errors,
  301. 'wsgi.multiprocess': True,
  302. 'wsgi.multithread': False,
  303. 'wsgi.run_once': False,
  304. **self.defaults,
  305. **request,
  306. }
  307. def request(self, **request):
  308. "Construct a generic request object."
  309. return WSGIRequest(self._base_environ(**request))
  310. def _encode_data(self, data, content_type):
  311. if content_type is MULTIPART_CONTENT:
  312. return encode_multipart(BOUNDARY, data)
  313. else:
  314. # Encode the content so that the byte representation is correct.
  315. match = CONTENT_TYPE_RE.match(content_type)
  316. if match:
  317. charset = match[1]
  318. else:
  319. charset = settings.DEFAULT_CHARSET
  320. return force_bytes(data, encoding=charset)
  321. def _encode_json(self, data, content_type):
  322. """
  323. Return encoded JSON if data is a dict, list, or tuple and content_type
  324. is application/json.
  325. """
  326. should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(data, (dict, list, tuple))
  327. return json.dumps(data, cls=self.json_encoder) if should_encode else data
  328. def _get_path(self, parsed):
  329. path = parsed.path
  330. # If there are parameters, add them
  331. if parsed.params:
  332. path += ";" + parsed.params
  333. path = unquote_to_bytes(path)
  334. # Replace the behavior where non-ASCII values in the WSGI environ are
  335. # arbitrarily decoded with ISO-8859-1.
  336. # Refs comment in `get_bytes_from_wsgi()`.
  337. return path.decode('iso-8859-1')
  338. def get(self, path, data=None, secure=False, **extra):
  339. """Construct a GET request."""
  340. data = {} if data is None else data
  341. return self.generic('GET', path, secure=secure, **{
  342. 'QUERY_STRING': urlencode(data, doseq=True),
  343. **extra,
  344. })
  345. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  346. secure=False, **extra):
  347. """Construct a POST request."""
  348. data = self._encode_json({} if data is None else data, content_type)
  349. post_data = self._encode_data(data, content_type)
  350. return self.generic('POST', path, post_data, content_type,
  351. secure=secure, **extra)
  352. def head(self, path, data=None, secure=False, **extra):
  353. """Construct a HEAD request."""
  354. data = {} if data is None else data
  355. return self.generic('HEAD', path, secure=secure, **{
  356. 'QUERY_STRING': urlencode(data, doseq=True),
  357. **extra,
  358. })
  359. def trace(self, path, secure=False, **extra):
  360. """Construct a TRACE request."""
  361. return self.generic('TRACE', path, secure=secure, **extra)
  362. def options(self, path, data='', content_type='application/octet-stream',
  363. secure=False, **extra):
  364. "Construct an OPTIONS request."
  365. return self.generic('OPTIONS', path, data, content_type,
  366. secure=secure, **extra)
  367. def put(self, path, data='', content_type='application/octet-stream',
  368. secure=False, **extra):
  369. """Construct a PUT request."""
  370. data = self._encode_json(data, content_type)
  371. return self.generic('PUT', path, data, content_type,
  372. secure=secure, **extra)
  373. def patch(self, path, data='', content_type='application/octet-stream',
  374. secure=False, **extra):
  375. """Construct a PATCH request."""
  376. data = self._encode_json(data, content_type)
  377. return self.generic('PATCH', path, data, content_type,
  378. secure=secure, **extra)
  379. def delete(self, path, data='', content_type='application/octet-stream',
  380. secure=False, **extra):
  381. """Construct a DELETE request."""
  382. data = self._encode_json(data, content_type)
  383. return self.generic('DELETE', path, data, content_type,
  384. secure=secure, **extra)
  385. def generic(self, method, path, data='',
  386. content_type='application/octet-stream', secure=False,
  387. **extra):
  388. """Construct an arbitrary HTTP request."""
  389. parsed = urlparse(str(path)) # path can be lazy
  390. data = force_bytes(data, settings.DEFAULT_CHARSET)
  391. r = {
  392. 'PATH_INFO': self._get_path(parsed),
  393. 'REQUEST_METHOD': method,
  394. 'SERVER_PORT': '443' if secure else '80',
  395. 'wsgi.url_scheme': 'https' if secure else 'http',
  396. }
  397. if data:
  398. r.update({
  399. 'CONTENT_LENGTH': str(len(data)),
  400. 'CONTENT_TYPE': content_type,
  401. 'wsgi.input': FakePayload(data),
  402. })
  403. r.update(extra)
  404. # If QUERY_STRING is absent or empty, we want to extract it from the URL.
  405. if not r.get('QUERY_STRING'):
  406. # WSGI requires latin-1 encoded strings. See get_path_info().
  407. query_string = parsed[4].encode().decode('iso-8859-1')
  408. r['QUERY_STRING'] = query_string
  409. return self.request(**r)
  410. class AsyncRequestFactory(RequestFactory):
  411. """
  412. Class that lets you create mock ASGI-like Request objects for use in
  413. testing. Usage:
  414. rf = AsyncRequestFactory()
  415. get_request = await rf.get('/hello/')
  416. post_request = await rf.post('/submit/', {'foo': 'bar'})
  417. Once you have a request object you can pass it to any view function,
  418. including synchronous ones. The reason we have a separate class here is:
  419. a) this makes ASGIRequest subclasses, and
  420. b) AsyncTestClient can subclass it.
  421. """
  422. def _base_scope(self, **request):
  423. """The base scope for a request."""
  424. # This is a minimal valid ASGI scope, plus:
  425. # - headers['cookie'] for cookie support,
  426. # - 'client' often useful, see #8551.
  427. scope = {
  428. 'asgi': {'version': '3.0'},
  429. 'type': 'http',
  430. 'http_version': '1.1',
  431. 'client': ['127.0.0.1', 0],
  432. 'server': ('testserver', '80'),
  433. 'scheme': 'http',
  434. 'method': 'GET',
  435. 'headers': [],
  436. **self.defaults,
  437. **request,
  438. }
  439. scope['headers'].append((
  440. b'cookie',
  441. b'; '.join(sorted(
  442. ('%s=%s' % (morsel.key, morsel.coded_value)).encode('ascii')
  443. for morsel in self.cookies.values()
  444. )),
  445. ))
  446. return scope
  447. def request(self, **request):
  448. """Construct a generic request object."""
  449. # This is synchronous, which means all methods on this class are.
  450. # AsyncClient, however, has an async request function, which makes all
  451. # its methods async.
  452. if '_body_file' in request:
  453. body_file = request.pop('_body_file')
  454. else:
  455. body_file = FakePayload('')
  456. return ASGIRequest(self._base_scope(**request), body_file)
  457. def generic(
  458. self, method, path, data='', content_type='application/octet-stream',
  459. secure=False, **extra,
  460. ):
  461. """Construct an arbitrary HTTP request."""
  462. parsed = urlparse(str(path)) # path can be lazy.
  463. data = force_bytes(data, settings.DEFAULT_CHARSET)
  464. s = {
  465. 'method': method,
  466. 'path': self._get_path(parsed),
  467. 'server': ('127.0.0.1', '443' if secure else '80'),
  468. 'scheme': 'https' if secure else 'http',
  469. 'headers': [(b'host', b'testserver')],
  470. }
  471. if data:
  472. s['headers'].extend([
  473. (b'content-length', str(len(data)).encode('ascii')),
  474. (b'content-type', content_type.encode('ascii')),
  475. ])
  476. s['_body_file'] = FakePayload(data)
  477. follow = extra.pop('follow', None)
  478. if follow is not None:
  479. s['follow'] = follow
  480. s['headers'] += [
  481. (key.lower().encode('ascii'), value.encode('latin1'))
  482. for key, value in extra.items()
  483. ]
  484. # If QUERY_STRING is absent or empty, we want to extract it from the
  485. # URL.
  486. if not s.get('query_string'):
  487. s['query_string'] = parsed[4]
  488. return self.request(**s)
  489. class ClientMixin:
  490. """
  491. Mixin with common methods between Client and AsyncClient.
  492. """
  493. def store_exc_info(self, **kwargs):
  494. """Store exceptions when they are generated by a view."""
  495. self.exc_info = sys.exc_info()
  496. def check_exception(self, response):
  497. """
  498. Look for a signaled exception, clear the current context exception
  499. data, re-raise the signaled exception, and clear the signaled exception
  500. from the local cache.
  501. """
  502. response.exc_info = self.exc_info
  503. if self.exc_info:
  504. _, exc_value, _ = self.exc_info
  505. self.exc_info = None
  506. if self.raise_request_exception:
  507. raise exc_value
  508. @property
  509. def session(self):
  510. """Return the current session variables."""
  511. engine = import_module(settings.SESSION_ENGINE)
  512. cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
  513. if cookie:
  514. return engine.SessionStore(cookie.value)
  515. session = engine.SessionStore()
  516. session.save()
  517. self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
  518. return session
  519. def login(self, **credentials):
  520. """
  521. Set the Factory to appear as if it has successfully logged into a site.
  522. Return True if login is possible or False if the provided credentials
  523. are incorrect.
  524. """
  525. from django.contrib.auth import authenticate
  526. user = authenticate(**credentials)
  527. if user:
  528. self._login(user)
  529. return True
  530. return False
  531. def force_login(self, user, backend=None):
  532. def get_backend():
  533. from django.contrib.auth import load_backend
  534. for backend_path in settings.AUTHENTICATION_BACKENDS:
  535. backend = load_backend(backend_path)
  536. if hasattr(backend, 'get_user'):
  537. return backend_path
  538. if backend is None:
  539. backend = get_backend()
  540. user.backend = backend
  541. self._login(user, backend)
  542. def _login(self, user, backend=None):
  543. from django.contrib.auth import login
  544. # Create a fake request to store login details.
  545. request = HttpRequest()
  546. if self.session:
  547. request.session = self.session
  548. else:
  549. engine = import_module(settings.SESSION_ENGINE)
  550. request.session = engine.SessionStore()
  551. login(request, user, backend)
  552. # Save the session values.
  553. request.session.save()
  554. # Set the cookie to represent the session.
  555. session_cookie = settings.SESSION_COOKIE_NAME
  556. self.cookies[session_cookie] = request.session.session_key
  557. cookie_data = {
  558. 'max-age': None,
  559. 'path': '/',
  560. 'domain': settings.SESSION_COOKIE_DOMAIN,
  561. 'secure': settings.SESSION_COOKIE_SECURE or None,
  562. 'expires': None,
  563. }
  564. self.cookies[session_cookie].update(cookie_data)
  565. def logout(self):
  566. """Log out the user by removing the cookies and session object."""
  567. from django.contrib.auth import get_user, logout
  568. request = HttpRequest()
  569. if self.session:
  570. request.session = self.session
  571. request.user = get_user(request)
  572. else:
  573. engine = import_module(settings.SESSION_ENGINE)
  574. request.session = engine.SessionStore()
  575. logout(request)
  576. self.cookies = SimpleCookie()
  577. def _parse_json(self, response, **extra):
  578. if not hasattr(response, '_json'):
  579. if not JSON_CONTENT_TYPE_RE.match(response.get('Content-Type')):
  580. raise ValueError(
  581. 'Content-Type header is "%s", not "application/json"'
  582. % response.get('Content-Type')
  583. )
  584. response._json = json.loads(response.content.decode(response.charset), **extra)
  585. return response._json
  586. class Client(ClientMixin, RequestFactory):
  587. """
  588. A class that can act as a client for testing purposes.
  589. It allows the user to compose GET and POST requests, and
  590. obtain the response that the server gave to those requests.
  591. The server Response objects are annotated with the details
  592. of the contexts and templates that were rendered during the
  593. process of serving the request.
  594. Client objects are stateful - they will retain cookie (and
  595. thus session) details for the lifetime of the Client instance.
  596. This is not intended as a replacement for Twill/Selenium or
  597. the like - it is here to allow testing against the
  598. contexts and templates produced by a view, rather than the
  599. HTML rendered to the end-user.
  600. """
  601. def __init__(self, enforce_csrf_checks=False, raise_request_exception=True, **defaults):
  602. super().__init__(**defaults)
  603. self.handler = ClientHandler(enforce_csrf_checks)
  604. self.raise_request_exception = raise_request_exception
  605. self.exc_info = None
  606. self.extra = None
  607. def request(self, **request):
  608. """
  609. The master request method. Compose the environment dictionary and pass
  610. to the handler, return the result of the handler. Assume defaults for
  611. the query environment, which can be overridden using the arguments to
  612. the request.
  613. """
  614. environ = self._base_environ(**request)
  615. # Curry a data dictionary into an instance of the template renderer
  616. # callback function.
  617. data = {}
  618. on_template_render = partial(store_rendered_templates, data)
  619. signal_uid = "template-render-%s" % id(request)
  620. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  621. # Capture exceptions created by the handler.
  622. exception_uid = "request-exception-%s" % id(request)
  623. got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
  624. try:
  625. response = self.handler(environ)
  626. finally:
  627. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  628. got_request_exception.disconnect(dispatch_uid=exception_uid)
  629. # Check for signaled exceptions.
  630. self.check_exception(response)
  631. # Save the client and request that stimulated the response.
  632. response.client = self
  633. response.request = request
  634. # Add any rendered template detail to the response.
  635. response.templates = data.get('templates', [])
  636. response.context = data.get('context')
  637. response.json = partial(self._parse_json, response)
  638. # Attach the ResolverMatch instance to the response.
  639. response.resolver_match = SimpleLazyObject(lambda: resolve(request['PATH_INFO']))
  640. # Flatten a single context. Not really necessary anymore thanks to the
  641. # __getattr__ flattening in ContextList, but has some edge case
  642. # backwards compatibility implications.
  643. if response.context and len(response.context) == 1:
  644. response.context = response.context[0]
  645. # Update persistent cookie data.
  646. if response.cookies:
  647. self.cookies.update(response.cookies)
  648. return response
  649. def get(self, path, data=None, follow=False, secure=False, **extra):
  650. """Request a response from the server using GET."""
  651. self.extra = extra
  652. response = super().get(path, data=data, secure=secure, **extra)
  653. if follow:
  654. response = self._handle_redirects(response, data=data, **extra)
  655. return response
  656. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  657. follow=False, secure=False, **extra):
  658. """Request a response from the server using POST."""
  659. self.extra = extra
  660. response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
  661. if follow:
  662. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  663. return response
  664. def head(self, path, data=None, follow=False, secure=False, **extra):
  665. """Request a response from the server using HEAD."""
  666. self.extra = extra
  667. response = super().head(path, data=data, secure=secure, **extra)
  668. if follow:
  669. response = self._handle_redirects(response, data=data, **extra)
  670. return response
  671. def options(self, path, data='', content_type='application/octet-stream',
  672. follow=False, secure=False, **extra):
  673. """Request a response from the server using OPTIONS."""
  674. self.extra = extra
  675. response = super().options(path, data=data, content_type=content_type, secure=secure, **extra)
  676. if follow:
  677. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  678. return response
  679. def put(self, path, data='', content_type='application/octet-stream',
  680. follow=False, secure=False, **extra):
  681. """Send a resource to the server using PUT."""
  682. self.extra = extra
  683. response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
  684. if follow:
  685. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  686. return response
  687. def patch(self, path, data='', content_type='application/octet-stream',
  688. follow=False, secure=False, **extra):
  689. """Send a resource to the server using PATCH."""
  690. self.extra = extra
  691. response = super().patch(path, data=data, content_type=content_type, secure=secure, **extra)
  692. if follow:
  693. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  694. return response
  695. def delete(self, path, data='', content_type='application/octet-stream',
  696. follow=False, secure=False, **extra):
  697. """Send a DELETE request to the server."""
  698. self.extra = extra
  699. response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra)
  700. if follow:
  701. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  702. return response
  703. def trace(self, path, data='', follow=False, secure=False, **extra):
  704. """Send a TRACE request to the server."""
  705. self.extra = extra
  706. response = super().trace(path, data=data, secure=secure, **extra)
  707. if follow:
  708. response = self._handle_redirects(response, data=data, **extra)
  709. return response
  710. def _handle_redirects(self, response, data='', content_type='', **extra):
  711. """
  712. Follow any redirects by requesting responses from the server using GET.
  713. """
  714. response.redirect_chain = []
  715. redirect_status_codes = (
  716. HTTPStatus.MOVED_PERMANENTLY,
  717. HTTPStatus.FOUND,
  718. HTTPStatus.SEE_OTHER,
  719. HTTPStatus.TEMPORARY_REDIRECT,
  720. HTTPStatus.PERMANENT_REDIRECT,
  721. )
  722. while response.status_code in redirect_status_codes:
  723. response_url = response.url
  724. redirect_chain = response.redirect_chain
  725. redirect_chain.append((response_url, response.status_code))
  726. url = urlsplit(response_url)
  727. if url.scheme:
  728. extra['wsgi.url_scheme'] = url.scheme
  729. if url.hostname:
  730. extra['SERVER_NAME'] = url.hostname
  731. if url.port:
  732. extra['SERVER_PORT'] = str(url.port)
  733. # Prepend the request path to handle relative path redirects
  734. path = url.path
  735. if not path.startswith('/'):
  736. path = urljoin(response.request['PATH_INFO'], path)
  737. if response.status_code in (HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT):
  738. # Preserve request method and query string (if needed)
  739. # post-redirect for 307/308 responses.
  740. request_method = response.request['REQUEST_METHOD'].lower()
  741. if request_method not in ('get', 'head'):
  742. extra['QUERY_STRING'] = url.query
  743. request_method = getattr(self, request_method)
  744. else:
  745. request_method = self.get
  746. data = QueryDict(url.query)
  747. content_type = None
  748. response = request_method(path, data=data, content_type=content_type, follow=False, **extra)
  749. response.redirect_chain = redirect_chain
  750. if redirect_chain[-1] in redirect_chain[:-1]:
  751. # Check that we're not redirecting to somewhere we've already
  752. # been to, to prevent loops.
  753. raise RedirectCycleError("Redirect loop detected.", last_response=response)
  754. if len(redirect_chain) > 20:
  755. # Such a lengthy chain likely also means a loop, but one with
  756. # a growing path, changing view, or changing query argument;
  757. # 20 is the value of "network.http.redirection-limit" from Firefox.
  758. raise RedirectCycleError("Too many redirects.", last_response=response)
  759. return response
  760. class AsyncClient(ClientMixin, AsyncRequestFactory):
  761. """
  762. An async version of Client that creates ASGIRequests and calls through an
  763. async request path.
  764. Does not currently support "follow" on its methods.
  765. """
  766. def __init__(self, enforce_csrf_checks=False, raise_request_exception=True, **defaults):
  767. super().__init__(**defaults)
  768. self.handler = AsyncClientHandler(enforce_csrf_checks)
  769. self.raise_request_exception = raise_request_exception
  770. self.exc_info = None
  771. self.extra = None
  772. async def request(self, **request):
  773. """
  774. The master request method. Compose the scope dictionary and pass to the
  775. handler, return the result of the handler. Assume defaults for the
  776. query environment, which can be overridden using the arguments to the
  777. request.
  778. """
  779. if 'follow' in request:
  780. raise NotImplementedError(
  781. 'AsyncClient request methods do not accept the follow '
  782. 'parameter.'
  783. )
  784. scope = self._base_scope(**request)
  785. # Curry a data dictionary into an instance of the template renderer
  786. # callback function.
  787. data = {}
  788. on_template_render = partial(store_rendered_templates, data)
  789. signal_uid = 'template-render-%s' % id(request)
  790. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  791. # Capture exceptions created by the handler.
  792. exception_uid = 'request-exception-%s' % id(request)
  793. got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
  794. try:
  795. response = await self.handler(scope)
  796. finally:
  797. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  798. got_request_exception.disconnect(dispatch_uid=exception_uid)
  799. # Check for signaled exceptions.
  800. self.check_exception(response)
  801. # Save the client and request that stimulated the response.
  802. response.client = self
  803. response.request = request
  804. # Add any rendered template detail to the response.
  805. response.templates = data.get('templates', [])
  806. response.context = data.get('context')
  807. response.json = partial(self._parse_json, response)
  808. # Attach the ResolverMatch instance to the response.
  809. response.resolver_match = SimpleLazyObject(lambda: resolve(request['path']))
  810. # Flatten a single context. Not really necessary anymore thanks to the
  811. # __getattr__ flattening in ContextList, but has some edge case
  812. # backwards compatibility implications.
  813. if response.context and len(response.context) == 1:
  814. response.context = response.context[0]
  815. # Update persistent cookie data.
  816. if response.cookies:
  817. self.cookies.update(response.cookies)
  818. return response