test.py 34 KB

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