test.py 47 KB

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