Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.py 38KB

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