test.py 47 KB

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