test.py 33 KB

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