You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

948 lines
35 KiB

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