testing.py
This file
Path
src/flask/testing.py
280 lines · 10.1 KiB · Python
Last changed by
Merge pull request #4445 from pallets/override-redirectDavid Lordbefore adoptione06dad6
History of this fileTake it
1import typing as t2from contextlib import contextmanager3from copy import copy4from types import TracebackType56import werkzeug.test7from click.testing import CliRunner8from werkzeug.test import Client9from werkzeug.urls import url_parse10from werkzeug.wrappers import Request as BaseRequest1112from .cli import ScriptInfo13from .globals import _request_ctx_stack14from .json import dumps as json_dumps15from .sessions import SessionMixin1617if t.TYPE_CHECKING:18 from werkzeug.test import TestResponse1920 from .app import Flask212223class EnvironBuilder(werkzeug.test.EnvironBuilder):24 """An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the25 application.2627 :param app: The Flask application to configure the environment from.28 :param path: URL path being requested.29 :param base_url: Base URL where the app is being served, which30 ``path`` is relative to. If not given, built from31 :data:`PREFERRED_URL_SCHEME`, ``subdomain``,32 :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.33 :param subdomain: Subdomain name to append to :data:`SERVER_NAME`.34 :param url_scheme: Scheme to use instead of35 :data:`PREFERRED_URL_SCHEME`.36 :param json: If given, this is serialized as JSON and passed as37 ``data``. Also defaults ``content_type`` to38 ``application/json``.39 :param args: other positional arguments passed to40 :class:`~werkzeug.test.EnvironBuilder`.41 :param kwargs: other keyword arguments passed to42 :class:`~werkzeug.test.EnvironBuilder`.43 """4445 def __init__(46 self,47 app: "Flask",48 path: str = "/",49 base_url: t.Optional[str] = None,50 subdomain: t.Optional[str] = None,51 url_scheme: t.Optional[str] = None,52 *args: t.Any,53 **kwargs: t.Any,54 ) -> None:55 assert not (base_url or subdomain or url_scheme) or (56 base_url is not None57 ) != bool(58 subdomain or url_scheme59 ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'6061 if base_url is None:62 http_host = app.config.get("SERVER_NAME") or "localhost"63 app_root = app.config["APPLICATION_ROOT"]6465 if subdomain:66 http_host = f"{subdomain}.{http_host}"6768 if url_scheme is None:69 url_scheme = app.config["PREFERRED_URL_SCHEME"]7071 url = url_parse(path)72 base_url = (73 f"{url.scheme or url_scheme}://{url.netloc or http_host}"74 f"/{app_root.lstrip('/')}"75 )76 path = url.path7778 if url.query:79 sep = b"?" if isinstance(url.query, bytes) else "?"80 path += sep + url.query8182 self.app = app83 super().__init__(path, base_url, *args, **kwargs)8485 def json_dumps(self, obj: t.Any, **kwargs: t.Any) -> str: # type: ignore86 """Serialize ``obj`` to a JSON-formatted string.8788 The serialization will be configured according to the config associated89 with this EnvironBuilder's ``app``.90 """91 kwargs.setdefault("app", self.app)92 return json_dumps(obj, **kwargs)939495class FlaskClient(Client):96 """Works like a regular Werkzeug test client but has some knowledge about97 how Flask works to defer the cleanup of the request context stack to the98 end of a ``with`` body when used in a ``with`` statement. For general99 information about how to use this class refer to100 :class:`werkzeug.test.Client`.101102 .. versionchanged:: 0.12103 `app.test_client()` includes preset default environment, which can be104 set after instantiation of the `app.test_client()` object in105 `client.environ_base`.106107 Basic usage is outlined in the :doc:`/testing` chapter.108 """109110 application: "Flask"111 preserve_context = False112113 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:114 super().__init__(*args, **kwargs)115 self.environ_base = {116 "REMOTE_ADDR": "127.0.0.1",117 "HTTP_USER_AGENT": f"werkzeug/{werkzeug.__version__}",118 }119120 @contextmanager121 def session_transaction(122 self, *args: t.Any, **kwargs: t.Any123 ) -> t.Generator[SessionMixin, None, None]:124 """When used in combination with a ``with`` statement this opens a125 session transaction. This can be used to modify the session that126 the test client uses. Once the ``with`` block is left the session is127 stored back.128129 ::130131 with client.session_transaction() as session:132 session['value'] = 42133134 Internally this is implemented by going through a temporary test135 request context and since session handling could depend on136 request variables this function accepts the same arguments as137 :meth:`~flask.Flask.test_request_context` which are directly138 passed through.139 """140 if self.cookie_jar is None:141 raise RuntimeError(142 "Session transactions only make sense with cookies enabled."143 )144 app = self.application145 environ_overrides = kwargs.setdefault("environ_overrides", {})146 self.cookie_jar.inject_wsgi(environ_overrides)147 outer_reqctx = _request_ctx_stack.top148 with app.test_request_context(*args, **kwargs) as c:149 session_interface = app.session_interface150 sess = session_interface.open_session(app, c.request)151 if sess is None:152 raise RuntimeError(153 "Session backend did not open a session. Check the configuration"154 )155156 # Since we have to open a new request context for the session157 # handling we want to make sure that we hide out own context158 # from the caller. By pushing the original request context159 # (or None) on top of this and popping it we get exactly that160 # behavior. It's important to not use the push and pop161 # methods of the actual request context object since that would162 # mean that cleanup handlers are called163 _request_ctx_stack.push(outer_reqctx)164 try:165 yield sess166 finally:167 _request_ctx_stack.pop()168169 resp = app.response_class()170 if not session_interface.is_null_session(sess):171 session_interface.save_session(app, sess, resp)172 headers = resp.get_wsgi_headers(c.request.environ)173 self.cookie_jar.extract_wsgi(c.request.environ, headers)174175 def _copy_environ(self, other):176 return {177 **self.environ_base,178 **other,179 "flask._preserve_context": self.preserve_context,180 }181182 def _request_from_builder_args(self, args, kwargs):183 kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {}))184 builder = EnvironBuilder(self.application, *args, **kwargs)185186 try:187 return builder.get_request()188 finally:189 builder.close()190191 def open(192 self,193 *args: t.Any,194 buffered: bool = False,195 follow_redirects: bool = False,196 **kwargs: t.Any,197 ) -> "TestResponse":198 if args and isinstance(199 args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)200 ):201 if isinstance(args[0], werkzeug.test.EnvironBuilder):202 builder = copy(args[0])203 builder.environ_base = self._copy_environ(builder.environ_base or {})204 request = builder.get_request()205 elif isinstance(args[0], dict):206 request = EnvironBuilder.from_environ(207 args[0], app=self.application, environ_base=self._copy_environ({})208 ).get_request()209 else:210 # isinstance(args[0], BaseRequest)211 request = copy(args[0])212 request.environ = self._copy_environ(request.environ)213 else:214 # request is None215 request = self._request_from_builder_args(args, kwargs)216217 return super().open(218 request,219 buffered=buffered,220 follow_redirects=follow_redirects,221 )222223 def __enter__(self) -> "FlaskClient":224 if self.preserve_context:225 raise RuntimeError("Cannot nest client invocations")226 self.preserve_context = True227 return self228229 def __exit__(230 self, exc_type: type, exc_value: BaseException, tb: TracebackType231 ) -> None:232 self.preserve_context = False233234 # Normally the request context is preserved until the next235 # request in the same thread comes. When the client exits we236 # want to clean up earlier. Pop request contexts until the stack237 # is empty or a non-preserved one is found.238 while True:239 top = _request_ctx_stack.top240241 if top is not None and top.preserved:242 top.pop()243 else:244 break245246247class FlaskCliRunner(CliRunner):248 """A :class:`~click.testing.CliRunner` for testing a Flask app's249 CLI commands. Typically created using250 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.251 """252253 def __init__(self, app: "Flask", **kwargs: t.Any) -> None:254 self.app = app255 super().__init__(**kwargs)256257 def invoke( # type: ignore258 self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any259 ) -> t.Any:260 """Invokes a CLI command in an isolated environment. See261 :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for262 full method documentation. See :ref:`testing-cli` for examples.263264 If the ``obj`` argument is not given, passes an instance of265 :class:`~flask.cli.ScriptInfo` that knows how to load the Flask266 app being tested.267268 :param cli: Command object to invoke. Default is the app's269 :attr:`~flask.app.Flask.cli` group.270 :param args: List of strings to invoke the command with.271272 :return: a :class:`~click.testing.Result` object.273 """274 if cli is None:275 cli = self.app.cli # type: ignore276277 if "obj" not in kwargs:278 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)279280 return super().invoke(cli, args, **kwargs)