Skip to content
Myr

testing.py

This file

Path

flask/testing.py

117 lines · 4.6 KiB · Python

Last changed by

The test client and test_request_context are now both using the same logic internally for creating the environ. Also they use APPLICATION_ROOT now.Armin Ronacherbefore adoptione853a0f

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    flask.testing4    ~~~~~~~~~~~~~56    Implements test support helpers.  This module is lazily imported7    and usually not used in production environments.89    :copyright: (c) 2010 by Armin Ronacher.10    :license: BSD, see LICENSE for more details.11"""1213from contextlib import contextmanager14from werkzeug.test import Client, EnvironBuilder15from flask import _request_ctx_stack161718def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):19    """Creates a new test builder with some application defaults thrown in."""20    http_host = app.config.get('SERVER_NAME')21    app_root = app.config.get('APPLICATION_ROOT')22    if base_url is None:23        base_url = 'http://%s/' % (http_host or 'localhost')24        if app_root:25            base_url += app_root.lstrip('/')26    return EnvironBuilder(path, base_url, *args, **kwargs)272829class FlaskClient(Client):30    """Works like a regular Werkzeug test client but has some knowledge about31    how Flask works to defer the cleanup of the request context stack to the32    end of a with body when used in a with statement.  For general information33    about how to use this class refer to :class:`werkzeug.test.Client`.3435    Basic usage is outlined in the :ref:`testing` chapter.36    """3738    preserve_context = context_preserved = False3940    @contextmanager41    def session_transaction(self, *args, **kwargs):42        """When used in combination with a with statement this opens a43        session transaction.  This can be used to modify the session that44        the test client uses.  Once the with block is left the session is45        stored back.4647            with client.session_transaction() as session:48                session['value'] = 424950        Internally this is implemented by going through a temporary test51        request context and since session handling could depend on52        request variables this function accepts the same arguments as53        :meth:`~flask.Flask.test_request_context` which are directly54        passed through.55        """56        app = self.application57        environ_overrides = kwargs.pop('environ_overrides', {})58        if self.cookie_jar is not None:59            self.cookie_jar.inject_wsgi(environ_overrides)60        outer_reqctx = _request_ctx_stack.top61        with app.test_request_context(*args, **kwargs) as c:62            sess = app.open_session(c.request)63            if sess is None:64                raise RuntimeError('Session backend did not open a session. '65                                   'Check the configuration')6667            # Since we have to open a new request context for the session68            # handling we want to make sure that we hide out own context69            # from the caller.  By pushing the original request context70            # (or None) on top of this and popping it we get exactly that71            # behavior.  It's important to not use the push and pop72            # methods of the actual request context object since that would73            # mean that cleanup handlers are called74            _request_ctx_stack.push(outer_reqctx)75            try:76                yield sess77            finally:78                _request_ctx_stack.pop()7980            resp = app.response_class()81            if not app.session_interface.is_null_session(sess):82                app.save_session(sess, resp)83            if self.cookie_jar is not None:84                headers = resp.get_wsgi_headers(c.request.environ)85                self.cookie_jar.extract_wsgi(c.request.environ, headers)8687    def open(self, *args, **kwargs):88        if self.context_preserved:89            _request_ctx_stack.pop()90            self.context_preserved = False91        kwargs.setdefault('environ_overrides', {}) \92            ['flask._preserve_context'] = self.preserve_context9394        as_tuple = kwargs.pop('as_tuple', False)95        buffered = kwargs.pop('buffered', False)96        follow_redirects = kwargs.pop('follow_redirects', False)97        builder = make_test_environ_builder(self.application, *args, **kwargs)9899        old = _request_ctx_stack.top100        try:101            return Client.open(self, builder,102                               as_tuple=as_tuple,103                               buffered=buffered,104                               follow_redirects=follow_redirects)105        finally:106            self.context_preserved = _request_ctx_stack.top is not old107108    def __enter__(self):109        if self.preserve_context:110            raise RuntimeError('Cannot nest client invocations')111        self.preserve_context = True112        return self113114    def __exit__(self, exc_type, exc_value, tb):115        self.preserve_context = False116        if self.context_preserved:117            _request_ctx_stack.pop()