test.py 40 KB

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