test.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.test
  4. ~~~~~~~~~~~~~
  5. This module implements a client to WSGI applications for testing.
  6. :copyright: 2007 Pallets
  7. :license: BSD-3-Clause
  8. """
  9. import mimetypes
  10. import sys
  11. from io import BytesIO
  12. from itertools import chain
  13. from random import random
  14. from tempfile import TemporaryFile
  15. from time import time
  16. from ._compat import iteritems
  17. from ._compat import iterlists
  18. from ._compat import itervalues
  19. from ._compat import make_literal_wrapper
  20. from ._compat import reraise
  21. from ._compat import string_types
  22. from ._compat import text_type
  23. from ._compat import to_bytes
  24. from ._compat import wsgi_encoding_dance
  25. from ._internal import _get_environ
  26. from .datastructures import CallbackDict
  27. from .datastructures import CombinedMultiDict
  28. from .datastructures import EnvironHeaders
  29. from .datastructures import FileMultiDict
  30. from .datastructures import Headers
  31. from .datastructures import MultiDict
  32. from .http import dump_cookie
  33. from .http import dump_options_header
  34. from .http import parse_options_header
  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 import BaseRequest
  43. from .wsgi import ClosingIterator
  44. from .wsgi import get_current_url
  45. try:
  46. from urllib.request import Request as U2Request
  47. except ImportError:
  48. from urllib2 import Request as U2Request
  49. try:
  50. from http.cookiejar import CookieJar
  51. except ImportError:
  52. from cookielib import CookieJar
  53. def stream_encode_multipart(
  54. values, use_tempfile=True, threshold=1024 * 500, boundary=None, charset="utf-8"
  55. ):
  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 = "---------------WerkzeugFormPart_%s%s" % (time(), random())
  62. _closure = [BytesIO(), 0, False]
  63. if use_tempfile:
  64. def write_binary(string):
  65. stream, total_length, on_disk = _closure
  66. if on_disk:
  67. stream.write(string)
  68. else:
  69. length = len(string)
  70. if length + _closure[1] <= threshold:
  71. stream.write(string)
  72. else:
  73. new_stream = TemporaryFile("wb+")
  74. new_stream.write(stream.getvalue())
  75. new_stream.write(string)
  76. _closure[0] = new_stream
  77. _closure[2] = True
  78. _closure[1] = total_length + length
  79. else:
  80. write_binary = _closure[0].write
  81. def write(string):
  82. write_binary(string.encode(charset))
  83. if not isinstance(values, MultiDict):
  84. values = MultiDict(values)
  85. for key, values in iterlists(values):
  86. for value in values:
  87. write('--%s\r\nContent-Disposition: form-data; name="%s"' % (boundary, key))
  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. if filename is not None:
  99. write('; filename="%s"\r\n' % filename)
  100. else:
  101. write("\r\n")
  102. write("Content-Type: %s\r\n\r\n" % content_type)
  103. while 1:
  104. chunk = reader(16384)
  105. if not chunk:
  106. break
  107. write_binary(chunk)
  108. else:
  109. if not isinstance(value, string_types):
  110. value = str(value)
  111. value = to_bytes(value, charset)
  112. write("\r\n\r\n")
  113. write_binary(value)
  114. write("\r\n")
  115. write("--%s--\r\n" % boundary)
  116. length = int(_closure[0].tell())
  117. _closure[0].seek(0)
  118. return _closure[0], length, boundary
  119. def encode_multipart(values, boundary=None, charset="utf-8"):
  120. """Like `stream_encode_multipart` but returns a tuple in the form
  121. (``boundary``, ``data``) where data is a bytestring.
  122. """
  123. stream, length, boundary = stream_encode_multipart(
  124. values, use_tempfile=False, boundary=boundary, charset=charset
  125. )
  126. return boundary, stream.read()
  127. class _TestCookieHeaders(object):
  128. """A headers adapter for cookielib
  129. """
  130. def __init__(self, headers):
  131. self.headers = headers
  132. def getheaders(self, name):
  133. headers = []
  134. name = name.lower()
  135. for k, v in self.headers:
  136. if k.lower() == name:
  137. headers.append(v)
  138. return headers
  139. def get_all(self, name, default=None):
  140. rv = []
  141. for k, v in self.headers:
  142. if k.lower() == name.lower():
  143. rv.append(v)
  144. return rv or default or []
  145. class _TestCookieResponse(object):
  146. """Something that looks like a httplib.HTTPResponse, but is actually just an
  147. adapter for our test responses to make them available for cookielib.
  148. """
  149. def __init__(self, headers):
  150. self.headers = _TestCookieHeaders(headers)
  151. def info(self):
  152. return self.headers
  153. class _TestCookieJar(CookieJar):
  154. """A cookielib.CookieJar modified to inject and read cookie headers from
  155. and to wsgi environments, and wsgi application responses.
  156. """
  157. def inject_wsgi(self, environ):
  158. """Inject the cookies as client headers into the server's wsgi
  159. environment.
  160. """
  161. cvals = ["%s=%s" % (c.name, c.value) for c in self]
  162. if cvals:
  163. environ["HTTP_COOKIE"] = "; ".join(cvals)
  164. else:
  165. environ.pop("HTTP_COOKIE", None)
  166. def extract_wsgi(self, environ, headers):
  167. """Extract the server's set-cookie headers as cookies into the
  168. cookie jar.
  169. """
  170. self.extract_cookies(
  171. _TestCookieResponse(headers), U2Request(get_current_url(environ))
  172. )
  173. def _iter_data(data):
  174. """Iterates over a `dict` or :class:`MultiDict` yielding all keys and
  175. values.
  176. This is used to iterate over the data passed to the
  177. :class:`EnvironBuilder`.
  178. """
  179. if isinstance(data, MultiDict):
  180. for key, values in iterlists(data):
  181. for value in values:
  182. yield key, value
  183. else:
  184. for key, values in iteritems(data):
  185. if isinstance(values, list):
  186. for value in values:
  187. yield key, value
  188. else:
  189. yield key, values
  190. class EnvironBuilder(object):
  191. """This class can be used to conveniently create a WSGI environment
  192. for testing purposes. It can be used to quickly create WSGI environments
  193. or request objects from arbitrary data.
  194. The signature of this class is also used in some other places as of
  195. Werkzeug 0.5 (:func:`create_environ`, :meth:`BaseResponse.from_values`,
  196. :meth:`Client.open`). Because of this most of the functionality is
  197. available through the constructor alone.
  198. Files and regular form data can be manipulated independently of each
  199. other with the :attr:`form` and :attr:`files` attributes, but are
  200. passed with the same argument to the constructor: `data`.
  201. `data` can be any of these values:
  202. - a `str` or `bytes` object: The object is converted into an
  203. :attr:`input_stream`, the :attr:`content_length` is set and you have to
  204. provide a :attr:`content_type`.
  205. - a `dict` or :class:`MultiDict`: The keys have to be strings. The values
  206. have to be either any of the following objects, or a list of any of the
  207. following objects:
  208. - a :class:`file`-like object: These are converted into
  209. :class:`FileStorage` objects automatically.
  210. - a `tuple`: The :meth:`~FileMultiDict.add_file` method is called
  211. with the key and the unpacked `tuple` items as positional
  212. arguments.
  213. - a `str`: The string is set as form data for the associated key.
  214. - a file-like object: The object content is loaded in memory and then
  215. handled like a regular `str` or a `bytes`.
  216. :param path: the path of the request. In the WSGI environment this will
  217. end up as `PATH_INFO`. If the `query_string` is not defined
  218. and there is a question mark in the `path` everything after
  219. it is used as query string.
  220. :param base_url: the base URL is a URL that is used to extract the WSGI
  221. URL scheme, host (server name + server port) and the
  222. script root (`SCRIPT_NAME`).
  223. :param query_string: an optional string or dict with URL parameters.
  224. :param method: the HTTP method to use, defaults to `GET`.
  225. :param input_stream: an optional input stream. Do not specify this and
  226. `data`. As soon as an input stream is set you can't
  227. modify :attr:`args` and :attr:`files` unless you
  228. set the :attr:`input_stream` to `None` again.
  229. :param content_type: The content type for the request. As of 0.5 you
  230. don't have to provide this when specifying files
  231. and form data via `data`.
  232. :param content_length: The content length for the request. You don't
  233. have to specify this when providing data via
  234. `data`.
  235. :param errors_stream: an optional error stream that is used for
  236. `wsgi.errors`. Defaults to :data:`stderr`.
  237. :param multithread: controls `wsgi.multithread`. Defaults to `False`.
  238. :param multiprocess: controls `wsgi.multiprocess`. Defaults to `False`.
  239. :param run_once: controls `wsgi.run_once`. Defaults to `False`.
  240. :param headers: an optional list or :class:`Headers` object of headers.
  241. :param data: a string or dict of form data or a file-object.
  242. See explanation above.
  243. :param json: An object to be serialized and assigned to ``data``.
  244. Defaults the content type to ``"application/json"``.
  245. Serialized with the function assigned to :attr:`json_dumps`.
  246. :param environ_base: an optional dict of environment defaults.
  247. :param environ_overrides: an optional dict of environment overrides.
  248. :param charset: the charset used to encode unicode data.
  249. .. versionadded:: 0.15
  250. The ``json`` param and :meth:`json_dumps` method.
  251. .. versionadded:: 0.15
  252. The environ has keys ``REQUEST_URI`` and ``RAW_URI`` containing
  253. the path before perecent-decoding. This is not part of the WSGI
  254. PEP, but many WSGI servers include it.
  255. .. versionchanged:: 0.6
  256. ``path`` and ``base_url`` can now be unicode strings that are
  257. encoded with :func:`iri_to_uri`.
  258. """
  259. #: the server protocol to use. defaults to HTTP/1.1
  260. server_protocol = "HTTP/1.1"
  261. #: the wsgi version to use. defaults to (1, 0)
  262. wsgi_version = (1, 0)
  263. #: the default request class for :meth:`get_request`
  264. request_class = BaseRequest
  265. import json
  266. #: The serialization function used when ``json`` is passed.
  267. json_dumps = staticmethod(json.dumps)
  268. del json
  269. def __init__(
  270. self,
  271. path="/",
  272. base_url=None,
  273. query_string=None,
  274. method="GET",
  275. input_stream=None,
  276. content_type=None,
  277. content_length=None,
  278. errors_stream=None,
  279. multithread=False,
  280. multiprocess=False,
  281. run_once=False,
  282. headers=None,
  283. data=None,
  284. environ_base=None,
  285. environ_overrides=None,
  286. charset="utf-8",
  287. mimetype=None,
  288. json=None,
  289. ):
  290. path_s = make_literal_wrapper(path)
  291. if query_string is not None and path_s("?") in path:
  292. raise ValueError("Query string is defined in the path and as an argument")
  293. if query_string is None and path_s("?") in path:
  294. path, query_string = path.split(path_s("?"), 1)
  295. self.charset = charset
  296. self.path = iri_to_uri(path)
  297. if base_url is not None:
  298. base_url = url_fix(iri_to_uri(base_url, charset), charset)
  299. self.base_url = base_url
  300. if isinstance(query_string, (bytes, text_type)):
  301. self.query_string = query_string
  302. else:
  303. if query_string is None:
  304. query_string = MultiDict()
  305. elif not isinstance(query_string, MultiDict):
  306. query_string = MultiDict(query_string)
  307. self.args = query_string
  308. self.method = method
  309. if headers is None:
  310. headers = Headers()
  311. elif not isinstance(headers, Headers):
  312. headers = Headers(headers)
  313. self.headers = headers
  314. if content_type is not None:
  315. self.content_type = content_type
  316. if errors_stream is None:
  317. errors_stream = sys.stderr
  318. self.errors_stream = errors_stream
  319. self.multithread = multithread
  320. self.multiprocess = multiprocess
  321. self.run_once = run_once
  322. self.environ_base = environ_base
  323. self.environ_overrides = environ_overrides
  324. self.input_stream = input_stream
  325. self.content_length = content_length
  326. self.closed = False
  327. if json is not None:
  328. if data is not None:
  329. raise TypeError("can't provide both json and data")
  330. data = self.json_dumps(json)
  331. if self.content_type is None:
  332. self.content_type = "application/json"
  333. if data:
  334. if input_stream is not None:
  335. raise TypeError("can't provide input stream and data")
  336. if hasattr(data, "read"):
  337. data = data.read()
  338. if isinstance(data, text_type):
  339. data = data.encode(self.charset)
  340. if isinstance(data, bytes):
  341. self.input_stream = BytesIO(data)
  342. if self.content_length is None:
  343. self.content_length = len(data)
  344. else:
  345. for key, value in _iter_data(data):
  346. if isinstance(value, (tuple, dict)) or hasattr(value, "read"):
  347. self._add_file_from_data(key, value)
  348. else:
  349. self.form.setlistdefault(key).append(value)
  350. if mimetype is not None:
  351. self.mimetype = mimetype
  352. @classmethod
  353. def from_environ(cls, environ, **kwargs):
  354. """Turn an environ dict back into a builder. Any extra kwargs
  355. override the args extracted from the environ.
  356. .. versionadded:: 0.15
  357. """
  358. headers = Headers(EnvironHeaders(environ))
  359. out = {
  360. "path": environ["PATH_INFO"],
  361. "base_url": cls._make_base_url(
  362. environ["wsgi.url_scheme"], headers.pop("Host"), environ["SCRIPT_NAME"]
  363. ),
  364. "query_string": environ["QUERY_STRING"],
  365. "method": environ["REQUEST_METHOD"],
  366. "input_stream": environ["wsgi.input"],
  367. "content_type": headers.pop("Content-Type", None),
  368. "content_length": headers.pop("Content-Length", None),
  369. "errors_stream": environ["wsgi.errors"],
  370. "multithread": environ["wsgi.multithread"],
  371. "multiprocess": environ["wsgi.multiprocess"],
  372. "run_once": environ["wsgi.run_once"],
  373. "headers": headers,
  374. }
  375. out.update(kwargs)
  376. return cls(**out)
  377. def _add_file_from_data(self, key, value):
  378. """Called in the EnvironBuilder to add files from the data dict."""
  379. if isinstance(value, tuple):
  380. self.files.add_file(key, *value)
  381. else:
  382. self.files.add_file(key, value)
  383. @staticmethod
  384. def _make_base_url(scheme, host, script_root):
  385. return url_unparse((scheme, host, script_root, "", "")).rstrip("/") + "/"
  386. @property
  387. def base_url(self):
  388. """The base URL is used to extract the URL scheme, host name,
  389. port, and root path.
  390. """
  391. return self._make_base_url(self.url_scheme, self.host, self.script_root)
  392. @base_url.setter
  393. def base_url(self, value):
  394. if value is None:
  395. scheme = "http"
  396. netloc = "localhost"
  397. script_root = ""
  398. else:
  399. scheme, netloc, script_root, qs, anchor = url_parse(value)
  400. if qs or anchor:
  401. raise ValueError("base url must not contain a query string or fragment")
  402. self.script_root = script_root.rstrip("/")
  403. self.host = netloc
  404. self.url_scheme = scheme
  405. @property
  406. def content_type(self):
  407. """The content type for the request. Reflected from and to
  408. the :attr:`headers`. Do not set if you set :attr:`files` or
  409. :attr:`form` for auto detection.
  410. """
  411. ct = self.headers.get("Content-Type")
  412. if ct is None and not self._input_stream:
  413. if self._files:
  414. return "multipart/form-data"
  415. if self._form:
  416. return "application/x-www-form-urlencoded"
  417. return None
  418. return ct
  419. @content_type.setter
  420. def content_type(self, value):
  421. if value is None:
  422. self.headers.pop("Content-Type", None)
  423. else:
  424. self.headers["Content-Type"] = value
  425. @property
  426. def mimetype(self):
  427. """The mimetype (content type without charset etc.)
  428. .. versionadded:: 0.14
  429. """
  430. ct = self.content_type
  431. return ct.split(";")[0].strip() if ct else None
  432. @mimetype.setter
  433. def mimetype(self, value):
  434. self.content_type = get_content_type(value, self.charset)
  435. @property
  436. def mimetype_params(self):
  437. """ The mimetype parameters as dict. For example if the
  438. content type is ``text/html; charset=utf-8`` the params would be
  439. ``{'charset': 'utf-8'}``.
  440. .. versionadded:: 0.14
  441. """
  442. def on_update(d):
  443. self.headers["Content-Type"] = dump_options_header(self.mimetype, d)
  444. d = parse_options_header(self.headers.get("content-type", ""))[1]
  445. return CallbackDict(d, on_update)
  446. @property
  447. def content_length(self):
  448. """The content length as integer. Reflected from and to the
  449. :attr:`headers`. Do not set if you set :attr:`files` or
  450. :attr:`form` for auto detection.
  451. """
  452. return self.headers.get("Content-Length", type=int)
  453. @content_length.setter
  454. def content_length(self, value):
  455. if value is None:
  456. self.headers.pop("Content-Length", None)
  457. else:
  458. self.headers["Content-Length"] = str(value)
  459. def _get_form(self, name, storage):
  460. """Common behavior for getting the :attr:`form` and
  461. :attr:`files` properties.
  462. :param name: Name of the internal cached attribute.
  463. :param storage: Storage class used for the data.
  464. """
  465. if self.input_stream is not None:
  466. raise AttributeError("an input stream is defined")
  467. rv = getattr(self, name)
  468. if rv is None:
  469. rv = storage()
  470. setattr(self, name, rv)
  471. return rv
  472. def _set_form(self, name, value):
  473. """Common behavior for setting the :attr:`form` and
  474. :attr:`files` properties.
  475. :param name: Name of the internal cached attribute.
  476. :param value: Value to assign to the attribute.
  477. """
  478. self._input_stream = None
  479. setattr(self, name, value)
  480. @property
  481. def form(self):
  482. """A :class:`MultiDict` of form values."""
  483. return self._get_form("_form", MultiDict)
  484. @form.setter
  485. def form(self, value):
  486. self._set_form("_form", value)
  487. @property
  488. def files(self):
  489. """A :class:`FileMultiDict` of uploaded files. Use
  490. :meth:`~FileMultiDict.add_file` to add new files.
  491. """
  492. return self._get_form("_files", FileMultiDict)
  493. @files.setter
  494. def files(self, value):
  495. self._set_form("_files", value)
  496. @property
  497. def input_stream(self):
  498. """An optional input stream. If you set this it will clear
  499. :attr:`form` and :attr:`files`.
  500. """
  501. return self._input_stream
  502. @input_stream.setter
  503. def input_stream(self, value):
  504. self._input_stream = value
  505. self._form = None
  506. self._files = None
  507. @property
  508. def query_string(self):
  509. """The query string. If you set this to a string
  510. :attr:`args` will no longer be available.
  511. """
  512. if self._query_string is None:
  513. if self._args is not None:
  514. return url_encode(self._args, charset=self.charset)
  515. return ""
  516. return self._query_string
  517. @query_string.setter
  518. def query_string(self, value):
  519. self._query_string = value
  520. self._args = None
  521. @property
  522. def args(self):
  523. """The URL arguments as :class:`MultiDict`."""
  524. if self._query_string is not None:
  525. raise AttributeError("a query string is defined")
  526. if self._args is None:
  527. self._args = MultiDict()
  528. return self._args
  529. @args.setter
  530. def args(self, value):
  531. self._query_string = None
  532. self._args = value
  533. @property
  534. def server_name(self):
  535. """The server name (read-only, use :attr:`host` to set)"""
  536. return self.host.split(":", 1)[0]
  537. @property
  538. def server_port(self):
  539. """The server port as integer (read-only, use :attr:`host` to set)"""
  540. pieces = self.host.split(":", 1)
  541. if len(pieces) == 2 and pieces[1].isdigit():
  542. return int(pieces[1])
  543. if self.url_scheme == "https":
  544. return 443
  545. return 80
  546. def __del__(self):
  547. try:
  548. self.close()
  549. except Exception:
  550. pass
  551. def close(self):
  552. """Closes all files. If you put real :class:`file` objects into the
  553. :attr:`files` dict you can call this method to automatically close
  554. them all in one go.
  555. """
  556. if self.closed:
  557. return
  558. try:
  559. files = itervalues(self.files)
  560. except AttributeError:
  561. files = ()
  562. for f in files:
  563. try:
  564. f.close()
  565. except Exception:
  566. pass
  567. self.closed = True
  568. def get_environ(self):
  569. """Return the built environ.
  570. .. versionchanged:: 0.15
  571. The content type and length headers are set based on
  572. input stream detection. Previously this only set the WSGI
  573. keys.
  574. """
  575. input_stream = self.input_stream
  576. content_length = self.content_length
  577. mimetype = self.mimetype
  578. content_type = self.content_type
  579. if input_stream is not None:
  580. start_pos = input_stream.tell()
  581. input_stream.seek(0, 2)
  582. end_pos = input_stream.tell()
  583. input_stream.seek(start_pos)
  584. content_length = end_pos - start_pos
  585. elif mimetype == "multipart/form-data":
  586. values = CombinedMultiDict([self.form, self.files])
  587. input_stream, content_length, boundary = stream_encode_multipart(
  588. values, charset=self.charset
  589. )
  590. content_type = mimetype + '; boundary="%s"' % boundary
  591. elif mimetype == "application/x-www-form-urlencoded":
  592. # XXX: py2v3 review
  593. values = url_encode(self.form, charset=self.charset)
  594. values = values.encode("ascii")
  595. content_length = len(values)
  596. input_stream = BytesIO(values)
  597. else:
  598. input_stream = BytesIO()
  599. result = {}
  600. if self.environ_base:
  601. result.update(self.environ_base)
  602. def _path_encode(x):
  603. return wsgi_encoding_dance(url_unquote(x, self.charset), self.charset)
  604. qs = wsgi_encoding_dance(self.query_string)
  605. result.update(
  606. {
  607. "REQUEST_METHOD": self.method,
  608. "SCRIPT_NAME": _path_encode(self.script_root),
  609. "PATH_INFO": _path_encode(self.path),
  610. "QUERY_STRING": qs,
  611. # Non-standard, added by mod_wsgi, uWSGI
  612. "REQUEST_URI": wsgi_encoding_dance(self.path),
  613. # Non-standard, added by gunicorn
  614. "RAW_URI": wsgi_encoding_dance(self.path),
  615. "SERVER_NAME": self.server_name,
  616. "SERVER_PORT": str(self.server_port),
  617. "HTTP_HOST": self.host,
  618. "SERVER_PROTOCOL": self.server_protocol,
  619. "wsgi.version": self.wsgi_version,
  620. "wsgi.url_scheme": self.url_scheme,
  621. "wsgi.input": input_stream,
  622. "wsgi.errors": self.errors_stream,
  623. "wsgi.multithread": self.multithread,
  624. "wsgi.multiprocess": self.multiprocess,
  625. "wsgi.run_once": self.run_once,
  626. }
  627. )
  628. headers = self.headers.copy()
  629. if content_type is not None:
  630. result["CONTENT_TYPE"] = content_type
  631. headers.set("Content-Type", content_type)
  632. if content_length is not None:
  633. result["CONTENT_LENGTH"] = str(content_length)
  634. headers.set("Content-Length", content_length)
  635. for key, value in headers.to_wsgi_list():
  636. result["HTTP_%s" % key.upper().replace("-", "_")] = value
  637. if self.environ_overrides:
  638. result.update(self.environ_overrides)
  639. return result
  640. def get_request(self, cls=None):
  641. """Returns a request with the data. If the request class is not
  642. specified :attr:`request_class` is used.
  643. :param cls: The request wrapper to use.
  644. """
  645. if cls is None:
  646. cls = self.request_class
  647. return cls(self.get_environ())
  648. class ClientRedirectError(Exception):
  649. """If a redirect loop is detected when using follow_redirects=True with
  650. the :cls:`Client`, then this exception is raised.
  651. """
  652. class Client(object):
  653. """This class allows you to send requests to a wrapped application.
  654. The response wrapper can be a class or factory function that takes
  655. three arguments: app_iter, status and headers. The default response
  656. wrapper just returns a tuple.
  657. Example::
  658. class ClientResponse(BaseResponse):
  659. ...
  660. client = Client(MyApplication(), response_wrapper=ClientResponse)
  661. The use_cookies parameter indicates whether cookies should be stored and
  662. sent for subsequent requests. This is True by default, but passing False
  663. will disable this behaviour.
  664. If you want to request some subdomain of your application you may set
  665. `allow_subdomain_redirects` to `True` as if not no external redirects
  666. are allowed.
  667. .. versionadded:: 0.5
  668. `use_cookies` is new in this version. Older versions did not provide
  669. builtin cookie support.
  670. .. versionadded:: 0.14
  671. The `mimetype` parameter was added.
  672. .. versionadded:: 0.15
  673. The ``json`` parameter.
  674. """
  675. def __init__(
  676. self,
  677. application,
  678. response_wrapper=None,
  679. use_cookies=True,
  680. allow_subdomain_redirects=False,
  681. ):
  682. self.application = application
  683. self.response_wrapper = response_wrapper
  684. if use_cookies:
  685. self.cookie_jar = _TestCookieJar()
  686. else:
  687. self.cookie_jar = None
  688. self.allow_subdomain_redirects = allow_subdomain_redirects
  689. def set_cookie(
  690. self,
  691. server_name,
  692. key,
  693. value="",
  694. max_age=None,
  695. expires=None,
  696. path="/",
  697. domain=None,
  698. secure=None,
  699. httponly=False,
  700. samesite=None,
  701. charset="utf-8",
  702. ):
  703. """Sets a cookie in the client's cookie jar. The server name
  704. is required and has to match the one that is also passed to
  705. the open call.
  706. """
  707. assert self.cookie_jar is not None, "cookies disabled"
  708. header = dump_cookie(
  709. key,
  710. value,
  711. max_age,
  712. expires,
  713. path,
  714. domain,
  715. secure,
  716. httponly,
  717. charset,
  718. samesite=samesite,
  719. )
  720. environ = create_environ(path, base_url="http://" + server_name)
  721. headers = [("Set-Cookie", header)]
  722. self.cookie_jar.extract_wsgi(environ, headers)
  723. def delete_cookie(self, server_name, key, path="/", domain=None):
  724. """Deletes a cookie in the test client."""
  725. self.set_cookie(
  726. server_name, key, expires=0, max_age=0, path=path, domain=domain
  727. )
  728. def run_wsgi_app(self, environ, buffered=False):
  729. """Runs the wrapped WSGI app with the given environment."""
  730. if self.cookie_jar is not None:
  731. self.cookie_jar.inject_wsgi(environ)
  732. rv = run_wsgi_app(self.application, environ, buffered=buffered)
  733. if self.cookie_jar is not None:
  734. self.cookie_jar.extract_wsgi(environ, rv[2])
  735. return rv
  736. def resolve_redirect(self, response, new_location, environ, buffered=False):
  737. """Perform a new request to the location given by the redirect
  738. response to the previous request.
  739. """
  740. scheme, netloc, path, qs, anchor = url_parse(new_location)
  741. builder = EnvironBuilder.from_environ(environ, query_string=qs)
  742. to_name_parts = netloc.split(":", 1)[0].split(".")
  743. from_name_parts = builder.server_name.split(".")
  744. if to_name_parts != [""]:
  745. # The new location has a host, use it for the base URL.
  746. builder.url_scheme = scheme
  747. builder.host = netloc
  748. else:
  749. # A local redirect with autocorrect_location_header=False
  750. # doesn't have a host, so use the request's host.
  751. to_name_parts = from_name_parts
  752. # Explain why a redirect to a different server name won't be followed.
  753. if to_name_parts != from_name_parts:
  754. if to_name_parts[-len(from_name_parts) :] == from_name_parts:
  755. if not self.allow_subdomain_redirects:
  756. raise RuntimeError("Following subdomain redirects is not enabled.")
  757. else:
  758. raise RuntimeError("Following external redirects is not supported.")
  759. path_parts = path.split("/")
  760. root_parts = builder.script_root.split("/")
  761. if path_parts[: len(root_parts)] == root_parts:
  762. # Strip the script root from the path.
  763. builder.path = path[len(builder.script_root) :]
  764. else:
  765. # The new location is not under the script root, so use the
  766. # whole path and clear the previous root.
  767. builder.path = path
  768. builder.script_root = ""
  769. status_code = int(response[1].split(None, 1)[0])
  770. # Only 307 and 308 preserve all of the original request.
  771. if status_code not in {307, 308}:
  772. # HEAD is preserved, everything else becomes GET.
  773. if builder.method != "HEAD":
  774. builder.method = "GET"
  775. # Clear the body and the headers that describe it.
  776. builder.input_stream = None
  777. builder.content_type = None
  778. builder.content_length = None
  779. builder.headers.pop("Transfer-Encoding", None)
  780. # Disable the response wrapper while handling redirects. Not
  781. # thread safe, but the client should not be shared anyway.
  782. old_response_wrapper = self.response_wrapper
  783. self.response_wrapper = None
  784. try:
  785. return self.open(builder, as_tuple=True, buffered=buffered)
  786. finally:
  787. self.response_wrapper = old_response_wrapper
  788. def open(self, *args, **kwargs):
  789. """Takes the same arguments as the :class:`EnvironBuilder` class with
  790. some additions: You can provide a :class:`EnvironBuilder` or a WSGI
  791. environment as only argument instead of the :class:`EnvironBuilder`
  792. arguments and two optional keyword arguments (`as_tuple`, `buffered`)
  793. that change the type of the return value or the way the application is
  794. executed.
  795. .. versionchanged:: 0.5
  796. If a dict is provided as file in the dict for the `data` parameter
  797. the content type has to be called `content_type` now instead of
  798. `mimetype`. This change was made for consistency with
  799. :class:`werkzeug.FileWrapper`.
  800. The `follow_redirects` parameter was added to :func:`open`.
  801. Additional parameters:
  802. :param as_tuple: Returns a tuple in the form ``(environ, result)``
  803. :param buffered: Set this to True to buffer the application run.
  804. This will automatically close the application for
  805. you as well.
  806. :param follow_redirects: Set this to True if the `Client` should
  807. follow HTTP redirects.
  808. """
  809. as_tuple = kwargs.pop("as_tuple", False)
  810. buffered = kwargs.pop("buffered", False)
  811. follow_redirects = kwargs.pop("follow_redirects", False)
  812. environ = None
  813. if not kwargs and len(args) == 1:
  814. if isinstance(args[0], EnvironBuilder):
  815. environ = args[0].get_environ()
  816. elif isinstance(args[0], dict):
  817. environ = args[0]
  818. if environ is None:
  819. builder = EnvironBuilder(*args, **kwargs)
  820. try:
  821. environ = builder.get_environ()
  822. finally:
  823. builder.close()
  824. response = self.run_wsgi_app(environ.copy(), buffered=buffered)
  825. # handle redirects
  826. redirect_chain = []
  827. while 1:
  828. status_code = int(response[1].split(None, 1)[0])
  829. if (
  830. status_code not in {301, 302, 303, 305, 307, 308}
  831. or not follow_redirects
  832. ):
  833. break
  834. # Exhaust intermediate response bodies to ensure middleware
  835. # that returns an iterator runs any cleanup code.
  836. if not buffered:
  837. for _ in response[0]:
  838. pass
  839. new_location = response[2]["location"]
  840. new_redirect_entry = (new_location, status_code)
  841. if new_redirect_entry in redirect_chain:
  842. raise ClientRedirectError("loop detected")
  843. redirect_chain.append(new_redirect_entry)
  844. environ, response = self.resolve_redirect(
  845. response, new_location, environ, buffered=buffered
  846. )
  847. if self.response_wrapper is not None:
  848. response = self.response_wrapper(*response)
  849. if as_tuple:
  850. return environ, response
  851. return response
  852. def get(self, *args, **kw):
  853. """Like open but method is enforced to GET."""
  854. kw["method"] = "GET"
  855. return self.open(*args, **kw)
  856. def patch(self, *args, **kw):
  857. """Like open but method is enforced to PATCH."""
  858. kw["method"] = "PATCH"
  859. return self.open(*args, **kw)
  860. def post(self, *args, **kw):
  861. """Like open but method is enforced to POST."""
  862. kw["method"] = "POST"
  863. return self.open(*args, **kw)
  864. def head(self, *args, **kw):
  865. """Like open but method is enforced to HEAD."""
  866. kw["method"] = "HEAD"
  867. return self.open(*args, **kw)
  868. def put(self, *args, **kw):
  869. """Like open but method is enforced to PUT."""
  870. kw["method"] = "PUT"
  871. return self.open(*args, **kw)
  872. def delete(self, *args, **kw):
  873. """Like open but method is enforced to DELETE."""
  874. kw["method"] = "DELETE"
  875. return self.open(*args, **kw)
  876. def options(self, *args, **kw):
  877. """Like open but method is enforced to OPTIONS."""
  878. kw["method"] = "OPTIONS"
  879. return self.open(*args, **kw)
  880. def trace(self, *args, **kw):
  881. """Like open but method is enforced to TRACE."""
  882. kw["method"] = "TRACE"
  883. return self.open(*args, **kw)
  884. def __repr__(self):
  885. return "<%s %r>" % (self.__class__.__name__, self.application)
  886. def create_environ(*args, **kwargs):
  887. """Create a new WSGI environ dict based on the values passed. The first
  888. parameter should be the path of the request which defaults to '/'. The
  889. second one can either be an absolute path (in that case the host is
  890. localhost:80) or a full path to the request with scheme, netloc port and
  891. the path to the script.
  892. This accepts the same arguments as the :class:`EnvironBuilder`
  893. constructor.
  894. .. versionchanged:: 0.5
  895. This function is now a thin wrapper over :class:`EnvironBuilder` which
  896. was added in 0.5. The `headers`, `environ_base`, `environ_overrides`
  897. and `charset` parameters were added.
  898. """
  899. builder = EnvironBuilder(*args, **kwargs)
  900. try:
  901. return builder.get_environ()
  902. finally:
  903. builder.close()
  904. def run_wsgi_app(app, environ, buffered=False):
  905. """Return a tuple in the form (app_iter, status, headers) of the
  906. application output. This works best if you pass it an application that
  907. returns an iterator all the time.
  908. Sometimes applications may use the `write()` callable returned
  909. by the `start_response` function. This tries to resolve such edge
  910. cases automatically. But if you don't get the expected output you
  911. should set `buffered` to `True` which enforces buffering.
  912. If passed an invalid WSGI application the behavior of this function is
  913. undefined. Never pass non-conforming WSGI applications to this function.
  914. :param app: the application to execute.
  915. :param buffered: set to `True` to enforce buffering.
  916. :return: tuple in the form ``(app_iter, status, headers)``
  917. """
  918. environ = _get_environ(environ)
  919. response = []
  920. buffer = []
  921. def start_response(status, headers, exc_info=None):
  922. if exc_info is not None:
  923. reraise(*exc_info)
  924. response[:] = [status, headers]
  925. return buffer.append
  926. app_rv = app(environ, start_response)
  927. close_func = getattr(app_rv, "close", None)
  928. app_iter = iter(app_rv)
  929. # when buffering we emit the close call early and convert the
  930. # application iterator into a regular list
  931. if buffered:
  932. try:
  933. app_iter = list(app_iter)
  934. finally:
  935. if close_func is not None:
  936. close_func()
  937. # otherwise we iterate the application iter until we have a response, chain
  938. # the already received data with the already collected data and wrap it in
  939. # a new `ClosingIterator` if we need to restore a `close` callable from the
  940. # original return value.
  941. else:
  942. for item in app_iter:
  943. buffer.append(item)
  944. if response:
  945. break
  946. if buffer:
  947. app_iter = chain(buffer, app_iter)
  948. if close_func is not None and app_iter is not app_rv:
  949. app_iter = ClosingIterator(app_iter, close_func)
  950. return app_iter, response[0], Headers(response[1])