test.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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(response.request.environ, query_string=qs)
  817. to_name_parts = netloc.split(":", 1)[0].split(".")
  818. from_name_parts = builder.server_name.split(".")
  819. if to_name_parts != [""]:
  820. # The new location has a host, use it for the base URL.
  821. builder.url_scheme = scheme
  822. builder.host = netloc
  823. else:
  824. # A local redirect with autocorrect_location_header=False
  825. # doesn't have a host, so use the request's host.
  826. to_name_parts = from_name_parts
  827. # Explain why a redirect to a different server name won't be followed.
  828. if to_name_parts != from_name_parts:
  829. if to_name_parts[-len(from_name_parts) :] == from_name_parts:
  830. if not self.allow_subdomain_redirects:
  831. raise RuntimeError("Following subdomain redirects is not enabled.")
  832. else:
  833. raise RuntimeError("Following external redirects is not supported.")
  834. path_parts = path.split("/")
  835. root_parts = builder.script_root.split("/")
  836. if path_parts[: len(root_parts)] == root_parts:
  837. # Strip the script root from the path.
  838. builder.path = path[len(builder.script_root) :]
  839. else:
  840. # The new location is not under the script root, so use the
  841. # whole path and clear the previous root.
  842. builder.path = path
  843. builder.script_root = ""
  844. # Only 307 and 308 preserve all of the original request.
  845. if response.status_code not in {307, 308}:
  846. # HEAD is preserved, everything else becomes GET.
  847. if builder.method != "HEAD":
  848. builder.method = "GET"
  849. # Clear the body and the headers that describe it.
  850. if builder.input_stream is not None:
  851. builder.input_stream.close()
  852. builder.input_stream = None
  853. builder.content_type = None
  854. builder.content_length = None
  855. builder.headers.pop("Transfer-Encoding", None)
  856. return self.open(builder, buffered=buffered)
  857. def open(
  858. self,
  859. *args: t.Any,
  860. as_tuple: bool = False,
  861. buffered: bool = False,
  862. follow_redirects: bool = False,
  863. **kwargs: t.Any,
  864. ) -> "TestResponse":
  865. """Generate an environ dict from the given arguments, make a
  866. request to the application using it, and return the response.
  867. :param args: Passed to :class:`EnvironBuilder` to create the
  868. environ for the request. If a single arg is passed, it can
  869. be an existing :class:`EnvironBuilder` or an environ dict.
  870. :param buffered: Convert the iterator returned by the app into
  871. a list. If the iterator has a ``close()`` method, it is
  872. called automatically.
  873. :param follow_redirects: Make additional requests to follow HTTP
  874. redirects until a non-redirect status is returned.
  875. :attr:`TestResponse.history` lists the intermediate
  876. responses.
  877. .. versionchanged:: 2.0
  878. ``as_tuple`` is deprecated and will be removed in Werkzeug
  879. 2.1. Use :attr:`TestResponse.request` and
  880. ``request.environ`` instead.
  881. .. versionchanged:: 2.0
  882. The request input stream is closed when calling
  883. ``response.close()``. Input streams for redirects are
  884. automatically closed.
  885. .. versionchanged:: 0.5
  886. If a dict is provided as file in the dict for the ``data``
  887. parameter the content type has to be called ``content_type``
  888. instead of ``mimetype``. This change was made for
  889. consistency with :class:`werkzeug.FileWrapper`.
  890. .. versionchanged:: 0.5
  891. Added the ``follow_redirects`` parameter.
  892. """
  893. request: t.Optional["Request"] = None
  894. if not kwargs and len(args) == 1:
  895. arg = args[0]
  896. if isinstance(arg, EnvironBuilder):
  897. request = arg.get_request()
  898. elif isinstance(arg, dict):
  899. request = EnvironBuilder.from_environ(arg).get_request()
  900. elif isinstance(arg, Request):
  901. request = arg
  902. if request is None:
  903. builder = EnvironBuilder(*args, **kwargs)
  904. try:
  905. request = builder.get_request()
  906. finally:
  907. builder.close()
  908. response = self.run_wsgi_app(request.environ, buffered=buffered)
  909. response = self.response_wrapper(*response, request=request)
  910. redirects = set()
  911. history: t.List["TestResponse"] = []
  912. while follow_redirects and response.status_code in {
  913. 301,
  914. 302,
  915. 303,
  916. 305,
  917. 307,
  918. 308,
  919. }:
  920. # Exhaust intermediate response bodies to ensure middleware
  921. # that returns an iterator runs any cleanup code.
  922. if not buffered:
  923. response.make_sequence()
  924. response.close()
  925. new_redirect_entry = (response.location, response.status_code)
  926. if new_redirect_entry in redirects:
  927. raise ClientRedirectError(
  928. f"Loop detected: A {response.status_code} redirect"
  929. f" to {response.location} was already made."
  930. )
  931. redirects.add(new_redirect_entry)
  932. response.history = tuple(history)
  933. history.append(response)
  934. response = self.resolve_redirect(response, buffered=buffered)
  935. else:
  936. # This is the final request after redirects, or not
  937. # following redirects.
  938. response.history = tuple(history)
  939. # Close the input stream when closing the response, in case
  940. # the input is an open temporary file.
  941. response.call_on_close(request.input_stream.close)
  942. if as_tuple:
  943. warnings.warn(
  944. "'as_tuple' is deprecated and will be removed in"
  945. " Werkzeug 2.1. Access 'response.request.environ'"
  946. " instead.",
  947. DeprecationWarning,
  948. stacklevel=2,
  949. )
  950. return request.environ, response # type: ignore
  951. return response
  952. def get(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  953. """Call :meth:`open` with ``method`` set to ``GET``."""
  954. kw["method"] = "GET"
  955. return self.open(*args, **kw)
  956. def post(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  957. """Call :meth:`open` with ``method`` set to ``POST``."""
  958. kw["method"] = "POST"
  959. return self.open(*args, **kw)
  960. def put(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  961. """Call :meth:`open` with ``method`` set to ``PUT``."""
  962. kw["method"] = "PUT"
  963. return self.open(*args, **kw)
  964. def delete(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  965. """Call :meth:`open` with ``method`` set to ``DELETE``."""
  966. kw["method"] = "DELETE"
  967. return self.open(*args, **kw)
  968. def patch(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  969. """Call :meth:`open` with ``method`` set to ``PATCH``."""
  970. kw["method"] = "PATCH"
  971. return self.open(*args, **kw)
  972. def options(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  973. """Call :meth:`open` with ``method`` set to ``OPTIONS``."""
  974. kw["method"] = "OPTIONS"
  975. return self.open(*args, **kw)
  976. def head(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  977. """Call :meth:`open` with ``method`` set to ``HEAD``."""
  978. kw["method"] = "HEAD"
  979. return self.open(*args, **kw)
  980. def trace(self, *args: t.Any, **kw: t.Any) -> "TestResponse":
  981. """Call :meth:`open` with ``method`` set to ``TRACE``."""
  982. kw["method"] = "TRACE"
  983. return self.open(*args, **kw)
  984. def __repr__(self) -> str:
  985. return f"<{type(self).__name__} {self.application!r}>"
  986. def create_environ(*args: t.Any, **kwargs: t.Any) -> "WSGIEnvironment":
  987. """Create a new WSGI environ dict based on the values passed. The first
  988. parameter should be the path of the request which defaults to '/'. The
  989. second one can either be an absolute path (in that case the host is
  990. localhost:80) or a full path to the request with scheme, netloc port and
  991. the path to the script.
  992. This accepts the same arguments as the :class:`EnvironBuilder`
  993. constructor.
  994. .. versionchanged:: 0.5
  995. This function is now a thin wrapper over :class:`EnvironBuilder` which
  996. was added in 0.5. The `headers`, `environ_base`, `environ_overrides`
  997. and `charset` parameters were added.
  998. """
  999. builder = EnvironBuilder(*args, **kwargs)
  1000. try:
  1001. return builder.get_environ()
  1002. finally:
  1003. builder.close()
  1004. def run_wsgi_app(
  1005. app: "WSGIApplication", environ: "WSGIEnvironment", buffered: bool = False
  1006. ) -> t.Tuple[t.Iterable[bytes], str, Headers]:
  1007. """Return a tuple in the form (app_iter, status, headers) of the
  1008. application output. This works best if you pass it an application that
  1009. returns an iterator all the time.
  1010. Sometimes applications may use the `write()` callable returned
  1011. by the `start_response` function. This tries to resolve such edge
  1012. cases automatically. But if you don't get the expected output you
  1013. should set `buffered` to `True` which enforces buffering.
  1014. If passed an invalid WSGI application the behavior of this function is
  1015. undefined. Never pass non-conforming WSGI applications to this function.
  1016. :param app: the application to execute.
  1017. :param buffered: set to `True` to enforce buffering.
  1018. :return: tuple in the form ``(app_iter, status, headers)``
  1019. """
  1020. # Copy environ to ensure any mutations by the app (ProxyFix, for
  1021. # example) don't affect subsequent requests (such as redirects).
  1022. environ = _get_environ(environ).copy()
  1023. status: str
  1024. response: t.Optional[t.Tuple[str, t.List[t.Tuple[str, str]]]] = None
  1025. buffer: t.List[bytes] = []
  1026. def start_response(status, headers, exc_info=None): # type: ignore
  1027. nonlocal response
  1028. if exc_info:
  1029. try:
  1030. raise exc_info[1].with_traceback(exc_info[2])
  1031. finally:
  1032. exc_info = None
  1033. response = (status, headers)
  1034. return buffer.append
  1035. app_rv = app(environ, start_response)
  1036. close_func = getattr(app_rv, "close", None)
  1037. app_iter: t.Iterable[bytes] = iter(app_rv)
  1038. # when buffering we emit the close call early and convert the
  1039. # application iterator into a regular list
  1040. if buffered:
  1041. try:
  1042. app_iter = list(app_iter)
  1043. finally:
  1044. if close_func is not None:
  1045. close_func()
  1046. # otherwise we iterate the application iter until we have a response, chain
  1047. # the already received data with the already collected data and wrap it in
  1048. # a new `ClosingIterator` if we need to restore a `close` callable from the
  1049. # original return value.
  1050. else:
  1051. for item in app_iter:
  1052. buffer.append(item)
  1053. if response is not None:
  1054. break
  1055. if buffer:
  1056. app_iter = chain(buffer, app_iter)
  1057. if close_func is not None and app_iter is not app_rv:
  1058. app_iter = ClosingIterator(app_iter, close_func)
  1059. status, headers = response # type: ignore
  1060. return app_iter, status, Headers(headers)
  1061. class TestResponse(Response):
  1062. """:class:`~werkzeug.wrappers.Response` subclass that provides extra
  1063. information about requests made with the test :class:`Client`.
  1064. Test client requests will always return an instance of this class.
  1065. If a custom response class is passed to the client, it is
  1066. subclassed along with this to support test information.
  1067. If the test request included large files, or if the application is
  1068. serving a file, call :meth:`close` to close any open files and
  1069. prevent Python showing a ``ResourceWarning``.
  1070. """
  1071. request: Request
  1072. """A request object with the environ used to make the request that
  1073. resulted in this response.
  1074. """
  1075. history: t.Tuple["TestResponse", ...]
  1076. """A list of intermediate responses. Populated when the test request
  1077. is made with ``follow_redirects`` enabled.
  1078. """
  1079. def __init__(
  1080. self,
  1081. response: t.Iterable[bytes],
  1082. status: str,
  1083. headers: Headers,
  1084. request: Request,
  1085. history: t.Tuple["TestResponse"] = (), # type: ignore
  1086. **kwargs: t.Any,
  1087. ) -> None:
  1088. super().__init__(response, status, headers, **kwargs)
  1089. self.request = request
  1090. self.history = history
  1091. self._compat_tuple = response, status, headers
  1092. def __iter__(self) -> t.Iterator:
  1093. warnings.warn(
  1094. (
  1095. "The test client no longer returns a tuple, it returns"
  1096. " a 'TestResponse'. Tuple unpacking is deprecated and"
  1097. " will be removed in Werkzeug 2.1. Access the"
  1098. " attributes 'data', 'status', and 'headers' instead."
  1099. ),
  1100. DeprecationWarning,
  1101. stacklevel=2,
  1102. )
  1103. return iter(self._compat_tuple)
  1104. def __getitem__(self, item: int) -> t.Any:
  1105. warnings.warn(
  1106. (
  1107. "The test client no longer returns a tuple, it returns"
  1108. " a 'TestResponse'. Item indexing is deprecated and"
  1109. " will be removed in Werkzeug 2.1. Access the"
  1110. " attributes 'data', 'status', and 'headers' instead."
  1111. ),
  1112. DeprecationWarning,
  1113. stacklevel=2,
  1114. )
  1115. return self._compat_tuple[item]