test.py 47 KB

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