test.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. from __future__ import annotations
  2. import dataclasses
  3. import mimetypes
  4. import sys
  5. import typing as t
  6. from collections import defaultdict
  7. from datetime import datetime
  8. from io import BytesIO
  9. from itertools import chain
  10. from random import random
  11. from tempfile import TemporaryFile
  12. from time import time
  13. from urllib.parse import unquote
  14. from urllib.parse import urlsplit
  15. from urllib.parse import urlunsplit
  16. from ._internal import _get_environ
  17. from ._internal import _wsgi_decoding_dance
  18. from ._internal import _wsgi_encoding_dance
  19. from .datastructures import Authorization
  20. from .datastructures import CallbackDict
  21. from .datastructures import CombinedMultiDict
  22. from .datastructures import EnvironHeaders
  23. from .datastructures import FileMultiDict
  24. from .datastructures import Headers
  25. from .datastructures import MultiDict
  26. from .http import dump_cookie
  27. from .http import dump_options_header
  28. from .http import parse_cookie
  29. from .http import parse_date
  30. from .http import parse_options_header
  31. from .sansio.multipart import Data
  32. from .sansio.multipart import Epilogue
  33. from .sansio.multipart import Field
  34. from .sansio.multipart import File
  35. from .sansio.multipart import MultipartEncoder
  36. from .sansio.multipart import Preamble
  37. from .urls import _urlencode
  38. from .urls import iri_to_uri
  39. from .utils import cached_property
  40. from .utils import get_content_type
  41. from .wrappers.request import Request
  42. from .wrappers.response import Response
  43. from .wsgi import ClosingIterator
  44. from .wsgi import get_current_url
  45. if t.TYPE_CHECKING:
  46. import typing_extensions as te
  47. from _typeshed.wsgi import WSGIApplication
  48. from _typeshed.wsgi import WSGIEnvironment
  49. def stream_encode_multipart(
  50. data: t.Mapping[str, t.Any],
  51. use_tempfile: bool = True,
  52. threshold: int = 1024 * 500,
  53. boundary: str | None = None,
  54. ) -> tuple[t.IO[bytes], int, str]:
  55. """Encode a dict of values (either strings or file descriptors or
  56. :class:`FileStorage` objects.) into a multipart encoded string stored
  57. in a file descriptor.
  58. This is not secure and must only be used during testing, never in applications.
  59. .. versionchanged:: 3.0
  60. The ``charset`` parameter was removed.
  61. """
  62. if boundary is None:
  63. boundary = f"---------------WerkzeugFormPart_{time()}{random()}"
  64. stream: t.IO[bytes] = BytesIO()
  65. total_length = 0
  66. on_disk = False
  67. write_binary: t.Callable[[bytes], int]
  68. if use_tempfile:
  69. def write_binary(s: bytes) -> int:
  70. nonlocal stream, total_length, on_disk
  71. if on_disk:
  72. return stream.write(s)
  73. else:
  74. length = len(s)
  75. if length + total_length <= threshold:
  76. stream.write(s)
  77. else:
  78. new_stream = t.cast(t.IO[bytes], TemporaryFile("wb+"))
  79. new_stream.write(stream.getvalue()) # type: ignore
  80. new_stream.write(s)
  81. stream = new_stream
  82. on_disk = True
  83. total_length += length
  84. return length
  85. else:
  86. write_binary = stream.write
  87. encoder = MultipartEncoder(boundary.encode())
  88. write_binary(encoder.send_event(Preamble(data=b"")))
  89. for key, value in _iter_data(data):
  90. reader = getattr(value, "read", None)
  91. if reader is not None:
  92. filename = getattr(value, "filename", getattr(value, "name", None))
  93. content_type = getattr(value, "content_type", None)
  94. if content_type is None:
  95. content_type = (
  96. filename
  97. and mimetypes.guess_type(filename)[0]
  98. or "application/octet-stream"
  99. )
  100. headers = value.headers
  101. headers.update([("Content-Type", content_type)])
  102. if filename is None:
  103. write_binary(encoder.send_event(Field(name=key, headers=headers)))
  104. else:
  105. write_binary(
  106. encoder.send_event(
  107. File(name=key, filename=filename, headers=headers)
  108. )
  109. )
  110. while True:
  111. chunk = reader(16384)
  112. if not chunk:
  113. write_binary(encoder.send_event(Data(data=chunk, more_data=False)))
  114. break
  115. write_binary(encoder.send_event(Data(data=chunk, more_data=True)))
  116. else:
  117. if not isinstance(value, str):
  118. value = str(value)
  119. write_binary(encoder.send_event(Field(name=key, headers=Headers())))
  120. write_binary(encoder.send_event(Data(data=value.encode(), more_data=False)))
  121. write_binary(encoder.send_event(Epilogue(data=b"")))
  122. length = stream.tell()
  123. stream.seek(0)
  124. return stream, length, boundary
  125. def encode_multipart(
  126. values: t.Mapping[str, t.Any], boundary: str | None = None
  127. ) -> tuple[str, bytes]:
  128. """Like `stream_encode_multipart` but returns a tuple in the form
  129. (``boundary``, ``data``) where data is bytes.
  130. This is not secure and must only be used during testing, never in applications.
  131. .. versionchanged:: 3.0
  132. The ``charset`` parameter was removed.
  133. """
  134. stream, length, boundary = stream_encode_multipart(
  135. values, use_tempfile=False, boundary=boundary
  136. )
  137. return boundary, stream.read()
  138. def _iter_data(data: t.Mapping[str, t.Any]) -> t.Iterator[tuple[str, t.Any]]:
  139. """Iterate over a mapping that might have a list of values, yielding
  140. all key, value pairs. Almost like iter_multi_items but only allows
  141. lists, not tuples, of values so tuples can be used for files.
  142. """
  143. if isinstance(data, MultiDict):
  144. yield from data.items(multi=True)
  145. else:
  146. for key, value in data.items():
  147. if isinstance(value, list):
  148. for v in value:
  149. yield key, v
  150. else:
  151. yield key, value
  152. _TAnyMultiDict = t.TypeVar("_TAnyMultiDict", bound="MultiDict[t.Any, t.Any]")
  153. class EnvironBuilder:
  154. """This class can be used to conveniently create a WSGI environment
  155. for testing purposes. It can be used to quickly create WSGI environments
  156. or request objects from arbitrary data.
  157. The signature of this class is also used in some other places as of
  158. Werkzeug 0.5 (:func:`create_environ`, :meth:`Response.from_values`,
  159. :meth:`Client.open`). Because of this most of the functionality is
  160. available through the constructor alone.
  161. Files and regular form data can be manipulated independently of each
  162. other with the :attr:`form` and :attr:`files` attributes, but are
  163. passed with the same argument to the constructor: `data`.
  164. `data` can be any of these values:
  165. - a `str` or `bytes` object: The object is converted into an
  166. :attr:`input_stream`, the :attr:`content_length` is set and you have to
  167. provide a :attr:`content_type`.
  168. - a `dict` or :class:`MultiDict`: The keys have to be strings. The values
  169. have to be either any of the following objects, or a list of any of the
  170. following objects:
  171. - a :class:`file`-like object: These are converted into
  172. :class:`FileStorage` objects automatically.
  173. - a `tuple`: The :meth:`~FileMultiDict.add_file` method is called
  174. with the key and the unpacked `tuple` items as positional
  175. arguments.
  176. - a `str`: The string is set as form data for the associated key.
  177. - a file-like object: The object content is loaded in memory and then
  178. handled like a regular `str` or a `bytes`.
  179. :param path: the path of the request. In the WSGI environment this will
  180. end up as `PATH_INFO`. If the `query_string` is not defined
  181. and there is a question mark in the `path` everything after
  182. it is used as query string.
  183. :param base_url: the base URL is a URL that is used to extract the WSGI
  184. URL scheme, host (server name + server port) and the
  185. script root (`SCRIPT_NAME`).
  186. :param query_string: an optional string or dict with URL parameters.
  187. :param method: the HTTP method to use, defaults to `GET`.
  188. :param input_stream: an optional input stream. Do not specify this and
  189. `data`. As soon as an input stream is set you can't
  190. modify :attr:`args` and :attr:`files` unless you
  191. set the :attr:`input_stream` to `None` again.
  192. :param content_type: The content type for the request. As of 0.5 you
  193. don't have to provide this when specifying files
  194. and form data via `data`.
  195. :param content_length: The content length for the request. You don't
  196. have to specify this when providing data via
  197. `data`.
  198. :param errors_stream: an optional error stream that is used for
  199. `wsgi.errors`. Defaults to :data:`stderr`.
  200. :param multithread: controls `wsgi.multithread`. Defaults to `False`.
  201. :param multiprocess: controls `wsgi.multiprocess`. Defaults to `False`.
  202. :param run_once: controls `wsgi.run_once`. Defaults to `False`.
  203. :param headers: an optional list or :class:`Headers` object of headers.
  204. :param data: a string or dict of form data or a file-object.
  205. See explanation above.
  206. :param json: An object to be serialized and assigned to ``data``.
  207. Defaults the content type to ``"application/json"``.
  208. Serialized with the function assigned to :attr:`json_dumps`.
  209. :param environ_base: an optional dict of environment defaults.
  210. :param environ_overrides: an optional dict of environment overrides.
  211. :param auth: An authorization object to use for the
  212. ``Authorization`` header value. A ``(username, password)`` tuple
  213. is a shortcut for ``Basic`` authorization.
  214. .. versionchanged:: 3.0
  215. The ``charset`` parameter was removed.
  216. .. versionchanged:: 2.1
  217. ``CONTENT_TYPE`` and ``CONTENT_LENGTH`` are not duplicated as
  218. header keys in the environ.
  219. .. versionchanged:: 2.0
  220. ``REQUEST_URI`` and ``RAW_URI`` is the full raw URI including
  221. the query string, not only the path.
  222. .. versionchanged:: 2.0
  223. The default :attr:`request_class` is ``Request`` instead of
  224. ``BaseRequest``.
  225. .. versionadded:: 2.0
  226. Added the ``auth`` parameter.
  227. .. versionadded:: 0.15
  228. The ``json`` param and :meth:`json_dumps` method.
  229. .. versionadded:: 0.15
  230. The environ has keys ``REQUEST_URI`` and ``RAW_URI`` containing
  231. the path before percent-decoding. This is not part of the WSGI
  232. PEP, but many WSGI servers include it.
  233. .. versionchanged:: 0.6
  234. ``path`` and ``base_url`` can now be unicode strings that are
  235. encoded with :func:`iri_to_uri`.
  236. """
  237. #: the server protocol to use. defaults to HTTP/1.1
  238. server_protocol = "HTTP/1.1"
  239. #: the wsgi version to use. defaults to (1, 0)
  240. wsgi_version = (1, 0)
  241. #: The default request class used by :meth:`get_request`.
  242. request_class = Request
  243. import json
  244. #: The serialization function used when ``json`` is passed.
  245. json_dumps = staticmethod(json.dumps)
  246. del json
  247. _args: MultiDict[str, str] | None
  248. _query_string: str | None
  249. _input_stream: t.IO[bytes] | None
  250. _form: MultiDict[str, str] | None
  251. _files: FileMultiDict | None
  252. def __init__(
  253. self,
  254. path: str = "/",
  255. base_url: str | None = None,
  256. query_string: t.Mapping[str, str] | str | None = None,
  257. method: str = "GET",
  258. input_stream: t.IO[bytes] | None = None,
  259. content_type: str | None = None,
  260. content_length: int | None = None,
  261. errors_stream: t.IO[str] | None = None,
  262. multithread: bool = False,
  263. multiprocess: bool = False,
  264. run_once: bool = False,
  265. headers: Headers | t.Iterable[tuple[str, str]] | None = None,
  266. data: None | (t.IO[bytes] | str | bytes | t.Mapping[str, t.Any]) = None,
  267. environ_base: t.Mapping[str, t.Any] | None = None,
  268. environ_overrides: t.Mapping[str, t.Any] | None = None,
  269. mimetype: str | None = None,
  270. json: t.Mapping[str, t.Any] | None = None,
  271. auth: Authorization | tuple[str, str] | None = None,
  272. ) -> None:
  273. if query_string is not None and "?" in path:
  274. raise ValueError("Query string is defined in the path and as an argument")
  275. request_uri = urlsplit(path)
  276. if query_string is None and "?" in path:
  277. query_string = request_uri.query
  278. self.path = iri_to_uri(request_uri.path)
  279. self.request_uri = path
  280. if base_url is not None:
  281. base_url = iri_to_uri(base_url)
  282. self.base_url = base_url
  283. if isinstance(query_string, str):
  284. self.query_string = query_string
  285. else:
  286. if query_string is None:
  287. query_string = MultiDict()
  288. elif not isinstance(query_string, MultiDict):
  289. query_string = MultiDict(query_string)
  290. self.args = query_string
  291. self.method = method
  292. if headers is None:
  293. headers = Headers()
  294. elif not isinstance(headers, Headers):
  295. headers = Headers(headers)
  296. self.headers = headers
  297. if content_type is not None:
  298. self.content_type = content_type
  299. if errors_stream is None:
  300. errors_stream = sys.stderr
  301. self.errors_stream = errors_stream
  302. self.multithread = multithread
  303. self.multiprocess = multiprocess
  304. self.run_once = run_once
  305. self.environ_base = environ_base
  306. self.environ_overrides = environ_overrides
  307. self.input_stream = input_stream
  308. self.content_length = content_length
  309. self.closed = False
  310. if auth is not None:
  311. if isinstance(auth, tuple):
  312. auth = Authorization(
  313. "basic", {"username": auth[0], "password": auth[1]}
  314. )
  315. self.headers.set("Authorization", auth.to_header())
  316. if json is not None:
  317. if data is not None:
  318. raise TypeError("can't provide both json and data")
  319. data = self.json_dumps(json)
  320. if self.content_type is None:
  321. self.content_type = "application/json"
  322. if data:
  323. if input_stream is not None:
  324. raise TypeError("can't provide input stream and data")
  325. if hasattr(data, "read"):
  326. data = data.read()
  327. if isinstance(data, str):
  328. data = data.encode()
  329. if isinstance(data, bytes):
  330. self.input_stream = BytesIO(data)
  331. if self.content_length is None:
  332. self.content_length = len(data)
  333. else:
  334. for key, value in _iter_data(data):
  335. if isinstance(value, (tuple, dict)) or hasattr(value, "read"):
  336. self._add_file_from_data(key, value)
  337. else:
  338. self.form.setlistdefault(key).append(value)
  339. if mimetype is not None:
  340. self.mimetype = mimetype
  341. @classmethod
  342. def from_environ(cls, environ: WSGIEnvironment, **kwargs: t.Any) -> EnvironBuilder:
  343. """Turn an environ dict back into a builder. Any extra kwargs
  344. override the args extracted from the environ.
  345. .. versionchanged:: 2.0
  346. Path and query values are passed through the WSGI decoding
  347. dance to avoid double encoding.
  348. .. versionadded:: 0.15
  349. """
  350. headers = Headers(EnvironHeaders(environ))
  351. out = {
  352. "path": _wsgi_decoding_dance(environ["PATH_INFO"]),
  353. "base_url": cls._make_base_url(
  354. environ["wsgi.url_scheme"],
  355. headers.pop("Host"),
  356. _wsgi_decoding_dance(environ["SCRIPT_NAME"]),
  357. ),
  358. "query_string": _wsgi_decoding_dance(environ["QUERY_STRING"]),
  359. "method": environ["REQUEST_METHOD"],
  360. "input_stream": environ["wsgi.input"],
  361. "content_type": headers.pop("Content-Type", None),
  362. "content_length": headers.pop("Content-Length", None),
  363. "errors_stream": environ["wsgi.errors"],
  364. "multithread": environ["wsgi.multithread"],
  365. "multiprocess": environ["wsgi.multiprocess"],
  366. "run_once": environ["wsgi.run_once"],
  367. "headers": headers,
  368. }
  369. out.update(kwargs)
  370. return cls(**out)
  371. def _add_file_from_data(
  372. self,
  373. key: str,
  374. value: (t.IO[bytes] | tuple[t.IO[bytes], str] | tuple[t.IO[bytes], str, str]),
  375. ) -> None:
  376. """Called in the EnvironBuilder to add files from the data dict."""
  377. if isinstance(value, tuple):
  378. self.files.add_file(key, *value)
  379. else:
  380. self.files.add_file(key, value)
  381. @staticmethod
  382. def _make_base_url(scheme: str, host: str, script_root: str) -> str:
  383. return urlunsplit((scheme, host, script_root, "", "")).rstrip("/") + "/"
  384. @property
  385. def base_url(self) -> str:
  386. """The base URL is used to extract the URL scheme, host name,
  387. port, and root path.
  388. """
  389. return self._make_base_url(self.url_scheme, self.host, self.script_root)
  390. @base_url.setter
  391. def base_url(self, value: str | None) -> None:
  392. if value is None:
  393. scheme = "http"
  394. netloc = "localhost"
  395. script_root = ""
  396. else:
  397. scheme, netloc, script_root, qs, anchor = urlsplit(value)
  398. if qs or anchor:
  399. raise ValueError("base url must not contain a query string or fragment")
  400. self.script_root = script_root.rstrip("/")
  401. self.host = netloc
  402. self.url_scheme = scheme
  403. @property
  404. def content_type(self) -> str | None:
  405. """The content type for the request. Reflected from and to
  406. the :attr:`headers`. Do not set if you set :attr:`files` or
  407. :attr:`form` for auto detection.
  408. """
  409. ct = self.headers.get("Content-Type")
  410. if ct is None and not self._input_stream:
  411. if self._files:
  412. return "multipart/form-data"
  413. if self._form:
  414. return "application/x-www-form-urlencoded"
  415. return None
  416. return ct
  417. @content_type.setter
  418. def content_type(self, value: str | None) -> None:
  419. if value is None:
  420. self.headers.pop("Content-Type", None)
  421. else:
  422. self.headers["Content-Type"] = value
  423. @property
  424. def mimetype(self) -> str | None:
  425. """The mimetype (content type without charset etc.)
  426. .. versionadded:: 0.14
  427. """
  428. ct = self.content_type
  429. return ct.partition(";")[0].strip() if ct else None
  430. @mimetype.setter
  431. def mimetype(self, value: str) -> None:
  432. self.content_type = get_content_type(value, "utf-8")
  433. @property
  434. def mimetype_params(self) -> t.Mapping[str, str]:
  435. """The mimetype parameters as dict. For example if the
  436. content type is ``text/html; charset=utf-8`` the params would be
  437. ``{'charset': 'utf-8'}``.
  438. .. versionadded:: 0.14
  439. """
  440. def on_update(d: CallbackDict[str, str]) -> None:
  441. self.headers["Content-Type"] = dump_options_header(self.mimetype, d)
  442. d = parse_options_header(self.headers.get("content-type", ""))[1]
  443. return CallbackDict(d, on_update)
  444. @property
  445. def content_length(self) -> int | None:
  446. """The content length as integer. Reflected from and to the
  447. :attr:`headers`. Do not set if you set :attr:`files` or
  448. :attr:`form` for auto detection.
  449. """
  450. return self.headers.get("Content-Length", type=int)
  451. @content_length.setter
  452. def content_length(self, value: int | None) -> None:
  453. if value is None:
  454. self.headers.pop("Content-Length", None)
  455. else:
  456. self.headers["Content-Length"] = str(value)
  457. def _get_form(self, name: str, storage: type[_TAnyMultiDict]) -> _TAnyMultiDict:
  458. """Common behavior for getting the :attr:`form` and
  459. :attr:`files` properties.
  460. :param name: Name of the internal cached attribute.
  461. :param storage: Storage class used for the data.
  462. """
  463. if self.input_stream is not None:
  464. raise AttributeError("an input stream is defined")
  465. rv = getattr(self, name)
  466. if rv is None:
  467. rv = storage()
  468. setattr(self, name, rv)
  469. return rv # type: ignore
  470. def _set_form(self, name: str, value: MultiDict[str, t.Any]) -> None:
  471. """Common behavior for setting the :attr:`form` and
  472. :attr:`files` properties.
  473. :param name: Name of the internal cached attribute.
  474. :param value: Value to assign to the attribute.
  475. """
  476. self._input_stream = None
  477. setattr(self, name, value)
  478. @property
  479. def form(self) -> MultiDict[str, str]:
  480. """A :class:`MultiDict` of form values."""
  481. return self._get_form("_form", MultiDict)
  482. @form.setter
  483. def form(self, value: MultiDict[str, str]) -> None:
  484. self._set_form("_form", value)
  485. @property
  486. def files(self) -> FileMultiDict:
  487. """A :class:`FileMultiDict` of uploaded files. Use
  488. :meth:`~FileMultiDict.add_file` to add new files.
  489. """
  490. return self._get_form("_files", FileMultiDict)
  491. @files.setter
  492. def files(self, value: FileMultiDict) -> None:
  493. self._set_form("_files", value)
  494. @property
  495. def input_stream(self) -> t.IO[bytes] | None:
  496. """An optional input stream. This is mutually exclusive with
  497. setting :attr:`form` and :attr:`files`, setting it will clear
  498. those. Do not provide this if the method is not ``POST`` or
  499. another method that has a body.
  500. """
  501. return self._input_stream
  502. @input_stream.setter
  503. def input_stream(self, value: t.IO[bytes] | None) -> None:
  504. self._input_stream = value
  505. self._form = None
  506. self._files = None
  507. @property
  508. def query_string(self) -> str:
  509. """The query string. If you set this to a string
  510. :attr:`args` will no longer be available.
  511. """
  512. if self._query_string is None:
  513. if self._args is not None:
  514. return _urlencode(self._args)
  515. return ""
  516. return self._query_string
  517. @query_string.setter
  518. def query_string(self, value: str | None) -> None:
  519. self._query_string = value
  520. self._args = None
  521. @property
  522. def args(self) -> MultiDict[str, str]:
  523. """The URL arguments as :class:`MultiDict`."""
  524. if self._query_string is not None:
  525. raise AttributeError("a query string is defined")
  526. if self._args is None:
  527. self._args = MultiDict()
  528. return self._args
  529. @args.setter
  530. def args(self, value: MultiDict[str, str] | None) -> None:
  531. self._query_string = None
  532. self._args = value
  533. @property
  534. def server_name(self) -> str:
  535. """The server name (read-only, use :attr:`host` to set)"""
  536. return self.host.partition(":")[0]
  537. @property
  538. def server_port(self) -> int:
  539. """The server port as integer (read-only, use :attr:`host` to set)"""
  540. _, sep, port = self.host.partition(":")
  541. if sep:
  542. try:
  543. return int(port)
  544. except ValueError:
  545. pass
  546. if self.url_scheme == "https":
  547. return 443
  548. return 80
  549. def __del__(self) -> None:
  550. try:
  551. self.close()
  552. except Exception:
  553. pass
  554. def close(self) -> None:
  555. """Closes all files. If you put real :class:`file` objects into the
  556. :attr:`files` dict you can call this method to automatically close
  557. them all in one go.
  558. """
  559. if self.closed:
  560. return
  561. try:
  562. files = self.files.values()
  563. except AttributeError:
  564. files = ()
  565. for f in files:
  566. try:
  567. f.close()
  568. except Exception:
  569. pass
  570. self.closed = True
  571. def get_environ(self) -> WSGIEnvironment:
  572. """Return the built environ.
  573. .. versionchanged:: 0.15
  574. The content type and length headers are set based on
  575. input stream detection. Previously this only set the WSGI
  576. keys.
  577. """
  578. input_stream = self.input_stream
  579. content_length = self.content_length
  580. mimetype = self.mimetype
  581. content_type = self.content_type
  582. if input_stream is not None:
  583. start_pos = input_stream.tell()
  584. input_stream.seek(0, 2)
  585. end_pos = input_stream.tell()
  586. input_stream.seek(start_pos)
  587. content_length = end_pos - start_pos
  588. elif mimetype == "multipart/form-data":
  589. input_stream, content_length, boundary = stream_encode_multipart(
  590. CombinedMultiDict([self.form, self.files])
  591. )
  592. content_type = f'{mimetype}; boundary="{boundary}"'
  593. elif mimetype == "application/x-www-form-urlencoded":
  594. form_encoded = _urlencode(self.form).encode("ascii")
  595. content_length = len(form_encoded)
  596. input_stream = BytesIO(form_encoded)
  597. else:
  598. input_stream = BytesIO()
  599. result: WSGIEnvironment = {}
  600. if self.environ_base:
  601. result.update(self.environ_base)
  602. def _path_encode(x: str) -> str:
  603. return _wsgi_encoding_dance(unquote(x))
  604. raw_uri = _wsgi_encoding_dance(self.request_uri)
  605. result.update(
  606. {
  607. "REQUEST_METHOD": self.method,
  608. "SCRIPT_NAME": _path_encode(self.script_root),
  609. "PATH_INFO": _path_encode(self.path),
  610. "QUERY_STRING": _wsgi_encoding_dance(self.query_string),
  611. # Non-standard, added by mod_wsgi, uWSGI
  612. "REQUEST_URI": raw_uri,
  613. # Non-standard, added by gunicorn
  614. "RAW_URI": raw_uri,
  615. "SERVER_NAME": self.server_name,
  616. "SERVER_PORT": str(self.server_port),
  617. "HTTP_HOST": self.host,
  618. "SERVER_PROTOCOL": self.server_protocol,
  619. "wsgi.version": self.wsgi_version,
  620. "wsgi.url_scheme": self.url_scheme,
  621. "wsgi.input": input_stream,
  622. "wsgi.errors": self.errors_stream,
  623. "wsgi.multithread": self.multithread,
  624. "wsgi.multiprocess": self.multiprocess,
  625. "wsgi.run_once": self.run_once,
  626. }
  627. )
  628. headers = self.headers.copy()
  629. # Don't send these as headers, they're part of the environ.
  630. headers.remove("Content-Type")
  631. headers.remove("Content-Length")
  632. if content_type is not None:
  633. result["CONTENT_TYPE"] = content_type
  634. if content_length is not None:
  635. result["CONTENT_LENGTH"] = str(content_length)
  636. combined_headers = defaultdict(list)
  637. for key, value in headers.to_wsgi_list():
  638. combined_headers[f"HTTP_{key.upper().replace('-', '_')}"].append(value)
  639. for key, values in combined_headers.items():
  640. result[key] = ", ".join(values)
  641. if self.environ_overrides:
  642. result.update(self.environ_overrides)
  643. return result
  644. def get_request(self, cls: type[Request] | None = None) -> Request:
  645. """Returns a request with the data. If the request class is not
  646. specified :attr:`request_class` is used.
  647. :param cls: The request wrapper to use.
  648. """
  649. if cls is None:
  650. cls = self.request_class
  651. return cls(self.get_environ())
  652. class ClientRedirectError(Exception):
  653. """If a redirect loop is detected when using follow_redirects=True with
  654. the :cls:`Client`, then this exception is raised.
  655. """
  656. class Client:
  657. """Simulate sending requests to a WSGI application without running a WSGI or HTTP
  658. server.
  659. :param application: The WSGI application to make requests to.
  660. :param response_wrapper: A :class:`.Response` class to wrap response data with.
  661. Defaults to :class:`.TestResponse`. If it's not a subclass of ``TestResponse``,
  662. one will be created.
  663. :param use_cookies: Persist cookies from ``Set-Cookie`` response headers to the
  664. ``Cookie`` header in subsequent requests. Domain and path matching is supported,
  665. but other cookie parameters are ignored.
  666. :param allow_subdomain_redirects: Allow requests to follow redirects to subdomains.
  667. Enable this if the application handles subdomains and redirects between them.
  668. .. versionchanged:: 2.3
  669. Simplify cookie implementation, support domain and path matching.
  670. .. versionchanged:: 2.1
  671. All data is available as properties on the returned response object. The
  672. response cannot be returned as a tuple.
  673. .. versionchanged:: 2.0
  674. ``response_wrapper`` is always a subclass of :class:``TestResponse``.
  675. .. versionchanged:: 0.5
  676. Added the ``use_cookies`` parameter.
  677. """
  678. def __init__(
  679. self,
  680. application: WSGIApplication,
  681. response_wrapper: type[Response] | None = None,
  682. use_cookies: bool = True,
  683. allow_subdomain_redirects: bool = False,
  684. ) -> None:
  685. self.application = application
  686. if response_wrapper in {None, Response}:
  687. response_wrapper = TestResponse
  688. elif response_wrapper is not None and not issubclass(
  689. response_wrapper, TestResponse
  690. ):
  691. response_wrapper = type(
  692. "WrapperTestResponse",
  693. (TestResponse, response_wrapper),
  694. {},
  695. )
  696. self.response_wrapper = t.cast(type["TestResponse"], response_wrapper)
  697. if use_cookies:
  698. self._cookies: dict[tuple[str, str, str], Cookie] | None = {}
  699. else:
  700. self._cookies = None
  701. self.allow_subdomain_redirects = allow_subdomain_redirects
  702. def get_cookie(
  703. self, key: str, domain: str = "localhost", path: str = "/"
  704. ) -> Cookie | None:
  705. """Return a :class:`.Cookie` if it exists. Cookies are uniquely identified by
  706. ``(domain, path, key)``.
  707. :param key: The decoded form of the key for the cookie.
  708. :param domain: The domain the cookie was set for.
  709. :param path: The path the cookie was set for.
  710. .. versionadded:: 2.3
  711. """
  712. if self._cookies is None:
  713. raise TypeError(
  714. "Cookies are disabled. Create a client with 'use_cookies=True'."
  715. )
  716. return self._cookies.get((domain, path, key))
  717. def set_cookie(
  718. self,
  719. key: str,
  720. value: str = "",
  721. *,
  722. domain: str = "localhost",
  723. origin_only: bool = True,
  724. path: str = "/",
  725. **kwargs: t.Any,
  726. ) -> None:
  727. """Set a cookie to be sent in subsequent requests.
  728. This is a convenience to skip making a test request to a route that would set
  729. the cookie. To test the cookie, make a test request to a route that uses the
  730. cookie value.
  731. The client uses ``domain``, ``origin_only``, and ``path`` to determine which
  732. cookies to send with a request. It does not use other cookie parameters that
  733. browsers use, since they're not applicable in tests.
  734. :param key: The key part of the cookie.
  735. :param value: The value part of the cookie.
  736. :param domain: Send this cookie with requests that match this domain. If
  737. ``origin_only`` is true, it must be an exact match, otherwise it may be a
  738. suffix match.
  739. :param origin_only: Whether the domain must be an exact match to the request.
  740. :param path: Send this cookie with requests that match this path either exactly
  741. or as a prefix.
  742. :param kwargs: Passed to :func:`.dump_cookie`.
  743. .. versionchanged:: 3.0
  744. The parameter ``server_name`` is removed. The first parameter is
  745. ``key``. Use the ``domain`` and ``origin_only`` parameters instead.
  746. .. versionchanged:: 2.3
  747. The ``origin_only`` parameter was added.
  748. .. versionchanged:: 2.3
  749. The ``domain`` parameter defaults to ``localhost``.
  750. """
  751. if self._cookies is None:
  752. raise TypeError(
  753. "Cookies are disabled. Create a client with 'use_cookies=True'."
  754. )
  755. cookie = Cookie._from_response_header(
  756. domain, "/", dump_cookie(key, value, domain=domain, path=path, **kwargs)
  757. )
  758. cookie.origin_only = origin_only
  759. if cookie._should_delete:
  760. self._cookies.pop(cookie._storage_key, None)
  761. else:
  762. self._cookies[cookie._storage_key] = cookie
  763. def delete_cookie(
  764. self,
  765. key: str,
  766. *,
  767. domain: str = "localhost",
  768. path: str = "/",
  769. ) -> None:
  770. """Delete a cookie if it exists. Cookies are uniquely identified by
  771. ``(domain, path, key)``.
  772. :param key: The decoded form of the key for the cookie.
  773. :param domain: The domain the cookie was set for.
  774. :param path: The path the cookie was set for.
  775. .. versionchanged:: 3.0
  776. The ``server_name`` parameter is removed. The first parameter is
  777. ``key``. Use the ``domain`` parameter instead.
  778. .. versionchanged:: 3.0
  779. The ``secure``, ``httponly`` and ``samesite`` parameters are removed.
  780. .. versionchanged:: 2.3
  781. The ``domain`` parameter defaults to ``localhost``.
  782. """
  783. if self._cookies is None:
  784. raise TypeError(
  785. "Cookies are disabled. Create a client with 'use_cookies=True'."
  786. )
  787. self._cookies.pop((domain, path, key), None)
  788. def _add_cookies_to_wsgi(self, environ: WSGIEnvironment) -> None:
  789. """If cookies are enabled, set the ``Cookie`` header in the environ to the
  790. cookies that are applicable to the request host and path.
  791. :meta private:
  792. .. versionadded:: 2.3
  793. """
  794. if self._cookies is None:
  795. return
  796. url = urlsplit(get_current_url(environ))
  797. server_name = url.hostname or "localhost"
  798. value = "; ".join(
  799. c._to_request_header()
  800. for c in self._cookies.values()
  801. if c._matches_request(server_name, url.path)
  802. )
  803. if value:
  804. environ["HTTP_COOKIE"] = value
  805. else:
  806. environ.pop("HTTP_COOKIE", None)
  807. def _update_cookies_from_response(
  808. self, server_name: str, path: str, headers: list[str]
  809. ) -> None:
  810. """If cookies are enabled, update the stored cookies from any ``Set-Cookie``
  811. headers in the response.
  812. :meta private:
  813. .. versionadded:: 2.3
  814. """
  815. if self._cookies is None:
  816. return
  817. for header in headers:
  818. cookie = Cookie._from_response_header(server_name, path, header)
  819. if cookie._should_delete:
  820. self._cookies.pop(cookie._storage_key, None)
  821. else:
  822. self._cookies[cookie._storage_key] = cookie
  823. def run_wsgi_app(
  824. self, environ: WSGIEnvironment, buffered: bool = False
  825. ) -> tuple[t.Iterable[bytes], str, Headers]:
  826. """Runs the wrapped WSGI app with the given environment.
  827. :meta private:
  828. """
  829. self._add_cookies_to_wsgi(environ)
  830. rv = run_wsgi_app(self.application, environ, buffered=buffered)
  831. url = urlsplit(get_current_url(environ))
  832. self._update_cookies_from_response(
  833. url.hostname or "localhost", url.path, rv[2].getlist("Set-Cookie")
  834. )
  835. return rv
  836. def resolve_redirect(
  837. self, response: TestResponse, buffered: bool = False
  838. ) -> TestResponse:
  839. """Perform a new request to the location given by the redirect
  840. response to the previous request.
  841. :meta private:
  842. """
  843. scheme, netloc, path, qs, anchor = urlsplit(response.location)
  844. builder = EnvironBuilder.from_environ(
  845. response.request.environ, path=path, query_string=qs
  846. )
  847. to_name_parts = netloc.partition(":")[0].split(".")
  848. from_name_parts = builder.server_name.split(".")
  849. if to_name_parts != [""]:
  850. # The new location has a host, use it for the base URL.
  851. builder.url_scheme = scheme
  852. builder.host = netloc
  853. else:
  854. # A local redirect with autocorrect_location_header=False
  855. # doesn't have a host, so use the request's host.
  856. to_name_parts = from_name_parts
  857. # Explain why a redirect to a different server name won't be followed.
  858. if to_name_parts != from_name_parts:
  859. if to_name_parts[-len(from_name_parts) :] == from_name_parts:
  860. if not self.allow_subdomain_redirects:
  861. raise RuntimeError("Following subdomain redirects is not enabled.")
  862. else:
  863. raise RuntimeError("Following external redirects is not supported.")
  864. path_parts = path.split("/")
  865. root_parts = builder.script_root.split("/")
  866. if path_parts[: len(root_parts)] == root_parts:
  867. # Strip the script root from the path.
  868. builder.path = path[len(builder.script_root) :]
  869. else:
  870. # The new location is not under the script root, so use the
  871. # whole path and clear the previous root.
  872. builder.path = path
  873. builder.script_root = ""
  874. # Only 307 and 308 preserve all of the original request.
  875. if response.status_code not in {307, 308}:
  876. # HEAD is preserved, everything else becomes GET.
  877. if builder.method != "HEAD":
  878. builder.method = "GET"
  879. # Clear the body and the headers that describe it.
  880. if builder.input_stream is not None:
  881. builder.input_stream.close()
  882. builder.input_stream = None
  883. builder.content_type = None
  884. builder.content_length = None
  885. builder.headers.pop("Transfer-Encoding", None)
  886. return self.open(builder, buffered=buffered)
  887. def open(
  888. self,
  889. *args: t.Any,
  890. buffered: bool = False,
  891. follow_redirects: bool = False,
  892. **kwargs: t.Any,
  893. ) -> TestResponse:
  894. """Generate an environ dict from the given arguments, make a
  895. request to the application using it, and return the response.
  896. :param args: Passed to :class:`EnvironBuilder` to create the
  897. environ for the request. If a single arg is passed, it can
  898. be an existing :class:`EnvironBuilder` or an environ dict.
  899. :param buffered: Convert the iterator returned by the app into
  900. a list. If the iterator has a ``close()`` method, it is
  901. called automatically.
  902. :param follow_redirects: Make additional requests to follow HTTP
  903. redirects until a non-redirect status is returned.
  904. :attr:`TestResponse.history` lists the intermediate
  905. responses.
  906. .. versionchanged:: 2.1
  907. Removed the ``as_tuple`` parameter.
  908. .. versionchanged:: 2.0
  909. The request input stream is closed when calling
  910. ``response.close()``. Input streams for redirects are
  911. automatically closed.
  912. .. versionchanged:: 0.5
  913. If a dict is provided as file in the dict for the ``data``
  914. parameter the content type has to be called ``content_type``
  915. instead of ``mimetype``. This change was made for
  916. consistency with :class:`werkzeug.FileWrapper`.
  917. .. versionchanged:: 0.5
  918. Added the ``follow_redirects`` parameter.
  919. """
  920. request: Request | None = None
  921. if not kwargs and len(args) == 1:
  922. arg = args[0]
  923. if isinstance(arg, EnvironBuilder):
  924. request = arg.get_request()
  925. elif isinstance(arg, dict):
  926. request = EnvironBuilder.from_environ(arg).get_request()
  927. elif isinstance(arg, Request):
  928. request = arg
  929. if request is None:
  930. builder = EnvironBuilder(*args, **kwargs)
  931. try:
  932. request = builder.get_request()
  933. finally:
  934. builder.close()
  935. response_parts = self.run_wsgi_app(request.environ, buffered=buffered)
  936. response = self.response_wrapper(*response_parts, request=request)
  937. redirects = set()
  938. history: list[TestResponse] = []
  939. if not follow_redirects:
  940. return response
  941. while response.status_code in {
  942. 301,
  943. 302,
  944. 303,
  945. 305,
  946. 307,
  947. 308,
  948. }:
  949. # Exhaust intermediate response bodies to ensure middleware
  950. # that returns an iterator runs any cleanup code.
  951. if not buffered:
  952. response.make_sequence()
  953. response.close()
  954. new_redirect_entry = (response.location, response.status_code)
  955. if new_redirect_entry in redirects:
  956. raise ClientRedirectError(
  957. f"Loop detected: A {response.status_code} redirect"
  958. f" to {response.location} was already made."
  959. )
  960. redirects.add(new_redirect_entry)
  961. response.history = tuple(history)
  962. history.append(response)
  963. response = self.resolve_redirect(response, buffered=buffered)
  964. else:
  965. # This is the final request after redirects.
  966. response.history = tuple(history)
  967. # Close the input stream when closing the response, in case
  968. # the input is an open temporary file.
  969. response.call_on_close(request.input_stream.close)
  970. return response
  971. def get(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  972. """Call :meth:`open` with ``method`` set to ``GET``."""
  973. kw["method"] = "GET"
  974. return self.open(*args, **kw)
  975. def post(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  976. """Call :meth:`open` with ``method`` set to ``POST``."""
  977. kw["method"] = "POST"
  978. return self.open(*args, **kw)
  979. def put(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  980. """Call :meth:`open` with ``method`` set to ``PUT``."""
  981. kw["method"] = "PUT"
  982. return self.open(*args, **kw)
  983. def delete(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  984. """Call :meth:`open` with ``method`` set to ``DELETE``."""
  985. kw["method"] = "DELETE"
  986. return self.open(*args, **kw)
  987. def patch(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  988. """Call :meth:`open` with ``method`` set to ``PATCH``."""
  989. kw["method"] = "PATCH"
  990. return self.open(*args, **kw)
  991. def options(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  992. """Call :meth:`open` with ``method`` set to ``OPTIONS``."""
  993. kw["method"] = "OPTIONS"
  994. return self.open(*args, **kw)
  995. def head(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  996. """Call :meth:`open` with ``method`` set to ``HEAD``."""
  997. kw["method"] = "HEAD"
  998. return self.open(*args, **kw)
  999. def trace(self, *args: t.Any, **kw: t.Any) -> TestResponse:
  1000. """Call :meth:`open` with ``method`` set to ``TRACE``."""
  1001. kw["method"] = "TRACE"
  1002. return self.open(*args, **kw)
  1003. def __repr__(self) -> str:
  1004. return f"<{type(self).__name__} {self.application!r}>"
  1005. def create_environ(*args: t.Any, **kwargs: t.Any) -> WSGIEnvironment:
  1006. """Create a new WSGI environ dict based on the values passed. The first
  1007. parameter should be the path of the request which defaults to '/'. The
  1008. second one can either be an absolute path (in that case the host is
  1009. localhost:80) or a full path to the request with scheme, netloc port and
  1010. the path to the script.
  1011. This accepts the same arguments as the :class:`EnvironBuilder`
  1012. constructor.
  1013. .. versionchanged:: 0.5
  1014. This function is now a thin wrapper over :class:`EnvironBuilder` which
  1015. was added in 0.5. The `headers`, `environ_base`, `environ_overrides`
  1016. and `charset` parameters were added.
  1017. """
  1018. builder = EnvironBuilder(*args, **kwargs)
  1019. try:
  1020. return builder.get_environ()
  1021. finally:
  1022. builder.close()
  1023. def run_wsgi_app(
  1024. app: WSGIApplication, environ: WSGIEnvironment, buffered: bool = False
  1025. ) -> tuple[t.Iterable[bytes], str, Headers]:
  1026. """Return a tuple in the form (app_iter, status, headers) of the
  1027. application output. This works best if you pass it an application that
  1028. returns an iterator all the time.
  1029. Sometimes applications may use the `write()` callable returned
  1030. by the `start_response` function. This tries to resolve such edge
  1031. cases automatically. But if you don't get the expected output you
  1032. should set `buffered` to `True` which enforces buffering.
  1033. If passed an invalid WSGI application the behavior of this function is
  1034. undefined. Never pass non-conforming WSGI applications to this function.
  1035. :param app: the application to execute.
  1036. :param buffered: set to `True` to enforce buffering.
  1037. :return: tuple in the form ``(app_iter, status, headers)``
  1038. """
  1039. # Copy environ to ensure any mutations by the app (ProxyFix, for
  1040. # example) don't affect subsequent requests (such as redirects).
  1041. environ = _get_environ(environ).copy()
  1042. status: str
  1043. response: tuple[str, list[tuple[str, str]]] | None = None
  1044. buffer: list[bytes] = []
  1045. def start_response(status, headers, exc_info=None): # type: ignore
  1046. nonlocal response
  1047. if exc_info:
  1048. try:
  1049. raise exc_info[1].with_traceback(exc_info[2])
  1050. finally:
  1051. exc_info = None
  1052. response = (status, headers)
  1053. return buffer.append
  1054. app_rv = app(environ, start_response)
  1055. close_func = getattr(app_rv, "close", None)
  1056. app_iter: t.Iterable[bytes] = iter(app_rv)
  1057. # when buffering we emit the close call early and convert the
  1058. # application iterator into a regular list
  1059. if buffered:
  1060. try:
  1061. app_iter = list(app_iter)
  1062. finally:
  1063. if close_func is not None:
  1064. close_func()
  1065. # otherwise we iterate the application iter until we have a response, chain
  1066. # the already received data with the already collected data and wrap it in
  1067. # a new `ClosingIterator` if we need to restore a `close` callable from the
  1068. # original return value.
  1069. else:
  1070. for item in app_iter:
  1071. buffer.append(item)
  1072. if response is not None:
  1073. break
  1074. if buffer:
  1075. app_iter = chain(buffer, app_iter)
  1076. if close_func is not None and app_iter is not app_rv:
  1077. app_iter = ClosingIterator(app_iter, close_func)
  1078. status, headers = response # type: ignore
  1079. return app_iter, status, Headers(headers)
  1080. class TestResponse(Response):
  1081. """:class:`~werkzeug.wrappers.Response` subclass that provides extra
  1082. information about requests made with the test :class:`Client`.
  1083. Test client requests will always return an instance of this class.
  1084. If a custom response class is passed to the client, it is
  1085. subclassed along with this to support test information.
  1086. If the test request included large files, or if the application is
  1087. serving a file, call :meth:`close` to close any open files and
  1088. prevent Python showing a ``ResourceWarning``.
  1089. .. versionchanged:: 2.2
  1090. Set the ``default_mimetype`` to None to prevent a mimetype being
  1091. assumed if missing.
  1092. .. versionchanged:: 2.1
  1093. Response instances cannot be treated as tuples.
  1094. .. versionadded:: 2.0
  1095. Test client methods always return instances of this class.
  1096. """
  1097. default_mimetype = None
  1098. # Don't assume a mimetype, instead use whatever the response provides
  1099. request: Request
  1100. """A request object with the environ used to make the request that
  1101. resulted in this response.
  1102. """
  1103. history: tuple[TestResponse, ...]
  1104. """A list of intermediate responses. Populated when the test request
  1105. is made with ``follow_redirects`` enabled.
  1106. """
  1107. # Tell Pytest to ignore this, it's not a test class.
  1108. __test__ = False
  1109. def __init__(
  1110. self,
  1111. response: t.Iterable[bytes],
  1112. status: str,
  1113. headers: Headers,
  1114. request: Request,
  1115. history: tuple[TestResponse] = (), # type: ignore
  1116. **kwargs: t.Any,
  1117. ) -> None:
  1118. super().__init__(response, status, headers, **kwargs)
  1119. self.request = request
  1120. self.history = history
  1121. self._compat_tuple = response, status, headers
  1122. @cached_property
  1123. def text(self) -> str:
  1124. """The response data as text. A shortcut for
  1125. ``response.get_data(as_text=True)``.
  1126. .. versionadded:: 2.1
  1127. """
  1128. return self.get_data(as_text=True)
  1129. @dataclasses.dataclass
  1130. class Cookie:
  1131. """A cookie key, value, and parameters.
  1132. The class itself is not a public API. Its attributes are documented for inspection
  1133. with :meth:`.Client.get_cookie` only.
  1134. .. versionadded:: 2.3
  1135. """
  1136. key: str
  1137. """The cookie key, encoded as a client would see it."""
  1138. value: str
  1139. """The cookie key, encoded as a client would see it."""
  1140. decoded_key: str
  1141. """The cookie key, decoded as the application would set and see it."""
  1142. decoded_value: str
  1143. """The cookie value, decoded as the application would set and see it."""
  1144. expires: datetime | None
  1145. """The time at which the cookie is no longer valid."""
  1146. max_age: int | None
  1147. """The number of seconds from when the cookie was set at which it is
  1148. no longer valid.
  1149. """
  1150. domain: str
  1151. """The domain that the cookie was set for, or the request domain if not set."""
  1152. origin_only: bool
  1153. """Whether the cookie will be sent for exact domain matches only. This is ``True``
  1154. if the ``Domain`` parameter was not present.
  1155. """
  1156. path: str
  1157. """The path that the cookie was set for."""
  1158. secure: bool | None
  1159. """The ``Secure`` parameter."""
  1160. http_only: bool | None
  1161. """The ``HttpOnly`` parameter."""
  1162. same_site: str | None
  1163. """The ``SameSite`` parameter."""
  1164. def _matches_request(self, server_name: str, path: str) -> bool:
  1165. return (
  1166. server_name == self.domain
  1167. or (
  1168. not self.origin_only
  1169. and server_name.endswith(self.domain)
  1170. and server_name[: -len(self.domain)].endswith(".")
  1171. )
  1172. ) and (
  1173. path == self.path
  1174. or (
  1175. path.startswith(self.path)
  1176. and path[len(self.path) - self.path.endswith("/") :].startswith("/")
  1177. )
  1178. )
  1179. def _to_request_header(self) -> str:
  1180. return f"{self.key}={self.value}"
  1181. @classmethod
  1182. def _from_response_header(cls, server_name: str, path: str, header: str) -> te.Self:
  1183. header, _, parameters_str = header.partition(";")
  1184. key, _, value = header.partition("=")
  1185. decoded_key, decoded_value = next(parse_cookie(header).items()) # type: ignore[call-overload]
  1186. params = {}
  1187. for item in parameters_str.split(";"):
  1188. k, sep, v = item.partition("=")
  1189. params[k.strip(" \t").lower()] = v.strip(" \t") if sep else None
  1190. return cls(
  1191. key=key.strip(" \t"),
  1192. value=value.strip(" \t"),
  1193. decoded_key=decoded_key,
  1194. decoded_value=decoded_value,
  1195. expires=parse_date(params.get("expires")),
  1196. max_age=int(params["max-age"] or 0) if "max-age" in params else None,
  1197. domain=params.get("domain") or server_name,
  1198. origin_only="domain" not in params,
  1199. path=params.get("path") or path.rpartition("/")[0] or "/",
  1200. secure="secure" in params,
  1201. http_only="httponly" in params,
  1202. same_site=params.get("samesite"),
  1203. )
  1204. @property
  1205. def _storage_key(self) -> tuple[str, str, str]:
  1206. return self.domain, self.path, self.decoded_key
  1207. @property
  1208. def _should_delete(self) -> bool:
  1209. return self.max_age == 0 or (
  1210. self.expires is not None and self.expires.timestamp() == 0
  1211. )