client.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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, IOBase
  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 LimitedStream, 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 HttpHeaders, 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. 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 is_iterable(value):
  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__(self, *, json_encoder=DjangoJSONEncoder, headers=None, **defaults):
  327. self.json_encoder = json_encoder
  328. self.defaults = defaults
  329. self.cookies = SimpleCookie()
  330. self.errors = BytesIO()
  331. if headers:
  332. self.defaults.update(HttpHeaders.to_wsgi_names(headers))
  333. def _base_environ(self, **request):
  334. """
  335. The base environment for a request.
  336. """
  337. # This is a minimal valid WSGI environ dictionary, plus:
  338. # - HTTP_COOKIE: for cookie support,
  339. # - REMOTE_ADDR: often useful, see #8551.
  340. # See https://www.python.org/dev/peps/pep-3333/#environ-variables
  341. return {
  342. "HTTP_COOKIE": "; ".join(
  343. sorted(
  344. "%s=%s" % (morsel.key, morsel.coded_value)
  345. for morsel in self.cookies.values()
  346. )
  347. ),
  348. "PATH_INFO": "/",
  349. "REMOTE_ADDR": "127.0.0.1",
  350. "REQUEST_METHOD": "GET",
  351. "SCRIPT_NAME": "",
  352. "SERVER_NAME": "testserver",
  353. "SERVER_PORT": "80",
  354. "SERVER_PROTOCOL": "HTTP/1.1",
  355. "wsgi.version": (1, 0),
  356. "wsgi.url_scheme": "http",
  357. "wsgi.input": FakePayload(b""),
  358. "wsgi.errors": self.errors,
  359. "wsgi.multiprocess": True,
  360. "wsgi.multithread": False,
  361. "wsgi.run_once": False,
  362. **self.defaults,
  363. **request,
  364. }
  365. def request(self, **request):
  366. "Construct a generic request object."
  367. return WSGIRequest(self._base_environ(**request))
  368. def _encode_data(self, data, content_type):
  369. if content_type is MULTIPART_CONTENT:
  370. return encode_multipart(BOUNDARY, data)
  371. else:
  372. # Encode the content so that the byte representation is correct.
  373. match = CONTENT_TYPE_RE.match(content_type)
  374. if match:
  375. charset = match[1]
  376. else:
  377. charset = settings.DEFAULT_CHARSET
  378. return force_bytes(data, encoding=charset)
  379. def _encode_json(self, data, content_type):
  380. """
  381. Return encoded JSON if data is a dict, list, or tuple and content_type
  382. is application/json.
  383. """
  384. should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(
  385. data, (dict, list, tuple)
  386. )
  387. return json.dumps(data, cls=self.json_encoder) if should_encode else data
  388. def _get_path(self, parsed):
  389. path = parsed.path
  390. # If there are parameters, add them
  391. if parsed.params:
  392. path += ";" + parsed.params
  393. path = unquote_to_bytes(path)
  394. # Replace the behavior where non-ASCII values in the WSGI environ are
  395. # arbitrarily decoded with ISO-8859-1.
  396. # Refs comment in `get_bytes_from_wsgi()`.
  397. return path.decode("iso-8859-1")
  398. def get(self, path, data=None, secure=False, *, headers=None, **extra):
  399. """Construct a GET request."""
  400. data = {} if data is None else data
  401. return self.generic(
  402. "GET",
  403. path,
  404. secure=secure,
  405. headers=headers,
  406. **{
  407. "QUERY_STRING": urlencode(data, doseq=True),
  408. **extra,
  409. },
  410. )
  411. def post(
  412. self,
  413. path,
  414. data=None,
  415. content_type=MULTIPART_CONTENT,
  416. secure=False,
  417. *,
  418. headers=None,
  419. **extra,
  420. ):
  421. """Construct a POST request."""
  422. data = self._encode_json({} if data is None else data, content_type)
  423. post_data = self._encode_data(data, content_type)
  424. return self.generic(
  425. "POST",
  426. path,
  427. post_data,
  428. content_type,
  429. secure=secure,
  430. headers=headers,
  431. **extra,
  432. )
  433. def head(self, path, data=None, secure=False, *, headers=None, **extra):
  434. """Construct a HEAD request."""
  435. data = {} if data is None else data
  436. return self.generic(
  437. "HEAD",
  438. path,
  439. secure=secure,
  440. headers=headers,
  441. **{
  442. "QUERY_STRING": urlencode(data, doseq=True),
  443. **extra,
  444. },
  445. )
  446. def trace(self, path, secure=False, *, headers=None, **extra):
  447. """Construct a TRACE request."""
  448. return self.generic("TRACE", path, secure=secure, headers=headers, **extra)
  449. def options(
  450. self,
  451. path,
  452. data="",
  453. content_type="application/octet-stream",
  454. secure=False,
  455. *,
  456. headers=None,
  457. **extra,
  458. ):
  459. "Construct an OPTIONS request."
  460. return self.generic(
  461. "OPTIONS", path, data, content_type, secure=secure, headers=headers, **extra
  462. )
  463. def put(
  464. self,
  465. path,
  466. data="",
  467. content_type="application/octet-stream",
  468. secure=False,
  469. *,
  470. headers=None,
  471. **extra,
  472. ):
  473. """Construct a PUT request."""
  474. data = self._encode_json(data, content_type)
  475. return self.generic(
  476. "PUT", path, data, content_type, secure=secure, headers=headers, **extra
  477. )
  478. def patch(
  479. self,
  480. path,
  481. data="",
  482. content_type="application/octet-stream",
  483. secure=False,
  484. *,
  485. headers=None,
  486. **extra,
  487. ):
  488. """Construct a PATCH request."""
  489. data = self._encode_json(data, content_type)
  490. return self.generic(
  491. "PATCH", path, data, content_type, secure=secure, headers=headers, **extra
  492. )
  493. def delete(
  494. self,
  495. path,
  496. data="",
  497. content_type="application/octet-stream",
  498. secure=False,
  499. *,
  500. headers=None,
  501. **extra,
  502. ):
  503. """Construct a DELETE request."""
  504. data = self._encode_json(data, content_type)
  505. return self.generic(
  506. "DELETE", path, data, content_type, secure=secure, headers=headers, **extra
  507. )
  508. def generic(
  509. self,
  510. method,
  511. path,
  512. data="",
  513. content_type="application/octet-stream",
  514. secure=False,
  515. *,
  516. headers=None,
  517. **extra,
  518. ):
  519. """Construct an arbitrary HTTP request."""
  520. parsed = urlparse(str(path)) # path can be lazy
  521. data = force_bytes(data, settings.DEFAULT_CHARSET)
  522. r = {
  523. "PATH_INFO": self._get_path(parsed),
  524. "REQUEST_METHOD": method,
  525. "SERVER_PORT": "443" if secure else "80",
  526. "wsgi.url_scheme": "https" if secure else "http",
  527. }
  528. if data:
  529. r.update(
  530. {
  531. "CONTENT_LENGTH": str(len(data)),
  532. "CONTENT_TYPE": content_type,
  533. "wsgi.input": FakePayload(data),
  534. }
  535. )
  536. if headers:
  537. extra.update(HttpHeaders.to_wsgi_names(headers))
  538. r.update(extra)
  539. # If QUERY_STRING is absent or empty, we want to extract it from the URL.
  540. if not r.get("QUERY_STRING"):
  541. # WSGI requires latin-1 encoded strings. See get_path_info().
  542. query_string = parsed[4].encode().decode("iso-8859-1")
  543. r["QUERY_STRING"] = query_string
  544. return self.request(**r)
  545. class AsyncRequestFactory(RequestFactory):
  546. """
  547. Class that lets you create mock ASGI-like Request objects for use in
  548. testing. Usage:
  549. rf = AsyncRequestFactory()
  550. get_request = rf.get("/hello/")
  551. post_request = rf.post("/submit/", {"foo": "bar"})
  552. Once you have a request object you can pass it to any view function,
  553. including synchronous ones. The reason we have a separate class here is:
  554. a) this makes ASGIRequest subclasses, and
  555. b) AsyncTestClient can subclass it.
  556. """
  557. def _base_scope(self, **request):
  558. """The base scope for a request."""
  559. # This is a minimal valid ASGI scope, plus:
  560. # - headers['cookie'] for cookie support,
  561. # - 'client' often useful, see #8551.
  562. scope = {
  563. "asgi": {"version": "3.0"},
  564. "type": "http",
  565. "http_version": "1.1",
  566. "client": ["127.0.0.1", 0],
  567. "server": ("testserver", "80"),
  568. "scheme": "http",
  569. "method": "GET",
  570. "headers": [],
  571. **self.defaults,
  572. **request,
  573. }
  574. scope["headers"].append(
  575. (
  576. b"cookie",
  577. b"; ".join(
  578. sorted(
  579. ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii")
  580. for morsel in self.cookies.values()
  581. )
  582. ),
  583. )
  584. )
  585. return scope
  586. def request(self, **request):
  587. """Construct a generic request object."""
  588. # This is synchronous, which means all methods on this class are.
  589. # AsyncClient, however, has an async request function, which makes all
  590. # its methods async.
  591. if "_body_file" in request:
  592. body_file = request.pop("_body_file")
  593. else:
  594. body_file = FakePayload("")
  595. # Wrap FakePayload body_file to allow large read() in test environment.
  596. return ASGIRequest(
  597. self._base_scope(**request), LimitedStream(body_file, len(body_file))
  598. )
  599. def generic(
  600. self,
  601. method,
  602. path,
  603. data="",
  604. content_type="application/octet-stream",
  605. secure=False,
  606. *,
  607. headers=None,
  608. **extra,
  609. ):
  610. """Construct an arbitrary HTTP request."""
  611. parsed = urlparse(str(path)) # path can be lazy.
  612. data = force_bytes(data, settings.DEFAULT_CHARSET)
  613. s = {
  614. "method": method,
  615. "path": self._get_path(parsed),
  616. "server": ("127.0.0.1", "443" if secure else "80"),
  617. "scheme": "https" if secure else "http",
  618. "headers": [(b"host", b"testserver")],
  619. }
  620. if data:
  621. s["headers"].extend(
  622. [
  623. (b"content-length", str(len(data)).encode("ascii")),
  624. (b"content-type", content_type.encode("ascii")),
  625. ]
  626. )
  627. s["_body_file"] = FakePayload(data)
  628. if query_string := extra.pop("QUERY_STRING", None):
  629. s["query_string"] = query_string
  630. if headers:
  631. extra.update(HttpHeaders.to_asgi_names(headers))
  632. s["headers"] += [
  633. (key.lower().encode("ascii"), value.encode("latin1"))
  634. for key, value in extra.items()
  635. ]
  636. # If QUERY_STRING is absent or empty, we want to extract it from the
  637. # URL.
  638. if not s.get("query_string"):
  639. s["query_string"] = parsed[4]
  640. return self.request(**s)
  641. class ClientMixin:
  642. """
  643. Mixin with common methods between Client and AsyncClient.
  644. """
  645. def store_exc_info(self, **kwargs):
  646. """Store exceptions when they are generated by a view."""
  647. self.exc_info = sys.exc_info()
  648. def check_exception(self, response):
  649. """
  650. Look for a signaled exception, clear the current context exception
  651. data, re-raise the signaled exception, and clear the signaled exception
  652. from the local cache.
  653. """
  654. response.exc_info = self.exc_info
  655. if self.exc_info:
  656. _, exc_value, _ = self.exc_info
  657. self.exc_info = None
  658. if self.raise_request_exception:
  659. raise exc_value
  660. @property
  661. def session(self):
  662. """Return the current session variables."""
  663. engine = import_module(settings.SESSION_ENGINE)
  664. cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
  665. if cookie:
  666. return engine.SessionStore(cookie.value)
  667. session = engine.SessionStore()
  668. session.save()
  669. self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
  670. return session
  671. async def asession(self):
  672. return await sync_to_async(lambda: self.session)()
  673. def login(self, **credentials):
  674. """
  675. Set the Factory to appear as if it has successfully logged into a site.
  676. Return True if login is possible or False if the provided credentials
  677. are incorrect.
  678. """
  679. from django.contrib.auth import authenticate
  680. user = authenticate(**credentials)
  681. if user:
  682. self._login(user)
  683. return True
  684. return False
  685. async def alogin(self, **credentials):
  686. """See login()."""
  687. from django.contrib.auth import aauthenticate
  688. user = await aauthenticate(**credentials)
  689. if user:
  690. await self._alogin(user)
  691. return True
  692. return False
  693. def force_login(self, user, backend=None):
  694. if backend is None:
  695. backend = self._get_backend()
  696. user.backend = backend
  697. self._login(user, backend)
  698. async def aforce_login(self, user, backend=None):
  699. if backend is None:
  700. backend = self._get_backend()
  701. user.backend = backend
  702. await self._alogin(user, backend)
  703. def _get_backend(self):
  704. from django.contrib.auth import load_backend
  705. for backend_path in settings.AUTHENTICATION_BACKENDS:
  706. backend = load_backend(backend_path)
  707. if hasattr(backend, "get_user"):
  708. return backend_path
  709. def _login(self, user, backend=None):
  710. from django.contrib.auth import login
  711. # Create a fake request to store login details.
  712. request = HttpRequest()
  713. if self.session:
  714. request.session = self.session
  715. else:
  716. engine = import_module(settings.SESSION_ENGINE)
  717. request.session = engine.SessionStore()
  718. login(request, user, backend)
  719. # Save the session values.
  720. request.session.save()
  721. self._set_login_cookies(request)
  722. async def _alogin(self, user, backend=None):
  723. from django.contrib.auth import alogin
  724. # Create a fake request to store login details.
  725. request = HttpRequest()
  726. session = await self.asession()
  727. if session:
  728. request.session = session
  729. else:
  730. engine = import_module(settings.SESSION_ENGINE)
  731. request.session = engine.SessionStore()
  732. await alogin(request, user, backend)
  733. # Save the session values.
  734. await sync_to_async(request.session.save)()
  735. self._set_login_cookies(request)
  736. def _set_login_cookies(self, request):
  737. # Set the cookie to represent the session.
  738. session_cookie = settings.SESSION_COOKIE_NAME
  739. self.cookies[session_cookie] = request.session.session_key
  740. cookie_data = {
  741. "max-age": None,
  742. "path": "/",
  743. "domain": settings.SESSION_COOKIE_DOMAIN,
  744. "secure": settings.SESSION_COOKIE_SECURE or None,
  745. "expires": None,
  746. }
  747. self.cookies[session_cookie].update(cookie_data)
  748. def logout(self):
  749. """Log out the user by removing the cookies and session object."""
  750. from django.contrib.auth import get_user, logout
  751. request = HttpRequest()
  752. if self.session:
  753. request.session = self.session
  754. request.user = get_user(request)
  755. else:
  756. engine = import_module(settings.SESSION_ENGINE)
  757. request.session = engine.SessionStore()
  758. logout(request)
  759. self.cookies = SimpleCookie()
  760. async def alogout(self):
  761. """See logout()."""
  762. from django.contrib.auth import aget_user, alogout
  763. request = HttpRequest()
  764. session = await self.asession()
  765. if session:
  766. request.session = session
  767. request.user = await aget_user(request)
  768. else:
  769. engine = import_module(settings.SESSION_ENGINE)
  770. request.session = engine.SessionStore()
  771. await alogout(request)
  772. self.cookies = SimpleCookie()
  773. def _parse_json(self, response, **extra):
  774. if not hasattr(response, "_json"):
  775. if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")):
  776. raise ValueError(
  777. 'Content-Type header is "%s", not "application/json"'
  778. % response.get("Content-Type")
  779. )
  780. response._json = json.loads(
  781. response.content.decode(response.charset), **extra
  782. )
  783. return response._json
  784. def _follow_redirect(
  785. self, response, *, data="", content_type="", headers=None, **extra
  786. ):
  787. """Follow a single redirect contained in response using GET."""
  788. response_url = response.url
  789. redirect_chain = response.redirect_chain
  790. redirect_chain.append((response_url, response.status_code))
  791. url = urlsplit(response_url)
  792. if url.scheme:
  793. extra["wsgi.url_scheme"] = url.scheme
  794. if url.hostname:
  795. extra["SERVER_NAME"] = url.hostname
  796. if url.port:
  797. extra["SERVER_PORT"] = str(url.port)
  798. path = url.path
  799. # RFC 3986 Section 6.2.3: Empty path should be normalized to "/".
  800. if not path and url.netloc:
  801. path = "/"
  802. # Prepend the request path to handle relative path redirects
  803. if not path.startswith("/"):
  804. path = urljoin(response.request["PATH_INFO"], path)
  805. if response.status_code in (
  806. HTTPStatus.TEMPORARY_REDIRECT,
  807. HTTPStatus.PERMANENT_REDIRECT,
  808. ):
  809. # Preserve request method and query string (if needed)
  810. # post-redirect for 307/308 responses.
  811. request_method = response.request["REQUEST_METHOD"].lower()
  812. if request_method not in ("get", "head"):
  813. extra["QUERY_STRING"] = url.query
  814. request_method = getattr(self, request_method)
  815. else:
  816. request_method = self.get
  817. data = QueryDict(url.query)
  818. content_type = None
  819. return request_method(
  820. path,
  821. data=data,
  822. content_type=content_type,
  823. follow=False,
  824. headers=headers,
  825. **extra,
  826. )
  827. def _ensure_redirects_not_cyclic(self, response):
  828. """
  829. Raise a RedirectCycleError if response contains too many redirects.
  830. """
  831. redirect_chain = response.redirect_chain
  832. if redirect_chain[-1] in redirect_chain[:-1]:
  833. # Check that we're not redirecting to somewhere we've already been
  834. # to, to prevent loops.
  835. raise RedirectCycleError("Redirect loop detected.", last_response=response)
  836. if len(redirect_chain) > 20:
  837. # Such a lengthy chain likely also means a loop, but one with a
  838. # growing path, changing view, or changing query argument. 20 is
  839. # the value of "network.http.redirection-limit" from Firefox.
  840. raise RedirectCycleError("Too many redirects.", last_response=response)
  841. class Client(ClientMixin, RequestFactory):
  842. """
  843. A class that can act as a client for testing purposes.
  844. It allows the user to compose GET and POST requests, and
  845. obtain the response that the server gave to those requests.
  846. The server Response objects are annotated with the details
  847. of the contexts and templates that were rendered during the
  848. process of serving the request.
  849. Client objects are stateful - they will retain cookie (and
  850. thus session) details for the lifetime of the Client instance.
  851. This is not intended as a replacement for Twill/Selenium or
  852. the like - it is here to allow testing against the
  853. contexts and templates produced by a view, rather than the
  854. HTML rendered to the end-user.
  855. """
  856. def __init__(
  857. self,
  858. enforce_csrf_checks=False,
  859. raise_request_exception=True,
  860. *,
  861. headers=None,
  862. **defaults,
  863. ):
  864. super().__init__(headers=headers, **defaults)
  865. self.handler = ClientHandler(enforce_csrf_checks)
  866. self.raise_request_exception = raise_request_exception
  867. self.exc_info = None
  868. self.extra = None
  869. self.headers = None
  870. def request(self, **request):
  871. """
  872. Make a generic request. Compose the environment dictionary and pass
  873. to the handler, return the result of the handler. Assume defaults for
  874. the query environment, which can be overridden using the arguments to
  875. the request.
  876. """
  877. environ = self._base_environ(**request)
  878. # Curry a data dictionary into an instance of the template renderer
  879. # callback function.
  880. data = {}
  881. on_template_render = partial(store_rendered_templates, data)
  882. signal_uid = "template-render-%s" % id(request)
  883. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  884. # Capture exceptions created by the handler.
  885. exception_uid = "request-exception-%s" % id(request)
  886. got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
  887. try:
  888. response = self.handler(environ)
  889. finally:
  890. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  891. got_request_exception.disconnect(dispatch_uid=exception_uid)
  892. # Check for signaled exceptions.
  893. self.check_exception(response)
  894. # Save the client and request that stimulated the response.
  895. response.client = self
  896. response.request = request
  897. # Add any rendered template detail to the response.
  898. response.templates = data.get("templates", [])
  899. response.context = data.get("context")
  900. response.json = partial(self._parse_json, response)
  901. # Attach the ResolverMatch instance to the response.
  902. urlconf = getattr(response.wsgi_request, "urlconf", None)
  903. response.resolver_match = SimpleLazyObject(
  904. lambda: resolve(request["PATH_INFO"], urlconf=urlconf),
  905. )
  906. # Flatten a single context. Not really necessary anymore thanks to the
  907. # __getattr__ flattening in ContextList, but has some edge case
  908. # backwards compatibility implications.
  909. if response.context and len(response.context) == 1:
  910. response.context = response.context[0]
  911. # Update persistent cookie data.
  912. if response.cookies:
  913. self.cookies.update(response.cookies)
  914. return response
  915. def get(
  916. self,
  917. path,
  918. data=None,
  919. follow=False,
  920. secure=False,
  921. *,
  922. headers=None,
  923. **extra,
  924. ):
  925. """Request a response from the server using GET."""
  926. self.extra = extra
  927. self.headers = headers
  928. response = super().get(path, data=data, secure=secure, headers=headers, **extra)
  929. if follow:
  930. response = self._handle_redirects(
  931. response, data=data, headers=headers, **extra
  932. )
  933. return response
  934. def post(
  935. self,
  936. path,
  937. data=None,
  938. content_type=MULTIPART_CONTENT,
  939. follow=False,
  940. secure=False,
  941. *,
  942. headers=None,
  943. **extra,
  944. ):
  945. """Request a response from the server using POST."""
  946. self.extra = extra
  947. self.headers = headers
  948. response = super().post(
  949. path,
  950. data=data,
  951. content_type=content_type,
  952. secure=secure,
  953. headers=headers,
  954. **extra,
  955. )
  956. if follow:
  957. response = self._handle_redirects(
  958. response, data=data, content_type=content_type, headers=headers, **extra
  959. )
  960. return response
  961. def head(
  962. self,
  963. path,
  964. data=None,
  965. follow=False,
  966. secure=False,
  967. *,
  968. headers=None,
  969. **extra,
  970. ):
  971. """Request a response from the server using HEAD."""
  972. self.extra = extra
  973. self.headers = headers
  974. response = super().head(
  975. path, data=data, secure=secure, headers=headers, **extra
  976. )
  977. if follow:
  978. response = self._handle_redirects(
  979. response, data=data, headers=headers, **extra
  980. )
  981. return response
  982. def options(
  983. self,
  984. path,
  985. data="",
  986. content_type="application/octet-stream",
  987. follow=False,
  988. secure=False,
  989. *,
  990. headers=None,
  991. **extra,
  992. ):
  993. """Request a response from the server using OPTIONS."""
  994. self.extra = extra
  995. self.headers = headers
  996. response = super().options(
  997. path,
  998. data=data,
  999. content_type=content_type,
  1000. secure=secure,
  1001. headers=headers,
  1002. **extra,
  1003. )
  1004. if follow:
  1005. response = self._handle_redirects(
  1006. response, data=data, content_type=content_type, headers=headers, **extra
  1007. )
  1008. return response
  1009. def put(
  1010. self,
  1011. path,
  1012. data="",
  1013. content_type="application/octet-stream",
  1014. follow=False,
  1015. secure=False,
  1016. *,
  1017. headers=None,
  1018. **extra,
  1019. ):
  1020. """Send a resource to the server using PUT."""
  1021. self.extra = extra
  1022. self.headers = headers
  1023. response = super().put(
  1024. path,
  1025. data=data,
  1026. content_type=content_type,
  1027. secure=secure,
  1028. headers=headers,
  1029. **extra,
  1030. )
  1031. if follow:
  1032. response = self._handle_redirects(
  1033. response, data=data, content_type=content_type, headers=headers, **extra
  1034. )
  1035. return response
  1036. def patch(
  1037. self,
  1038. path,
  1039. data="",
  1040. content_type="application/octet-stream",
  1041. follow=False,
  1042. secure=False,
  1043. *,
  1044. headers=None,
  1045. **extra,
  1046. ):
  1047. """Send a resource to the server using PATCH."""
  1048. self.extra = extra
  1049. self.headers = headers
  1050. response = super().patch(
  1051. path,
  1052. data=data,
  1053. content_type=content_type,
  1054. secure=secure,
  1055. headers=headers,
  1056. **extra,
  1057. )
  1058. if follow:
  1059. response = self._handle_redirects(
  1060. response, data=data, content_type=content_type, headers=headers, **extra
  1061. )
  1062. return response
  1063. def delete(
  1064. self,
  1065. path,
  1066. data="",
  1067. content_type="application/octet-stream",
  1068. follow=False,
  1069. secure=False,
  1070. *,
  1071. headers=None,
  1072. **extra,
  1073. ):
  1074. """Send a DELETE request to the server."""
  1075. self.extra = extra
  1076. self.headers = headers
  1077. response = super().delete(
  1078. path,
  1079. data=data,
  1080. content_type=content_type,
  1081. secure=secure,
  1082. headers=headers,
  1083. **extra,
  1084. )
  1085. if follow:
  1086. response = self._handle_redirects(
  1087. response, data=data, content_type=content_type, headers=headers, **extra
  1088. )
  1089. return response
  1090. def trace(
  1091. self,
  1092. path,
  1093. data="",
  1094. follow=False,
  1095. secure=False,
  1096. *,
  1097. headers=None,
  1098. **extra,
  1099. ):
  1100. """Send a TRACE request to the server."""
  1101. self.extra = extra
  1102. self.headers = headers
  1103. response = super().trace(
  1104. path, data=data, secure=secure, headers=headers, **extra
  1105. )
  1106. if follow:
  1107. response = self._handle_redirects(
  1108. response, data=data, headers=headers, **extra
  1109. )
  1110. return response
  1111. def _handle_redirects(
  1112. self,
  1113. response,
  1114. data="",
  1115. content_type="",
  1116. headers=None,
  1117. **extra,
  1118. ):
  1119. """
  1120. Follow any redirects by requesting responses from the server using GET.
  1121. """
  1122. response.redirect_chain = []
  1123. while response.status_code in REDIRECT_STATUS_CODES:
  1124. redirect_chain = response.redirect_chain
  1125. response = self._follow_redirect(
  1126. response,
  1127. data=data,
  1128. content_type=content_type,
  1129. headers=headers,
  1130. **extra,
  1131. )
  1132. response.redirect_chain = redirect_chain
  1133. self._ensure_redirects_not_cyclic(response)
  1134. return response
  1135. class AsyncClient(ClientMixin, AsyncRequestFactory):
  1136. """
  1137. An async version of Client that creates ASGIRequests and calls through an
  1138. async request path.
  1139. Does not currently support "follow" on its methods.
  1140. """
  1141. def __init__(
  1142. self,
  1143. enforce_csrf_checks=False,
  1144. raise_request_exception=True,
  1145. *,
  1146. headers=None,
  1147. **defaults,
  1148. ):
  1149. super().__init__(headers=headers, **defaults)
  1150. self.handler = AsyncClientHandler(enforce_csrf_checks)
  1151. self.raise_request_exception = raise_request_exception
  1152. self.exc_info = None
  1153. self.extra = None
  1154. self.headers = None
  1155. async def request(self, **request):
  1156. """
  1157. Make a generic request. Compose the scope dictionary and pass to the
  1158. handler, return the result of the handler. Assume defaults for the
  1159. query environment, which can be overridden using the arguments to the
  1160. request.
  1161. """
  1162. scope = self._base_scope(**request)
  1163. # Curry a data dictionary into an instance of the template renderer
  1164. # callback function.
  1165. data = {}
  1166. on_template_render = partial(store_rendered_templates, data)
  1167. signal_uid = "template-render-%s" % id(request)
  1168. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  1169. # Capture exceptions created by the handler.
  1170. exception_uid = "request-exception-%s" % id(request)
  1171. got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
  1172. try:
  1173. response = await self.handler(scope)
  1174. finally:
  1175. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  1176. got_request_exception.disconnect(dispatch_uid=exception_uid)
  1177. # Check for signaled exceptions.
  1178. self.check_exception(response)
  1179. # Save the client and request that stimulated the response.
  1180. response.client = self
  1181. response.request = request
  1182. # Add any rendered template detail to the response.
  1183. response.templates = data.get("templates", [])
  1184. response.context = data.get("context")
  1185. response.json = partial(self._parse_json, response)
  1186. # Attach the ResolverMatch instance to the response.
  1187. urlconf = getattr(response.asgi_request, "urlconf", None)
  1188. response.resolver_match = SimpleLazyObject(
  1189. lambda: resolve(request["path"], urlconf=urlconf),
  1190. )
  1191. # Flatten a single context. Not really necessary anymore thanks to the
  1192. # __getattr__ flattening in ContextList, but has some edge case
  1193. # backwards compatibility implications.
  1194. if response.context and len(response.context) == 1:
  1195. response.context = response.context[0]
  1196. # Update persistent cookie data.
  1197. if response.cookies:
  1198. self.cookies.update(response.cookies)
  1199. return response
  1200. async def get(
  1201. self,
  1202. path,
  1203. data=None,
  1204. follow=False,
  1205. secure=False,
  1206. *,
  1207. headers=None,
  1208. **extra,
  1209. ):
  1210. """Request a response from the server using GET."""
  1211. self.extra = extra
  1212. self.headers = headers
  1213. response = await super().get(
  1214. path, data=data, secure=secure, headers=headers, **extra
  1215. )
  1216. if follow:
  1217. response = await self._ahandle_redirects(
  1218. response, data=data, headers=headers, **extra
  1219. )
  1220. return response
  1221. async def post(
  1222. self,
  1223. path,
  1224. data=None,
  1225. content_type=MULTIPART_CONTENT,
  1226. follow=False,
  1227. secure=False,
  1228. *,
  1229. headers=None,
  1230. **extra,
  1231. ):
  1232. """Request a response from the server using POST."""
  1233. self.extra = extra
  1234. self.headers = headers
  1235. response = await super().post(
  1236. path,
  1237. data=data,
  1238. content_type=content_type,
  1239. secure=secure,
  1240. headers=headers,
  1241. **extra,
  1242. )
  1243. if follow:
  1244. response = await self._ahandle_redirects(
  1245. response, data=data, content_type=content_type, headers=headers, **extra
  1246. )
  1247. return response
  1248. async def head(
  1249. self,
  1250. path,
  1251. data=None,
  1252. follow=False,
  1253. secure=False,
  1254. *,
  1255. headers=None,
  1256. **extra,
  1257. ):
  1258. """Request a response from the server using HEAD."""
  1259. self.extra = extra
  1260. self.headers = headers
  1261. response = await super().head(
  1262. path, data=data, secure=secure, headers=headers, **extra
  1263. )
  1264. if follow:
  1265. response = await self._ahandle_redirects(
  1266. response, data=data, headers=headers, **extra
  1267. )
  1268. return response
  1269. async def options(
  1270. self,
  1271. path,
  1272. data="",
  1273. content_type="application/octet-stream",
  1274. follow=False,
  1275. secure=False,
  1276. *,
  1277. headers=None,
  1278. **extra,
  1279. ):
  1280. """Request a response from the server using OPTIONS."""
  1281. self.extra = extra
  1282. self.headers = headers
  1283. response = await super().options(
  1284. path,
  1285. data=data,
  1286. content_type=content_type,
  1287. secure=secure,
  1288. headers=headers,
  1289. **extra,
  1290. )
  1291. if follow:
  1292. response = await self._ahandle_redirects(
  1293. response, data=data, content_type=content_type, headers=headers, **extra
  1294. )
  1295. return response
  1296. async def put(
  1297. self,
  1298. path,
  1299. data="",
  1300. content_type="application/octet-stream",
  1301. follow=False,
  1302. secure=False,
  1303. *,
  1304. headers=None,
  1305. **extra,
  1306. ):
  1307. """Send a resource to the server using PUT."""
  1308. self.extra = extra
  1309. self.headers = headers
  1310. response = await super().put(
  1311. path,
  1312. data=data,
  1313. content_type=content_type,
  1314. secure=secure,
  1315. headers=headers,
  1316. **extra,
  1317. )
  1318. if follow:
  1319. response = await self._ahandle_redirects(
  1320. response, data=data, content_type=content_type, headers=headers, **extra
  1321. )
  1322. return response
  1323. async def patch(
  1324. self,
  1325. path,
  1326. data="",
  1327. content_type="application/octet-stream",
  1328. follow=False,
  1329. secure=False,
  1330. *,
  1331. headers=None,
  1332. **extra,
  1333. ):
  1334. """Send a resource to the server using PATCH."""
  1335. self.extra = extra
  1336. self.headers = headers
  1337. response = await super().patch(
  1338. path,
  1339. data=data,
  1340. content_type=content_type,
  1341. secure=secure,
  1342. headers=headers,
  1343. **extra,
  1344. )
  1345. if follow:
  1346. response = await self._ahandle_redirects(
  1347. response, data=data, content_type=content_type, headers=headers, **extra
  1348. )
  1349. return response
  1350. async def delete(
  1351. self,
  1352. path,
  1353. data="",
  1354. content_type="application/octet-stream",
  1355. follow=False,
  1356. secure=False,
  1357. *,
  1358. headers=None,
  1359. **extra,
  1360. ):
  1361. """Send a DELETE request to the server."""
  1362. self.extra = extra
  1363. self.headers = headers
  1364. response = await super().delete(
  1365. path,
  1366. data=data,
  1367. content_type=content_type,
  1368. secure=secure,
  1369. headers=headers,
  1370. **extra,
  1371. )
  1372. if follow:
  1373. response = await self._ahandle_redirects(
  1374. response, data=data, content_type=content_type, headers=headers, **extra
  1375. )
  1376. return response
  1377. async def trace(
  1378. self,
  1379. path,
  1380. data="",
  1381. follow=False,
  1382. secure=False,
  1383. *,
  1384. headers=None,
  1385. **extra,
  1386. ):
  1387. """Send a TRACE request to the server."""
  1388. self.extra = extra
  1389. self.headers = headers
  1390. response = await super().trace(
  1391. path, data=data, secure=secure, headers=headers, **extra
  1392. )
  1393. if follow:
  1394. response = await self._ahandle_redirects(
  1395. response, data=data, headers=headers, **extra
  1396. )
  1397. return response
  1398. async def _ahandle_redirects(
  1399. self,
  1400. response,
  1401. data="",
  1402. content_type="",
  1403. headers=None,
  1404. **extra,
  1405. ):
  1406. """
  1407. Follow any redirects by requesting responses from the server using GET.
  1408. """
  1409. response.redirect_chain = []
  1410. while response.status_code in REDIRECT_STATUS_CODES:
  1411. redirect_chain = response.redirect_chain
  1412. response = await self._follow_redirect(
  1413. response,
  1414. data=data,
  1415. content_type=content_type,
  1416. headers=headers,
  1417. **extra,
  1418. )
  1419. response.redirect_chain = redirect_chain
  1420. self._ensure_redirects_not_cyclic(response)
  1421. return response