client.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. import json
  2. import mimetypes
  3. import os
  4. import sys
  5. from collections.abc import Iterable
  6. from copy import copy
  7. from functools import partial
  8. from http import HTTPStatus
  9. from importlib import import_module
  10. from io import BytesIO, IOBase
  11. from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit
  12. from asgiref.sync import sync_to_async
  13. from django.conf import settings
  14. from django.core.handlers.asgi import ASGIRequest
  15. from django.core.handlers.base import BaseHandler
  16. from django.core.handlers.wsgi import LimitedStream, WSGIRequest
  17. from django.core.serializers.json import DjangoJSONEncoder
  18. from django.core.signals import got_request_exception, request_finished, request_started
  19. from django.db import close_old_connections
  20. from django.http import HttpHeaders, HttpRequest, QueryDict, SimpleCookie
  21. from django.test import signals
  22. from django.test.utils import ContextList
  23. from django.urls import resolve
  24. from django.utils.encoding import force_bytes
  25. from django.utils.functional import SimpleLazyObject
  26. from django.utils.http import urlencode
  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. REDIRECT_STATUS_CODES = frozenset(
  43. [
  44. HTTPStatus.MOVED_PERMANENTLY,
  45. HTTPStatus.FOUND,
  46. HTTPStatus.SEE_OTHER,
  47. HTTPStatus.TEMPORARY_REDIRECT,
  48. HTTPStatus.PERMANENT_REDIRECT,
  49. ]
  50. )
  51. class RedirectCycleError(Exception):
  52. """The test client has been asked to follow a redirect loop."""
  53. def __init__(self, message, last_response):
  54. super().__init__(message)
  55. self.last_response = last_response
  56. self.redirect_chain = last_response.redirect_chain
  57. class FakePayload(IOBase):
  58. """
  59. A wrapper around BytesIO that restricts what can be read since data from
  60. the network can't be sought and cannot be read outside of its content
  61. length. This makes sure that views can't do anything under the test client
  62. that wouldn't work in real life.
  63. """
  64. def __init__(self, initial_bytes=None):
  65. self.__content = BytesIO()
  66. self.__len = 0
  67. self.read_started = False
  68. if initial_bytes is not None:
  69. self.write(initial_bytes)
  70. def __len__(self):
  71. return self.__len
  72. def read(self, size=-1, /):
  73. if not self.read_started:
  74. self.__content.seek(0)
  75. self.read_started = True
  76. if size == -1 or size is None:
  77. size = self.__len
  78. assert (
  79. self.__len >= size
  80. ), "Cannot read more than the available bytes from the HTTP incoming data."
  81. content = self.__content.read(size)
  82. self.__len -= len(content)
  83. return content
  84. def readline(self, size=-1, /):
  85. if not self.read_started:
  86. self.__content.seek(0)
  87. self.read_started = True
  88. if size == -1 or size is None:
  89. size = self.__len
  90. assert (
  91. self.__len >= size
  92. ), "Cannot read more than the available bytes from the HTTP incoming data."
  93. content = self.__content.readline(size)
  94. self.__len -= len(content)
  95. return content
  96. def write(self, b, /):
  97. if self.read_started:
  98. raise ValueError("Unable to write a payload after it's been read")
  99. content = force_bytes(b)
  100. self.__content.write(content)
  101. self.__len += len(content)
  102. def closing_iterator_wrapper(iterable, close):
  103. try:
  104. yield from iterable
  105. finally:
  106. request_finished.disconnect(close_old_connections)
  107. close() # will fire request_finished
  108. request_finished.connect(close_old_connections)
  109. async def aclosing_iterator_wrapper(iterable, close):
  110. try:
  111. async for chunk in iterable:
  112. yield chunk
  113. finally:
  114. request_finished.disconnect(close_old_connections)
  115. close() # will fire request_finished
  116. request_finished.connect(close_old_connections)
  117. def conditional_content_removal(request, response):
  118. """
  119. Simulate the behavior of most web servers by removing the content of
  120. responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
  121. compliance with RFC 9112 Section 6.3.
  122. """
  123. if 100 <= response.status_code < 200 or response.status_code in (204, 304):
  124. if response.streaming:
  125. response.streaming_content = []
  126. else:
  127. response.content = b""
  128. if request.method == "HEAD":
  129. if response.streaming:
  130. response.streaming_content = []
  131. else:
  132. response.content = b""
  133. return response
  134. class ClientHandler(BaseHandler):
  135. """
  136. An HTTP Handler that can be used for testing purposes. Use the WSGI
  137. interface to compose requests, but return the raw HttpResponse object with
  138. the originating WSGIRequest attached to its ``wsgi_request`` attribute.
  139. """
  140. def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
  141. self.enforce_csrf_checks = enforce_csrf_checks
  142. super().__init__(*args, **kwargs)
  143. def __call__(self, environ):
  144. # Set up middleware if needed. We couldn't do this earlier, because
  145. # settings weren't available.
  146. if self._middleware_chain is None:
  147. self.load_middleware()
  148. request_started.disconnect(close_old_connections)
  149. request_started.send(sender=self.__class__, environ=environ)
  150. request_started.connect(close_old_connections)
  151. request = WSGIRequest(environ)
  152. # sneaky little hack so that we can easily get round
  153. # CsrfViewMiddleware. This makes life easier, and is probably
  154. # required for backwards compatibility with external tests against
  155. # admin views.
  156. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
  157. # Request goes through middleware.
  158. response = self.get_response(request)
  159. # Simulate behaviors of most web servers.
  160. conditional_content_removal(request, response)
  161. # Attach the originating request to the response so that it could be
  162. # later retrieved.
  163. response.wsgi_request = request
  164. # Emulate a WSGI server by calling the close method on completion.
  165. if response.streaming:
  166. if response.is_async:
  167. response.streaming_content = aclosing_iterator_wrapper(
  168. response.streaming_content, response.close
  169. )
  170. else:
  171. response.streaming_content = closing_iterator_wrapper(
  172. response.streaming_content, response.close
  173. )
  174. else:
  175. request_finished.disconnect(close_old_connections)
  176. response.close() # will fire request_finished
  177. request_finished.connect(close_old_connections)
  178. return response
  179. class AsyncClientHandler(BaseHandler):
  180. """An async version of ClientHandler."""
  181. def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
  182. self.enforce_csrf_checks = enforce_csrf_checks
  183. super().__init__(*args, **kwargs)
  184. async def __call__(self, scope):
  185. # Set up middleware if needed. We couldn't do this earlier, because
  186. # settings weren't available.
  187. if self._middleware_chain is None:
  188. self.load_middleware(is_async=True)
  189. # Extract body file from the scope, if provided.
  190. if "_body_file" in scope:
  191. body_file = scope.pop("_body_file")
  192. else:
  193. body_file = FakePayload("")
  194. request_started.disconnect(close_old_connections)
  195. await request_started.asend(sender=self.__class__, scope=scope)
  196. request_started.connect(close_old_connections)
  197. # Wrap FakePayload body_file to allow large read() in test environment.
  198. request = ASGIRequest(scope, LimitedStream(body_file, len(body_file)))
  199. # Sneaky little hack so that we can easily get round
  200. # CsrfViewMiddleware. This makes life easier, and is probably required
  201. # for backwards compatibility with external tests against admin views.
  202. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
  203. # Request goes through middleware.
  204. response = await self.get_response_async(request)
  205. # Simulate behaviors of most web servers.
  206. conditional_content_removal(request, response)
  207. # Attach the originating ASGI request to the response so that it could
  208. # be later retrieved.
  209. response.asgi_request = request
  210. # Emulate a server by calling the close method on completion.
  211. if response.streaming:
  212. if response.is_async:
  213. response.streaming_content = aclosing_iterator_wrapper(
  214. response.streaming_content, response.close
  215. )
  216. else:
  217. response.streaming_content = closing_iterator_wrapper(
  218. response.streaming_content, response.close
  219. )
  220. else:
  221. request_finished.disconnect(close_old_connections)
  222. # Will fire request_finished.
  223. await sync_to_async(response.close, thread_sensitive=False)()
  224. request_finished.connect(close_old_connections)
  225. return response
  226. def store_rendered_templates(store, signal, sender, template, context, **kwargs):
  227. """
  228. Store templates and contexts that are rendered.
  229. The context is copied so that it is an accurate representation at the time
  230. of rendering.
  231. """
  232. store.setdefault("templates", []).append(template)
  233. if "context" not in store:
  234. store["context"] = ContextList()
  235. store["context"].append(copy(context))
  236. def encode_multipart(boundary, data):
  237. """
  238. Encode multipart POST data from a dictionary of form values.
  239. The key will be used as the form data name; the value will be transmitted
  240. as content. If the value is a file, the contents of the file will be sent
  241. as an application/octet-stream; otherwise, str(value) will be sent.
  242. """
  243. lines = []
  244. def to_bytes(s):
  245. return force_bytes(s, settings.DEFAULT_CHARSET)
  246. # Not by any means perfect, but good enough for our purposes.
  247. def is_file(thing):
  248. return hasattr(thing, "read") and callable(thing.read)
  249. # Each bit of the multipart form data could be either a form value or a
  250. # file, or a *list* of form values and/or files. Remember that HTTP field
  251. # names can be duplicated!
  252. for key, value in data.items():
  253. if value is None:
  254. raise TypeError(
  255. "Cannot encode None for key '%s' as POST data. Did you mean "
  256. "to pass an empty string or omit the value?" % key
  257. )
  258. elif is_file(value):
  259. lines.extend(encode_file(boundary, key, value))
  260. elif not isinstance(value, str) and isinstance(value, Iterable):
  261. for item in value:
  262. if is_file(item):
  263. lines.extend(encode_file(boundary, key, item))
  264. else:
  265. lines.extend(
  266. to_bytes(val)
  267. for val in [
  268. "--%s" % boundary,
  269. 'Content-Disposition: form-data; name="%s"' % key,
  270. "",
  271. item,
  272. ]
  273. )
  274. else:
  275. lines.extend(
  276. to_bytes(val)
  277. for val in [
  278. "--%s" % boundary,
  279. 'Content-Disposition: form-data; name="%s"' % key,
  280. "",
  281. value,
  282. ]
  283. )
  284. lines.extend(
  285. [
  286. to_bytes("--%s--" % boundary),
  287. b"",
  288. ]
  289. )
  290. return b"\r\n".join(lines)
  291. def encode_file(boundary, key, file):
  292. def to_bytes(s):
  293. return force_bytes(s, settings.DEFAULT_CHARSET)
  294. # file.name might not be a string. For example, it's an int for
  295. # tempfile.TemporaryFile().
  296. file_has_string_name = hasattr(file, "name") and isinstance(file.name, str)
  297. filename = os.path.basename(file.name) if file_has_string_name else ""
  298. if hasattr(file, "content_type"):
  299. content_type = file.content_type
  300. elif filename:
  301. content_type = mimetypes.guess_type(filename)[0]
  302. else:
  303. content_type = None
  304. if content_type is None:
  305. content_type = "application/octet-stream"
  306. filename = filename or key
  307. return [
  308. to_bytes("--%s" % boundary),
  309. to_bytes(
  310. 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)
  311. ),
  312. to_bytes("Content-Type: %s" % content_type),
  313. b"",
  314. to_bytes(file.read()),
  315. ]
  316. class RequestFactory:
  317. """
  318. Class that lets you create mock Request objects for use in testing.
  319. Usage:
  320. rf = RequestFactory()
  321. get_request = rf.get('/hello/')
  322. post_request = rf.post('/submit/', {'foo': 'bar'})
  323. Once you have a request object you can pass it to any view function,
  324. just as if that view had been hooked up using a URLconf.
  325. """
  326. def __init__(
  327. self,
  328. *,
  329. json_encoder=DjangoJSONEncoder,
  330. headers=None,
  331. query_params=None,
  332. **defaults,
  333. ):
  334. self.json_encoder = json_encoder
  335. self.defaults = defaults
  336. self.cookies = SimpleCookie()
  337. self.errors = BytesIO()
  338. if headers:
  339. self.defaults.update(HttpHeaders.to_wsgi_names(headers))
  340. if query_params:
  341. self.defaults["QUERY_STRING"] = urlencode(query_params, doseq=True)
  342. def _base_environ(self, **request):
  343. """
  344. The base environment for a request.
  345. """
  346. # This is a minimal valid WSGI environ dictionary, plus:
  347. # - HTTP_COOKIE: for cookie support,
  348. # - REMOTE_ADDR: often useful, see #8551.
  349. # See https://www.python.org/dev/peps/pep-3333/#environ-variables
  350. return {
  351. "HTTP_COOKIE": "; ".join(
  352. sorted(
  353. "%s=%s" % (morsel.key, morsel.coded_value)
  354. for morsel in self.cookies.values()
  355. )
  356. ),
  357. "PATH_INFO": "/",
  358. "REMOTE_ADDR": "127.0.0.1",
  359. "REQUEST_METHOD": "GET",
  360. "SCRIPT_NAME": "",
  361. "SERVER_NAME": "testserver",
  362. "SERVER_PORT": "80",
  363. "SERVER_PROTOCOL": "HTTP/1.1",
  364. "wsgi.version": (1, 0),
  365. "wsgi.url_scheme": "http",
  366. "wsgi.input": FakePayload(b""),
  367. "wsgi.errors": self.errors,
  368. "wsgi.multiprocess": True,
  369. "wsgi.multithread": False,
  370. "wsgi.run_once": False,
  371. **self.defaults,
  372. **request,
  373. }
  374. def request(self, **request):
  375. "Construct a generic request object."
  376. return WSGIRequest(self._base_environ(**request))
  377. def _encode_data(self, data, content_type):
  378. if content_type is MULTIPART_CONTENT:
  379. return encode_multipart(BOUNDARY, data)
  380. else:
  381. # Encode the content so that the byte representation is correct.
  382. match = CONTENT_TYPE_RE.match(content_type)
  383. if match:
  384. charset = match[1]
  385. else:
  386. charset = settings.DEFAULT_CHARSET
  387. return force_bytes(data, encoding=charset)
  388. def _encode_json(self, data, content_type):
  389. """
  390. Return encoded JSON if data is a dict, list, or tuple and content_type
  391. is application/json.
  392. """
  393. should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(
  394. data, (dict, list, tuple)
  395. )
  396. return json.dumps(data, cls=self.json_encoder) if should_encode else data
  397. def _get_path(self, parsed):
  398. path = parsed.path
  399. # If there are parameters, add them
  400. if parsed.params:
  401. path += ";" + parsed.params
  402. path = unquote_to_bytes(path)
  403. # Replace the behavior where non-ASCII values in the WSGI environ are
  404. # arbitrarily decoded with ISO-8859-1.
  405. # Refs comment in `get_bytes_from_wsgi()`.
  406. return path.decode("iso-8859-1")
  407. def get(
  408. self, path, data=None, secure=False, *, headers=None, query_params=None, **extra
  409. ):
  410. """Construct a GET request."""
  411. if query_params and data:
  412. raise ValueError("query_params and data arguments are mutually exclusive.")
  413. query_params = data or query_params
  414. query_params = {} if query_params is None else query_params
  415. return self.generic(
  416. "GET",
  417. path,
  418. secure=secure,
  419. headers=headers,
  420. query_params=query_params,
  421. **extra,
  422. )
  423. def post(
  424. self,
  425. path,
  426. data=None,
  427. content_type=MULTIPART_CONTENT,
  428. secure=False,
  429. *,
  430. headers=None,
  431. query_params=None,
  432. **extra,
  433. ):
  434. """Construct a POST request."""
  435. data = self._encode_json({} if data is None else data, content_type)
  436. post_data = self._encode_data(data, content_type)
  437. return self.generic(
  438. "POST",
  439. path,
  440. post_data,
  441. content_type,
  442. secure=secure,
  443. headers=headers,
  444. query_params=query_params,
  445. **extra,
  446. )
  447. def head(
  448. self, path, data=None, secure=False, *, headers=None, query_params=None, **extra
  449. ):
  450. """Construct a HEAD request."""
  451. if query_params and data:
  452. raise ValueError("query_params and data arguments are mutually exclusive.")
  453. query_params = data or query_params
  454. query_params = {} if query_params is None else query_params
  455. return self.generic(
  456. "HEAD",
  457. path,
  458. secure=secure,
  459. headers=headers,
  460. query_params=query_params,
  461. **extra,
  462. )
  463. def trace(self, path, secure=False, *, headers=None, query_params=None, **extra):
  464. """Construct a TRACE request."""
  465. return self.generic(
  466. "TRACE",
  467. path,
  468. secure=secure,
  469. headers=headers,
  470. query_params=query_params,
  471. **extra,
  472. )
  473. def options(
  474. self,
  475. path,
  476. data="",
  477. content_type="application/octet-stream",
  478. secure=False,
  479. *,
  480. headers=None,
  481. query_params=None,
  482. **extra,
  483. ):
  484. "Construct an OPTIONS request."
  485. return self.generic(
  486. "OPTIONS",
  487. path,
  488. data,
  489. content_type,
  490. secure=secure,
  491. headers=headers,
  492. query_params=query_params,
  493. **extra,
  494. )
  495. def put(
  496. self,
  497. path,
  498. data="",
  499. content_type="application/octet-stream",
  500. secure=False,
  501. *,
  502. headers=None,
  503. query_params=None,
  504. **extra,
  505. ):
  506. """Construct a PUT request."""
  507. data = self._encode_json(data, content_type)
  508. return self.generic(
  509. "PUT",
  510. path,
  511. data,
  512. content_type,
  513. secure=secure,
  514. headers=headers,
  515. query_params=query_params,
  516. **extra,
  517. )
  518. def patch(
  519. self,
  520. path,
  521. data="",
  522. content_type="application/octet-stream",
  523. secure=False,
  524. *,
  525. headers=None,
  526. query_params=None,
  527. **extra,
  528. ):
  529. """Construct a PATCH request."""
  530. data = self._encode_json(data, content_type)
  531. return self.generic(
  532. "PATCH",
  533. path,
  534. data,
  535. content_type,
  536. secure=secure,
  537. headers=headers,
  538. query_params=query_params,
  539. **extra,
  540. )
  541. def delete(
  542. self,
  543. path,
  544. data="",
  545. content_type="application/octet-stream",
  546. secure=False,
  547. *,
  548. headers=None,
  549. query_params=None,
  550. **extra,
  551. ):
  552. """Construct a DELETE request."""
  553. data = self._encode_json(data, content_type)
  554. return self.generic(
  555. "DELETE",
  556. path,
  557. data,
  558. content_type,
  559. secure=secure,
  560. headers=headers,
  561. query_params=query_params,
  562. **extra,
  563. )
  564. def generic(
  565. self,
  566. method,
  567. path,
  568. data="",
  569. content_type="application/octet-stream",
  570. secure=False,
  571. *,
  572. headers=None,
  573. query_params=None,
  574. **extra,
  575. ):
  576. """Construct an arbitrary HTTP request."""
  577. parsed = urlparse(str(path)) # path can be lazy
  578. data = force_bytes(data, settings.DEFAULT_CHARSET)
  579. r = {
  580. "PATH_INFO": self._get_path(parsed),
  581. "REQUEST_METHOD": method,
  582. "SERVER_PORT": "443" if secure else "80",
  583. "wsgi.url_scheme": "https" if secure else "http",
  584. }
  585. if data:
  586. r.update(
  587. {
  588. "CONTENT_LENGTH": str(len(data)),
  589. "CONTENT_TYPE": content_type,
  590. "wsgi.input": FakePayload(data),
  591. }
  592. )
  593. if headers:
  594. extra.update(HttpHeaders.to_wsgi_names(headers))
  595. if query_params:
  596. extra["QUERY_STRING"] = urlencode(query_params, doseq=True)
  597. r.update(extra)
  598. # If QUERY_STRING is absent or empty, we want to extract it from the URL.
  599. if not r.get("QUERY_STRING"):
  600. # WSGI requires latin-1 encoded strings. See get_path_info().
  601. query_string = parsed[4].encode().decode("iso-8859-1")
  602. r["QUERY_STRING"] = query_string
  603. return self.request(**r)
  604. class AsyncRequestFactory(RequestFactory):
  605. """
  606. Class that lets you create mock ASGI-like Request objects for use in
  607. testing. Usage:
  608. rf = AsyncRequestFactory()
  609. get_request = rf.get("/hello/")
  610. post_request = rf.post("/submit/", {"foo": "bar"})
  611. Once you have a request object you can pass it to any view function,
  612. including synchronous ones. The reason we have a separate class here is:
  613. a) this makes ASGIRequest subclasses, and
  614. b) AsyncClient can subclass it.
  615. """
  616. def _base_scope(self, **request):
  617. """The base scope for a request."""
  618. # This is a minimal valid ASGI scope, plus:
  619. # - headers['cookie'] for cookie support,
  620. # - 'client' often useful, see #8551.
  621. scope = {
  622. "asgi": {"version": "3.0"},
  623. "type": "http",
  624. "http_version": "1.1",
  625. "client": ["127.0.0.1", 0],
  626. "server": ("testserver", "80"),
  627. "scheme": "http",
  628. "method": "GET",
  629. "headers": [],
  630. **self.defaults,
  631. **request,
  632. }
  633. scope["headers"].append(
  634. (
  635. b"cookie",
  636. b"; ".join(
  637. sorted(
  638. ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii")
  639. for morsel in self.cookies.values()
  640. )
  641. ),
  642. )
  643. )
  644. return scope
  645. def request(self, **request):
  646. """Construct a generic request object."""
  647. # This is synchronous, which means all methods on this class are.
  648. # AsyncClient, however, has an async request function, which makes all
  649. # its methods async.
  650. if "_body_file" in request:
  651. body_file = request.pop("_body_file")
  652. else:
  653. body_file = FakePayload("")
  654. # Wrap FakePayload body_file to allow large read() in test environment.
  655. return ASGIRequest(
  656. self._base_scope(**request), LimitedStream(body_file, len(body_file))
  657. )
  658. def generic(
  659. self,
  660. method,
  661. path,
  662. data="",
  663. content_type="application/octet-stream",
  664. secure=False,
  665. *,
  666. headers=None,
  667. query_params=None,
  668. **extra,
  669. ):
  670. """Construct an arbitrary HTTP request."""
  671. parsed = urlparse(str(path)) # path can be lazy.
  672. data = force_bytes(data, settings.DEFAULT_CHARSET)
  673. s = {
  674. "method": method,
  675. "path": self._get_path(parsed),
  676. "server": ("127.0.0.1", "443" if secure else "80"),
  677. "scheme": "https" if secure else "http",
  678. "headers": [(b"host", b"testserver")],
  679. }
  680. if data:
  681. s["headers"].extend(
  682. [
  683. (b"content-length", str(len(data)).encode("ascii")),
  684. (b"content-type", content_type.encode("ascii")),
  685. ]
  686. )
  687. s["_body_file"] = FakePayload(data)
  688. if query_params:
  689. s["query_string"] = urlencode(query_params, doseq=True)
  690. elif query_string := extra.pop("QUERY_STRING", None):
  691. s["query_string"] = query_string
  692. else:
  693. # If QUERY_STRING is absent or empty, we want to extract it from
  694. # the URL.
  695. s["query_string"] = parsed[4]
  696. if headers:
  697. extra.update(HttpHeaders.to_asgi_names(headers))
  698. s["headers"] += [
  699. (key.lower().encode("ascii"), value.encode("latin1"))
  700. for key, value in extra.items()
  701. ]
  702. return self.request(**s)
  703. class ClientMixin:
  704. """
  705. Mixin with common methods between Client and AsyncClient.
  706. """
  707. def store_exc_info(self, **kwargs):
  708. """Store exceptions when they are generated by a view."""
  709. self.exc_info = sys.exc_info()
  710. def check_exception(self, response):
  711. """
  712. Look for a signaled exception, clear the current context exception
  713. data, re-raise the signaled exception, and clear the signaled exception
  714. from the local cache.
  715. """
  716. response.exc_info = self.exc_info
  717. if self.exc_info:
  718. _, exc_value, _ = self.exc_info
  719. self.exc_info = None
  720. if self.raise_request_exception:
  721. raise exc_value
  722. @property
  723. def session(self):
  724. """Return the current session variables."""
  725. engine = import_module(settings.SESSION_ENGINE)
  726. cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
  727. if cookie:
  728. return engine.SessionStore(cookie.value)
  729. session = engine.SessionStore()
  730. session.save()
  731. self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
  732. return session
  733. async def asession(self):
  734. engine = import_module(settings.SESSION_ENGINE)
  735. cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
  736. if cookie:
  737. return engine.SessionStore(cookie.value)
  738. session = engine.SessionStore()
  739. await session.asave()
  740. self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
  741. return session
  742. def login(self, **credentials):
  743. """
  744. Set the Factory to appear as if it has successfully logged into a site.
  745. Return True if login is possible or False if the provided credentials
  746. are incorrect.
  747. """
  748. from django.contrib.auth import authenticate
  749. user = authenticate(**credentials)
  750. if user:
  751. self._login(user)
  752. return True
  753. return False
  754. async def alogin(self, **credentials):
  755. """See login()."""
  756. from django.contrib.auth import aauthenticate
  757. user = await aauthenticate(**credentials)
  758. if user:
  759. await self._alogin(user)
  760. return True
  761. return False
  762. def force_login(self, user, backend=None):
  763. if backend is None:
  764. backend = self._get_backend()
  765. user.backend = backend
  766. self._login(user, backend)
  767. async def aforce_login(self, user, backend=None):
  768. if backend is None:
  769. backend = self._get_backend()
  770. user.backend = backend
  771. await self._alogin(user, backend)
  772. def _get_backend(self):
  773. from django.contrib.auth import load_backend
  774. for backend_path in settings.AUTHENTICATION_BACKENDS:
  775. backend = load_backend(backend_path)
  776. if hasattr(backend, "get_user"):
  777. return backend_path
  778. def _login(self, user, backend=None):
  779. from django.contrib.auth import login
  780. # Create a fake request to store login details.
  781. request = HttpRequest()
  782. if self.session:
  783. request.session = self.session
  784. else:
  785. engine = import_module(settings.SESSION_ENGINE)
  786. request.session = engine.SessionStore()
  787. login(request, user, backend)
  788. # Save the session values.
  789. request.session.save()
  790. self._set_login_cookies(request)
  791. async def _alogin(self, user, backend=None):
  792. from django.contrib.auth import alogin
  793. # Create a fake request to store login details.
  794. request = HttpRequest()
  795. session = await self.asession()
  796. if session:
  797. request.session = session
  798. else:
  799. engine = import_module(settings.SESSION_ENGINE)
  800. request.session = engine.SessionStore()
  801. await alogin(request, user, backend)
  802. # Save the session values.
  803. await request.session.asave()
  804. self._set_login_cookies(request)
  805. def _set_login_cookies(self, request):
  806. # Set the cookie to represent the session.
  807. session_cookie = settings.SESSION_COOKIE_NAME
  808. self.cookies[session_cookie] = request.session.session_key
  809. cookie_data = {
  810. "max-age": None,
  811. "path": "/",
  812. "domain": settings.SESSION_COOKIE_DOMAIN,
  813. "secure": settings.SESSION_COOKIE_SECURE or None,
  814. "expires": None,
  815. }
  816. self.cookies[session_cookie].update(cookie_data)
  817. def logout(self):
  818. """Log out the user by removing the cookies and session object."""
  819. from django.contrib.auth import get_user, logout
  820. request = HttpRequest()
  821. if self.session:
  822. request.session = self.session
  823. request.user = get_user(request)
  824. else:
  825. engine = import_module(settings.SESSION_ENGINE)
  826. request.session = engine.SessionStore()
  827. logout(request)
  828. self.cookies = SimpleCookie()
  829. async def alogout(self):
  830. """See logout()."""
  831. from django.contrib.auth import aget_user, alogout
  832. request = HttpRequest()
  833. session = await self.asession()
  834. if session:
  835. request.session = session
  836. request.user = await aget_user(request)
  837. else:
  838. engine = import_module(settings.SESSION_ENGINE)
  839. request.session = engine.SessionStore()
  840. await alogout(request)
  841. self.cookies = SimpleCookie()
  842. def _parse_json(self, response, **extra):
  843. if not hasattr(response, "_json"):
  844. if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")):
  845. raise ValueError(
  846. 'Content-Type header is "%s", not "application/json"'
  847. % response.get("Content-Type")
  848. )
  849. response._json = json.loads(
  850. response.content.decode(response.charset), **extra
  851. )
  852. return response._json
  853. def _follow_redirect(
  854. self,
  855. response,
  856. *,
  857. data="",
  858. content_type="",
  859. headers=None,
  860. query_params=None,
  861. **extra,
  862. ):
  863. """Follow a single redirect contained in response using GET."""
  864. response_url = response.url
  865. redirect_chain = response.redirect_chain
  866. redirect_chain.append((response_url, response.status_code))
  867. url = urlsplit(response_url)
  868. if url.scheme:
  869. extra["wsgi.url_scheme"] = url.scheme
  870. if url.hostname:
  871. extra["SERVER_NAME"] = url.hostname
  872. extra["HTTP_HOST"] = url.hostname
  873. if url.port:
  874. extra["SERVER_PORT"] = str(url.port)
  875. path = url.path
  876. # RFC 3986 Section 6.2.3: Empty path should be normalized to "/".
  877. if not path and url.netloc:
  878. path = "/"
  879. # Prepend the request path to handle relative path redirects
  880. if not path.startswith("/"):
  881. path = urljoin(response.request["PATH_INFO"], path)
  882. if response.status_code in (
  883. HTTPStatus.TEMPORARY_REDIRECT,
  884. HTTPStatus.PERMANENT_REDIRECT,
  885. ):
  886. # Preserve request method and query string (if needed)
  887. # post-redirect for 307/308 responses.
  888. request_method = response.request["REQUEST_METHOD"].lower()
  889. if request_method not in ("get", "head"):
  890. extra["QUERY_STRING"] = url.query
  891. request_method = getattr(self, request_method)
  892. else:
  893. request_method = self.get
  894. data = QueryDict(url.query)
  895. content_type = None
  896. return request_method(
  897. path,
  898. data=data,
  899. content_type=content_type,
  900. follow=False,
  901. headers=headers,
  902. query_params=query_params,
  903. **extra,
  904. )
  905. def _ensure_redirects_not_cyclic(self, response):
  906. """
  907. Raise a RedirectCycleError if response contains too many redirects.
  908. """
  909. redirect_chain = response.redirect_chain
  910. if redirect_chain[-1] in redirect_chain[:-1]:
  911. # Check that we're not redirecting to somewhere we've already been
  912. # to, to prevent loops.
  913. raise RedirectCycleError("Redirect loop detected.", last_response=response)
  914. if len(redirect_chain) > 20:
  915. # Such a lengthy chain likely also means a loop, but one with a
  916. # growing path, changing view, or changing query argument. 20 is
  917. # the value of "network.http.redirection-limit" from Firefox.
  918. raise RedirectCycleError("Too many redirects.", last_response=response)
  919. class Client(ClientMixin, RequestFactory):
  920. """
  921. A class that can act as a client for testing purposes.
  922. It allows the user to compose GET and POST requests, and
  923. obtain the response that the server gave to those requests.
  924. The server Response objects are annotated with the details
  925. of the contexts and templates that were rendered during the
  926. process of serving the request.
  927. Client objects are stateful - they will retain cookie (and
  928. thus session) details for the lifetime of the Client instance.
  929. This is not intended as a replacement for Twill/Selenium or
  930. the like - it is here to allow testing against the
  931. contexts and templates produced by a view, rather than the
  932. HTML rendered to the end-user.
  933. """
  934. def __init__(
  935. self,
  936. enforce_csrf_checks=False,
  937. raise_request_exception=True,
  938. *,
  939. headers=None,
  940. query_params=None,
  941. **defaults,
  942. ):
  943. super().__init__(headers=headers, query_params=query_params, **defaults)
  944. self.handler = ClientHandler(enforce_csrf_checks)
  945. self.raise_request_exception = raise_request_exception
  946. self.exc_info = None
  947. self.extra = None
  948. self.headers = None
  949. def request(self, **request):
  950. """
  951. Make a generic request. Compose the environment dictionary and pass
  952. to the handler, return the result of the handler. Assume defaults for
  953. the query environment, which can be overridden using the arguments to
  954. the request.
  955. """
  956. environ = self._base_environ(**request)
  957. # Curry a data dictionary into an instance of the template renderer
  958. # callback function.
  959. data = {}
  960. on_template_render = partial(store_rendered_templates, data)
  961. signal_uid = "template-render-%s" % id(request)
  962. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  963. # Capture exceptions created by the handler.
  964. exception_uid = "request-exception-%s" % id(request)
  965. got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
  966. try:
  967. response = self.handler(environ)
  968. finally:
  969. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  970. got_request_exception.disconnect(dispatch_uid=exception_uid)
  971. # Check for signaled exceptions.
  972. self.check_exception(response)
  973. # Save the client and request that stimulated the response.
  974. response.client = self
  975. response.request = request
  976. # Add any rendered template detail to the response.
  977. response.templates = data.get("templates", [])
  978. response.context = data.get("context")
  979. response.json = partial(self._parse_json, response)
  980. # Attach the ResolverMatch instance to the response.
  981. urlconf = getattr(response.wsgi_request, "urlconf", None)
  982. response.resolver_match = SimpleLazyObject(
  983. lambda: resolve(request["PATH_INFO"], urlconf=urlconf),
  984. )
  985. # Flatten a single context. Not really necessary anymore thanks to the
  986. # __getattr__ flattening in ContextList, but has some edge case
  987. # backwards compatibility implications.
  988. if response.context and len(response.context) == 1:
  989. response.context = response.context[0]
  990. # Update persistent cookie data.
  991. if response.cookies:
  992. self.cookies.update(response.cookies)
  993. return response
  994. def get(
  995. self,
  996. path,
  997. data=None,
  998. follow=False,
  999. secure=False,
  1000. *,
  1001. headers=None,
  1002. query_params=None,
  1003. **extra,
  1004. ):
  1005. """Request a response from the server using GET."""
  1006. self.extra = extra
  1007. self.headers = headers
  1008. response = super().get(
  1009. path,
  1010. data=data,
  1011. secure=secure,
  1012. headers=headers,
  1013. query_params=query_params,
  1014. **extra,
  1015. )
  1016. if follow:
  1017. response = self._handle_redirects(
  1018. response, data=data, headers=headers, query_params=query_params, **extra
  1019. )
  1020. return response
  1021. def post(
  1022. self,
  1023. path,
  1024. data=None,
  1025. content_type=MULTIPART_CONTENT,
  1026. follow=False,
  1027. secure=False,
  1028. *,
  1029. headers=None,
  1030. query_params=None,
  1031. **extra,
  1032. ):
  1033. """Request a response from the server using POST."""
  1034. self.extra = extra
  1035. self.headers = headers
  1036. response = super().post(
  1037. path,
  1038. data=data,
  1039. content_type=content_type,
  1040. secure=secure,
  1041. headers=headers,
  1042. query_params=query_params,
  1043. **extra,
  1044. )
  1045. if follow:
  1046. response = self._handle_redirects(
  1047. response,
  1048. data=data,
  1049. content_type=content_type,
  1050. headers=headers,
  1051. query_params=query_params,
  1052. **extra,
  1053. )
  1054. return response
  1055. def head(
  1056. self,
  1057. path,
  1058. data=None,
  1059. follow=False,
  1060. secure=False,
  1061. *,
  1062. headers=None,
  1063. query_params=None,
  1064. **extra,
  1065. ):
  1066. """Request a response from the server using HEAD."""
  1067. self.extra = extra
  1068. self.headers = headers
  1069. response = super().head(
  1070. path,
  1071. data=data,
  1072. secure=secure,
  1073. headers=headers,
  1074. query_params=query_params,
  1075. **extra,
  1076. )
  1077. if follow:
  1078. response = self._handle_redirects(
  1079. response, data=data, headers=headers, query_params=query_params, **extra
  1080. )
  1081. return response
  1082. def options(
  1083. self,
  1084. path,
  1085. data="",
  1086. content_type="application/octet-stream",
  1087. follow=False,
  1088. secure=False,
  1089. *,
  1090. headers=None,
  1091. query_params=None,
  1092. **extra,
  1093. ):
  1094. """Request a response from the server using OPTIONS."""
  1095. self.extra = extra
  1096. self.headers = headers
  1097. response = super().options(
  1098. path,
  1099. data=data,
  1100. content_type=content_type,
  1101. secure=secure,
  1102. headers=headers,
  1103. query_params=query_params,
  1104. **extra,
  1105. )
  1106. if follow:
  1107. response = self._handle_redirects(
  1108. response,
  1109. data=data,
  1110. content_type=content_type,
  1111. headers=headers,
  1112. query_params=query_params,
  1113. **extra,
  1114. )
  1115. return response
  1116. def put(
  1117. self,
  1118. path,
  1119. data="",
  1120. content_type="application/octet-stream",
  1121. follow=False,
  1122. secure=False,
  1123. *,
  1124. headers=None,
  1125. query_params=None,
  1126. **extra,
  1127. ):
  1128. """Send a resource to the server using PUT."""
  1129. self.extra = extra
  1130. self.headers = headers
  1131. response = super().put(
  1132. path,
  1133. data=data,
  1134. content_type=content_type,
  1135. secure=secure,
  1136. headers=headers,
  1137. query_params=query_params,
  1138. **extra,
  1139. )
  1140. if follow:
  1141. response = self._handle_redirects(
  1142. response,
  1143. data=data,
  1144. content_type=content_type,
  1145. headers=headers,
  1146. query_params=query_params,
  1147. **extra,
  1148. )
  1149. return response
  1150. def patch(
  1151. self,
  1152. path,
  1153. data="",
  1154. content_type="application/octet-stream",
  1155. follow=False,
  1156. secure=False,
  1157. *,
  1158. headers=None,
  1159. query_params=None,
  1160. **extra,
  1161. ):
  1162. """Send a resource to the server using PATCH."""
  1163. self.extra = extra
  1164. self.headers = headers
  1165. response = super().patch(
  1166. path,
  1167. data=data,
  1168. content_type=content_type,
  1169. secure=secure,
  1170. headers=headers,
  1171. query_params=query_params,
  1172. **extra,
  1173. )
  1174. if follow:
  1175. response = self._handle_redirects(
  1176. response,
  1177. data=data,
  1178. content_type=content_type,
  1179. headers=headers,
  1180. query_params=query_params,
  1181. **extra,
  1182. )
  1183. return response
  1184. def delete(
  1185. self,
  1186. path,
  1187. data="",
  1188. content_type="application/octet-stream",
  1189. follow=False,
  1190. secure=False,
  1191. *,
  1192. headers=None,
  1193. query_params=None,
  1194. **extra,
  1195. ):
  1196. """Send a DELETE request to the server."""
  1197. self.extra = extra
  1198. self.headers = headers
  1199. response = super().delete(
  1200. path,
  1201. data=data,
  1202. content_type=content_type,
  1203. secure=secure,
  1204. headers=headers,
  1205. query_params=query_params,
  1206. **extra,
  1207. )
  1208. if follow:
  1209. response = self._handle_redirects(
  1210. response,
  1211. data=data,
  1212. content_type=content_type,
  1213. headers=headers,
  1214. query_params=query_params,
  1215. **extra,
  1216. )
  1217. return response
  1218. def trace(
  1219. self,
  1220. path,
  1221. data="",
  1222. follow=False,
  1223. secure=False,
  1224. *,
  1225. headers=None,
  1226. query_params=None,
  1227. **extra,
  1228. ):
  1229. """Send a TRACE request to the server."""
  1230. self.extra = extra
  1231. self.headers = headers
  1232. response = super().trace(
  1233. path,
  1234. data=data,
  1235. secure=secure,
  1236. headers=headers,
  1237. query_params=query_params,
  1238. **extra,
  1239. )
  1240. if follow:
  1241. response = self._handle_redirects(
  1242. response, data=data, headers=headers, query_params=query_params, **extra
  1243. )
  1244. return response
  1245. def _handle_redirects(
  1246. self,
  1247. response,
  1248. data="",
  1249. content_type="",
  1250. headers=None,
  1251. query_params=None,
  1252. **extra,
  1253. ):
  1254. """
  1255. Follow any redirects by requesting responses from the server using GET.
  1256. """
  1257. response.redirect_chain = []
  1258. while response.status_code in REDIRECT_STATUS_CODES:
  1259. redirect_chain = response.redirect_chain
  1260. response = self._follow_redirect(
  1261. response,
  1262. data=data,
  1263. content_type=content_type,
  1264. headers=headers,
  1265. query_params=query_params,
  1266. **extra,
  1267. )
  1268. response.redirect_chain = redirect_chain
  1269. self._ensure_redirects_not_cyclic(response)
  1270. return response
  1271. class AsyncClient(ClientMixin, AsyncRequestFactory):
  1272. """
  1273. An async version of Client that creates ASGIRequests and calls through an
  1274. async request path.
  1275. Does not currently support "follow" on its methods.
  1276. """
  1277. def __init__(
  1278. self,
  1279. enforce_csrf_checks=False,
  1280. raise_request_exception=True,
  1281. *,
  1282. headers=None,
  1283. query_params=None,
  1284. **defaults,
  1285. ):
  1286. super().__init__(headers=headers, query_params=query_params, **defaults)
  1287. self.handler = AsyncClientHandler(enforce_csrf_checks)
  1288. self.raise_request_exception = raise_request_exception
  1289. self.exc_info = None
  1290. self.extra = None
  1291. self.headers = None
  1292. async def request(self, **request):
  1293. """
  1294. Make a generic request. Compose the scope dictionary and pass to the
  1295. handler, return the result of the handler. Assume defaults for the
  1296. query environment, which can be overridden using the arguments to the
  1297. request.
  1298. """
  1299. scope = self._base_scope(**request)
  1300. # Curry a data dictionary into an instance of the template renderer
  1301. # callback function.
  1302. data = {}
  1303. on_template_render = partial(store_rendered_templates, data)
  1304. signal_uid = "template-render-%s" % id(request)
  1305. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  1306. # Capture exceptions created by the handler.
  1307. exception_uid = "request-exception-%s" % id(request)
  1308. got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
  1309. try:
  1310. response = await self.handler(scope)
  1311. finally:
  1312. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  1313. got_request_exception.disconnect(dispatch_uid=exception_uid)
  1314. # Check for signaled exceptions.
  1315. self.check_exception(response)
  1316. # Save the client and request that stimulated the response.
  1317. response.client = self
  1318. response.request = request
  1319. # Add any rendered template detail to the response.
  1320. response.templates = data.get("templates", [])
  1321. response.context = data.get("context")
  1322. response.json = partial(self._parse_json, response)
  1323. # Attach the ResolverMatch instance to the response.
  1324. urlconf = getattr(response.asgi_request, "urlconf", None)
  1325. response.resolver_match = SimpleLazyObject(
  1326. lambda: resolve(request["path"], urlconf=urlconf),
  1327. )
  1328. # Flatten a single context. Not really necessary anymore thanks to the
  1329. # __getattr__ flattening in ContextList, but has some edge case
  1330. # backwards compatibility implications.
  1331. if response.context and len(response.context) == 1:
  1332. response.context = response.context[0]
  1333. # Update persistent cookie data.
  1334. if response.cookies:
  1335. self.cookies.update(response.cookies)
  1336. return response
  1337. async def get(
  1338. self,
  1339. path,
  1340. data=None,
  1341. follow=False,
  1342. secure=False,
  1343. *,
  1344. headers=None,
  1345. query_params=None,
  1346. **extra,
  1347. ):
  1348. """Request a response from the server using GET."""
  1349. self.extra = extra
  1350. self.headers = headers
  1351. response = await super().get(
  1352. path,
  1353. data=data,
  1354. secure=secure,
  1355. headers=headers,
  1356. query_params=query_params,
  1357. **extra,
  1358. )
  1359. if follow:
  1360. response = await self._ahandle_redirects(
  1361. response, data=data, headers=headers, query_params=query_params, **extra
  1362. )
  1363. return response
  1364. async def post(
  1365. self,
  1366. path,
  1367. data=None,
  1368. content_type=MULTIPART_CONTENT,
  1369. follow=False,
  1370. secure=False,
  1371. *,
  1372. headers=None,
  1373. query_params=None,
  1374. **extra,
  1375. ):
  1376. """Request a response from the server using POST."""
  1377. self.extra = extra
  1378. self.headers = headers
  1379. response = await super().post(
  1380. path,
  1381. data=data,
  1382. content_type=content_type,
  1383. secure=secure,
  1384. headers=headers,
  1385. query_params=query_params,
  1386. **extra,
  1387. )
  1388. if follow:
  1389. response = await self._ahandle_redirects(
  1390. response,
  1391. data=data,
  1392. content_type=content_type,
  1393. headers=headers,
  1394. query_params=query_params,
  1395. **extra,
  1396. )
  1397. return response
  1398. async def head(
  1399. self,
  1400. path,
  1401. data=None,
  1402. follow=False,
  1403. secure=False,
  1404. *,
  1405. headers=None,
  1406. query_params=None,
  1407. **extra,
  1408. ):
  1409. """Request a response from the server using HEAD."""
  1410. self.extra = extra
  1411. self.headers = headers
  1412. response = await super().head(
  1413. path,
  1414. data=data,
  1415. secure=secure,
  1416. headers=headers,
  1417. query_params=query_params,
  1418. **extra,
  1419. )
  1420. if follow:
  1421. response = await self._ahandle_redirects(
  1422. response, data=data, headers=headers, query_params=query_params, **extra
  1423. )
  1424. return response
  1425. async def options(
  1426. self,
  1427. path,
  1428. data="",
  1429. content_type="application/octet-stream",
  1430. follow=False,
  1431. secure=False,
  1432. *,
  1433. headers=None,
  1434. query_params=None,
  1435. **extra,
  1436. ):
  1437. """Request a response from the server using OPTIONS."""
  1438. self.extra = extra
  1439. self.headers = headers
  1440. response = await super().options(
  1441. path,
  1442. data=data,
  1443. content_type=content_type,
  1444. secure=secure,
  1445. headers=headers,
  1446. query_params=query_params,
  1447. **extra,
  1448. )
  1449. if follow:
  1450. response = await self._ahandle_redirects(
  1451. response,
  1452. data=data,
  1453. content_type=content_type,
  1454. headers=headers,
  1455. query_params=query_params,
  1456. **extra,
  1457. )
  1458. return response
  1459. async def put(
  1460. self,
  1461. path,
  1462. data="",
  1463. content_type="application/octet-stream",
  1464. follow=False,
  1465. secure=False,
  1466. *,
  1467. headers=None,
  1468. query_params=None,
  1469. **extra,
  1470. ):
  1471. """Send a resource to the server using PUT."""
  1472. self.extra = extra
  1473. self.headers = headers
  1474. response = await super().put(
  1475. path,
  1476. data=data,
  1477. content_type=content_type,
  1478. secure=secure,
  1479. headers=headers,
  1480. query_params=query_params,
  1481. **extra,
  1482. )
  1483. if follow:
  1484. response = await self._ahandle_redirects(
  1485. response,
  1486. data=data,
  1487. content_type=content_type,
  1488. headers=headers,
  1489. query_params=query_params,
  1490. **extra,
  1491. )
  1492. return response
  1493. async def patch(
  1494. self,
  1495. path,
  1496. data="",
  1497. content_type="application/octet-stream",
  1498. follow=False,
  1499. secure=False,
  1500. *,
  1501. headers=None,
  1502. query_params=None,
  1503. **extra,
  1504. ):
  1505. """Send a resource to the server using PATCH."""
  1506. self.extra = extra
  1507. self.headers = headers
  1508. response = await super().patch(
  1509. path,
  1510. data=data,
  1511. content_type=content_type,
  1512. secure=secure,
  1513. headers=headers,
  1514. query_params=query_params,
  1515. **extra,
  1516. )
  1517. if follow:
  1518. response = await self._ahandle_redirects(
  1519. response,
  1520. data=data,
  1521. content_type=content_type,
  1522. headers=headers,
  1523. query_params=query_params,
  1524. **extra,
  1525. )
  1526. return response
  1527. async def delete(
  1528. self,
  1529. path,
  1530. data="",
  1531. content_type="application/octet-stream",
  1532. follow=False,
  1533. secure=False,
  1534. *,
  1535. headers=None,
  1536. query_params=None,
  1537. **extra,
  1538. ):
  1539. """Send a DELETE request to the server."""
  1540. self.extra = extra
  1541. self.headers = headers
  1542. response = await super().delete(
  1543. path,
  1544. data=data,
  1545. content_type=content_type,
  1546. secure=secure,
  1547. headers=headers,
  1548. query_params=query_params,
  1549. **extra,
  1550. )
  1551. if follow:
  1552. response = await self._ahandle_redirects(
  1553. response,
  1554. data=data,
  1555. content_type=content_type,
  1556. headers=headers,
  1557. query_params=query_params,
  1558. **extra,
  1559. )
  1560. return response
  1561. async def trace(
  1562. self,
  1563. path,
  1564. data="",
  1565. follow=False,
  1566. secure=False,
  1567. *,
  1568. headers=None,
  1569. query_params=None,
  1570. **extra,
  1571. ):
  1572. """Send a TRACE request to the server."""
  1573. self.extra = extra
  1574. self.headers = headers
  1575. response = await super().trace(
  1576. path,
  1577. data=data,
  1578. secure=secure,
  1579. headers=headers,
  1580. query_params=query_params,
  1581. **extra,
  1582. )
  1583. if follow:
  1584. response = await self._ahandle_redirects(
  1585. response, data=data, headers=headers, query_params=query_params, **extra
  1586. )
  1587. return response
  1588. async def _ahandle_redirects(
  1589. self,
  1590. response,
  1591. data="",
  1592. content_type="",
  1593. headers=None,
  1594. query_params=None,
  1595. **extra,
  1596. ):
  1597. """
  1598. Follow any redirects by requesting responses from the server using GET.
  1599. """
  1600. response.redirect_chain = []
  1601. while response.status_code in REDIRECT_STATUS_CODES:
  1602. redirect_chain = response.redirect_chain
  1603. response = await self._follow_redirect(
  1604. response,
  1605. data=data,
  1606. content_type=content_type,
  1607. headers=headers,
  1608. query_params=query_params,
  1609. **extra,
  1610. )
  1611. response.redirect_chain = redirect_chain
  1612. self._ensure_redirects_not_cyclic(response)
  1613. return response