Added support for deferred context cleanup. test_client users can now access the context locals after the actual request if the client is used with a with-block. This fixes #59.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 9373608 · Browse files · 5 files·+111 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+111 added−3 removed
- tests:+31 added−0 removed
- other:+80 added−3 removed
Provenance
- Commit
bc00fd1- Tree
cc70bae- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9373608
5 files changed+111 added−3 removed
modified:docs/api.rst+17 added
298 unmodified lines299 The internal :class:`~werkzeug.LocalStack` that is used to implement300 all the context local objects used in Flask. This is a documented301 instance and can be used by extensions and application code but the302 use is discouraged in general.303+304+ .. versionchanged:: 0.4305+306+ The request context is automatically popped at the end of the request307+ for you. In debug mode the request context is kept around if308+ exceptions happen so that interactive debuggers have a chance to309+ introspect the data. With 0.4 this can also be forced for requests310+ that did not fail and outside of `DEBUG` mode. By setting311+ ``'flask._preserve_context'`` to `True` on the WSGI environment the312+ context will not pop itself at the end of the request. This is used by313+ the :meth:`~flask.Flask.test_client` for example to implement the314+ deferred cleanup functionality.315+316+ You might find this helpful for unittests where you need the317+ information from the context local around for a little longer. Make318+ sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in319+ that situation, otherwise your unittests will leak memory.modified:docs/testing.rst+24 added
216 unmodified lines217 218 If you want to test your application with different configurations and219 there does not seem to be a good way to do that, consider switching to220 application factories (see :ref:`app-factories`).221+222+223+Keeping the Context Around224+--------------------------225+226+.. versionadded:: 0.4227+228+Sometimes it can be helpful to trigger a regular request but keep the229+context around for a little longer so that additional introspection can230+happen. With Flask 0.4 this is possible by using the231+:meth:`~flask.Flask.test_client` with a `with` block::232+233+ app = flask.Flask(__name__)234+235+ with app.test_client() as c:236+ rv = c.get('/?foo=42')237+ assert request.args['foo'] == '42'238+239+If you would just be using the :meth:`~flask.Flask.test_client` without240+the `with` block, the `assert` would fail with an error because `request`241+is no longer available (because used outside of an actual request).242+Keep in mind however that :meth:`~flask.Flask.after_request` functions243+are already called at that point so your database connection and244+everything involved is probably already closed down.modified:tests/flask_tests.py+31 added
56 unmodified lines57 with app.test_request_context('/?name=World'):58 assert index() == 'Hello World!'59 with app.test_request_context('/meh'):60 assert meh() == 'http://localhost/meh'61+ assert flask._request_ctx_stack.top is None62 63 def test_manual_context_binding(self):64 app = flask.Flask(__name__)65 @app.route('/')10 unmodified lines76 pass77 else:78 assert 0, 'expected runtime error'79 80+ def test_test_client_context_binding(self):81+ app = flask.Flask(__name__)82+ @app.route('/')83+ def index():84+ flask.g.value = 4285+ return 'Hello World!'86 87+ @app.route('/other')88+ def other():89+ 1/090+91+ with app.test_client() as c:92+ resp = c.get('/')93+ assert flask.g.value == 4294+ assert resp.data == 'Hello World!'95+ assert resp.status_code == 20096+97+ resp = c.get('/other')98+ assert not hasattr(flask.g, 'value')99+ assert 'Internal Server Error' in resp.data100+ assert resp.status_code == 500101+ flask.g.value = 23102+103+ try:104+ flask.g.value105+ except (AttributeError, RuntimeError):106+ pass107+ else:108+ raise AssertionError('some kind of exception expected')109+110+111 class BasicFunctionalityTestCase(unittest.TestCase):112 113 def test_request_dispatching(self):114 app = flask.Flask(__name__)733 unmodified linesmodified:CHANGES+3 added
11 unmodified lines12 from modules.13 - :meth:`~flask.Flask.after_request` handlers are now also invoked14 if the request dies with an exception and an error handling page15 kicks in.16+- test client has not the ability to preserve the request context17+ for a little longer. This can also be used to trigger custom18+ requests that do not pop the request stack for testing.19 20 Version 0.3.121 -------------22 48 unmodified linesmodified:flask.py+36 added-3 removed
161 unmodified lines162 163 def __exit__(self, exc_type, exc_value, tb):164 # do not pop the request stack if we are in debug mode and an165 # exception happened. This will allow the debugger to still166- # access the request object in the interactive shell.167- if tb is None or not self.app.debug:166+ # access the request object in the interactive shell. Furthermore167+ # the context can be force kept alive for the test client.168+ if not self.request.environ.get('flask._preserve_context') and \169+ (tb is None or not self.app.debug):170 self.pop()171 172 173 def url_for(endpoint, **values):848 unmodified lines1022 1023 def test_client(self):1024 """Creates a test client for this application. For information1025 about unit testing head over to :ref:`testing`.1026+1027+ The test client can be used in a `with` block to defer the closing down1028+ of the context until the end of the `with` block. This is useful if1029+ you want to access the context locals for testing::1030+1031+ with app.test_client() as c:1032+ rv = c.get('/?foo=42')1033+ assert request.args['foo'] == '42'1034+1035+ .. versionchanged:: 0.41036+ added support for `with` block usage for the client.1037 """1038 from werkzeug import Client1039+ class FlaskClient(Client):1040+ preserve_context = context_preserved = False1041+ def open(self, *args, **kwargs):1042+ if self.context_preserved:1043+ _request_ctx_stack.pop()1044+ self.context_preserved = False1045+ kwargs.setdefault('environ_overrides', {}) \1046+ ['flask._preserve_context'] = self.preserve_context1047+ old = _request_ctx_stack.top1048+ try:1049+ return Client.open(self, *args, **kwargs)1050+ finally:1051+ self.context_preserved = _request_ctx_stack.top is not old1052+ def __enter__(self):1053+ self.preserve_context = True1054+ return self1055+ def __exit__(self, exc_type, exc_value, tb):1056+ self.preserve_context = False1057+ if self.context_preserved:1058+ _request_ctx_stack.pop()1026- return Client(self, self.response_class, use_cookies=True)1059+ return FlaskClient(self, self.response_class, use_cookies=True)1060 1061 def open_session(self, request):1062 """Creates or opens a new session. Default implementation stores all1063 session data in a signed cookie. This requires that the420 unmodified lines