Skip to content
Myr

testing.py

This file

Path

src/flask/testing.py

286 lines · 10.3 KiB · Python

Last changed by

Merge pull request #4692 from pallets/json-providerDavid Lordbefore adoption67310ab

History of this file

Take it

1import typing as t2from contextlib import contextmanager3from contextlib import ExitStack4from copy import copy5from types import TracebackType67import werkzeug.test8from click.testing import CliRunner9from werkzeug.test import Client10from werkzeug.urls import url_parse11from werkzeug.wrappers import Request as BaseRequest1213from .cli import ScriptInfo14from .globals import _cv_request15from .sessions import SessionMixin1617if t.TYPE_CHECKING:  # pragma: no cover18    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        return self.app.json.dumps(obj, **kwargs)929394class FlaskClient(Client):95    """Works like a regular Werkzeug test client but has knowledge about96    Flask's contexts to defer the cleanup of the request context until97    the end of a ``with`` block. For general information about how to98    use this class refer to :class:`werkzeug.test.Client`.99100    .. versionchanged:: 0.12101       `app.test_client()` includes preset default environment, which can be102       set after instantiation of the `app.test_client()` object in103       `client.environ_base`.104105    Basic usage is outlined in the :doc:`/testing` chapter.106    """107108    application: "Flask"109110    def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:111        super().__init__(*args, **kwargs)112        self.preserve_context = False113        self._new_contexts: t.List[t.ContextManager[t.Any]] = []114        self._context_stack = ExitStack()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 = _cv_request.get(None)148        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            token = _cv_request.set(outer_reqctx)  # type: ignore[arg-type]164            try:165                yield sess166            finally:167                _cv_request.reset(token)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        out = {**self.environ_base, **other}177178        if self.preserve_context:179            out["werkzeug.debug.preserve_context"] = self._new_contexts.append180181        return out182183    def _request_from_builder_args(self, args, kwargs):184        kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {}))185        builder = EnvironBuilder(self.application, *args, **kwargs)186187        try:188            return builder.get_request()189        finally:190            builder.close()191192    def open(193        self,194        *args: t.Any,195        buffered: bool = False,196        follow_redirects: bool = False,197        **kwargs: t.Any,198    ) -> "TestResponse":199        if args and isinstance(200            args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest)201        ):202            if isinstance(args[0], werkzeug.test.EnvironBuilder):203                builder = copy(args[0])204                builder.environ_base = self._copy_environ(builder.environ_base or {})205                request = builder.get_request()206            elif isinstance(args[0], dict):207                request = EnvironBuilder.from_environ(208                    args[0], app=self.application, environ_base=self._copy_environ({})209                ).get_request()210            else:211                # isinstance(args[0], BaseRequest)212                request = copy(args[0])213                request.environ = self._copy_environ(request.environ)214        else:215            # request is None216            request = self._request_from_builder_args(args, kwargs)217218        # Pop any previously preserved contexts. This prevents contexts219        # from being preserved across redirects or multiple requests220        # within a single block.221        self._context_stack.close()222223        response = super().open(224            request,225            buffered=buffered,226            follow_redirects=follow_redirects,227        )228        response.json_module = self.application.json  # type: ignore[misc]229230        # Re-push contexts that were preserved during the request.231        while self._new_contexts:232            cm = self._new_contexts.pop()233            self._context_stack.enter_context(cm)234235        return response236237    def __enter__(self) -> "FlaskClient":238        if self.preserve_context:239            raise RuntimeError("Cannot nest client invocations")240        self.preserve_context = True241        return self242243    def __exit__(244        self,245        exc_type: t.Optional[type],246        exc_value: t.Optional[BaseException],247        tb: t.Optional[TracebackType],248    ) -> None:249        self.preserve_context = False250        self._context_stack.close()251252253class FlaskCliRunner(CliRunner):254    """A :class:`~click.testing.CliRunner` for testing a Flask app's255    CLI commands. Typically created using256    :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.257    """258259    def __init__(self, app: "Flask", **kwargs: t.Any) -> None:260        self.app = app261        super().__init__(**kwargs)262263    def invoke(  # type: ignore264        self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any265    ) -> t.Any:266        """Invokes a CLI command in an isolated environment. See267        :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for268        full method documentation. See :ref:`testing-cli` for examples.269270        If the ``obj`` argument is not given, passes an instance of271        :class:`~flask.cli.ScriptInfo` that knows how to load the Flask272        app being tested.273274        :param cli: Command object to invoke. Default is the app's275            :attr:`~flask.app.Flask.cli` group.276        :param args: List of strings to invoke the command with.277278        :return: a :class:`~click.testing.Result` object.279        """280        if cli is None:281            cli = self.app.cli  # type: ignore282283        if "obj" not in kwargs:284            kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)285286        return super().invoke(cli, args, **kwargs)