Context preserving is now part of Flask and not the test client. This fixes #326
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 d2eefe2 · Browse files · 5 files·+64 added−21 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+64 added−21 removed
- other:+64 added−21 removed
Provenance
- Commit
c631613- Tree
93d1e35- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d2eefe2
5 files changed+64 added−21 removed
modified:flask/testsuite/basic.py+17 added
902 unmodified lines903 self.assertEqual(c.get('/foo/').data, 'foo')904 self.assertEqual(c.get('/bar/').data, 'bar')905 self.assertEqual(c.get('/bar/123').data, '123')906 907+ def test_preserve_only_once(self):908+ app = flask.Flask(__name__)909+ app.debug = True910 911+ @app.route('/fail')912+ def fail_func():913+ 1/0914+915+ c = app.test_client()916+ for x in xrange(3):917+ with self.assert_raises(ZeroDivisionError):918+ c.get('/fail')919+920+ self.assert_(flask._request_ctx_stack.top is not None)921+ flask._request_ctx_stack.pop()922+ self.assert_(flask._request_ctx_stack.top is None)923+924+925 class ContextTestCase(FlaskTestCase):926 927 def test_context_binding(self):928 app = flask.Flask(__name__)123 unmodified linesmodified:flask/ctx.py+32 added-3 removed
87 unmodified lines88 self.g = _RequestGlobals()89 self.flashes = None90 self.session = None91 92+ # indicator if the context was preserved. Next time another context93+ # is pushed the preserved context is popped.94+ self.preserved = False95+96 self.match_request()97 98 # XXX: Support for deprecated functionality. This is doing away with99 # Flask 1.017 unmodified lines117 self.request.routing_exception = e118 119 def push(self):120 """Binds the request context to the current context."""121+ # If an exception ocurrs in debug mode or if context preservation is122+ # activated under exception situations exactly one context stays123+ # on the stack. The rationale is that you want to access that124+ # information under debug situations. However if someone forgets to125+ # pop that context again we want to make sure that on the next push126+ # it's invalidated otherwise we run at risk that something leaks127+ # memory. This is usually only a problem in testsuite since this128+ # functionality is not active in production environments.129+ top = _request_ctx_stack.top130+ if top is not None and top.preserved:131+ top.pop()132+133 _request_ctx_stack.push(self)134 135 # Open the session at the moment that the request context is136 # available. This allows a custom open_session method to use the6 unmodified lines143 """Pops the request context and unbinds it by doing that. This will144 also trigger the execution of functions registered by the145 :meth:`~flask.Flask.teardown_request` decorator.146 """147+ self.preserved = False148 self.app.do_teardown_request()132- _request_ctx_stack.pop()149+ rv = _request_ctx_stack.pop()150+ assert rv is self, 'Popped wrong request context. (%r instead of %r)' \151+ % (rv, self)152 153 def __enter__(self):154 self.push()155 return self3 unmodified lines159 # exception happened. This will allow the debugger to still160 # access the request object in the interactive shell. Furthermore161 # the context can be force kept alive for the test client.162 # See flask.testing for how this works.144- if not self.request.environ.get('flask._preserve_context') and \145- (tb is None or not self.app.preserve_context_on_exception):163+ if self.request.environ.get('flask._preserve_context') or \164+ (tb is not None and self.app.preserve_context_on_exception):165+ self.preserved = True166+ else:167 self.pop()168+169+ def __repr__(self):170+ return '<%s \'%s\' [%s] of %s>' % (171+ self.__class__.__name__,172+ self.request.url,173+ self.request.method,174+ self.app.name175+ )modified:flask/globals.py+1 added
17 unmodified lines18 if top is None:19 raise RuntimeError('working outside of request context')20 return getattr(top, name)21 22+23 # context locals24 _request_ctx_stack = LocalStack()25 current_app = LocalProxy(partial(_lookup_object, 'app'))26 request = LocalProxy(partial(_lookup_object, 'request'))2 unmodified linesmodified:flask/testing.py+11 added-18 removed
35 unmodified lines36 37 Basic usage is outlined in the :ref:`testing` chapter.38 """39 40- preserve_context = context_preserved = False40+ preserve_context = False41 42 @contextmanager43 def session_transaction(self, *args, **kwargs):44 """When used in combination with a with statement this opens a42 unmodified lines87 headers = resp.get_wsgi_headers(c.request.environ)88 self.cookie_jar.extract_wsgi(c.request.environ, headers)89 90 def open(self, *args, **kwargs):91- self._pop_reqctx_if_necessary()91 kwargs.setdefault('environ_overrides', {}) \92 ['flask._preserve_context'] = self.preserve_context93 94 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)98 100- old = _request_ctx_stack.top101- try:102- return Client.open(self, builder,103- as_tuple=as_tuple,104- buffered=buffered,105- follow_redirects=follow_redirects)99+ return Client.open(self, builder,100+ as_tuple=as_tuple,101+ buffered=buffered,102+ follow_redirects=follow_redirects)106- finally:107- self.context_preserved = _request_ctx_stack.top is not old103 104 def __enter__(self):105 if self.preserve_context:106 raise RuntimeError('Cannot nest client invocations')1 unmodified line108 return self109 110 def __exit__(self, exc_type, exc_value, tb):111 self.preserve_context = False117- self._pop_reqctx_if_necessary()112 119- def _pop_reqctx_if_necessary(self):120- if self.context_preserved:121- # we have to use _request_ctx_stack.top.pop instead of122- # _request_ctx_stack.pop since we want teardown handlers123- # to be executed.124- _request_ctx_stack.top.pop()125- self.context_preserved = False113+ # on exit we want to clean up earlier. Normally the request context114+ # stays preserved until the next request in the same thread comes115+ # in. See RequestGlobals.push() for the general behavior.116+ top = _request_ctx_stack.top117+ if top is not None and top.preserved:118+ top.pop()modified:CHANGES+3 added
44 unmodified lines45 - Added finer control over the session cookie parameters.46 - HEAD requests to a method view now automatically dispatch to the `get`47 method if no handler was implemented.48 - Implemented the virtual :mod:`flask.ext` package to import extensions from.49+- The context preservation on exceptions is now an integral component of50+ Flask itself and no longer of the test client. This cleaned up some51+ internal logic and lowers the odds of runaway request contexts in unittests.52 53 Version 0.7.354 -------------55 238 unmodified lines