Skip to content
Myr

Implemented flask.testing.TestClient.session_transaction for quick session modifications in test environments.

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 c844d02 · Browse files · 5 files+112 added−4 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+112 added−4 removed

  • tests:+45 added−0 removed
  • other:+67 added−4 removed

5 files+112 added−4 removed

modified:docs/api.rst+9 added
216 unmodified lines
217.. autoclass:: SessionMixin218 :members:219220221Test Client222-----------223224.. currentmodule:: flask.testing225226.. autoclass:: TestClient227 :members:228229230Application Globals231-------------------232233.. currentmodule:: flask
270 unmodified lines
modified:flask/app.py+2 added
704 unmodified lines
705 with app.test_client() as c:706 rv = c.get('/?vodka=42')707 assert request.args['vodka'] == '42'708709 See :class:`~flask.testing.TestClient` for more information.710711 .. versionchanged:: 0.4712 added support for `with` block usage for the client.713714 .. versionadded:: 0.7
825 unmodified lines
modified:flask/testing.py+54 added-4 removed
8 unmodified lines
9 :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_stack161718class FlaskClient(Client):18 """Works like a regular Werkzeug test client but has some19 knowledge about how Flask works to defer the cleanup of the20 request context stack to the end of a with body when used21 in a with statement.19 """Works like a regular Werkzeug test client but has some knowledge about20 how Flask works to defer the cleanup of the request context stack to the21 end of a with body when used in a with statement. For general information22 about how to use this class refer to :class:`werkzeug.test.Client`.2324 Basic usage is outlined in the :ref:`testing` chapter.25 """2627 preserve_context = context_preserved = False2829 @contextmanager30 def session_transaction(self, *args, **kwargs):31 """When used in combination with a with statement this opens a32 session transaction. This can be used to modify the session that33 the test client uses. Once the with block is left the session is34 stored back.3536 with client.session_transaction() as session:37 session['value'] = 423839 Internally this is implemented by going through a temporary test40 request context and since session handling could depend on41 request variables this function accepts the same arguments as42 :meth:`~flask.Flask.test_request_context` which are directly43 passed through.44 """45 app = self.application46 environ_overrides = kwargs.pop('environ_overrides', {})47 if self.cookie_jar is not None:48 self.cookie_jar.inject_wsgi(environ_overrides)49 outer_reqctx = _request_ctx_stack.top50 with app.test_request_context(*args, **kwargs) as c:51 sess = app.open_session(c.request)52 if sess is None:53 raise RuntimeError('Session backend did not open a session. '54 'Check the configuration')5556 # Since we have to open a new request context for the session57 # handling we want to make sure that we hide out own context58 # from the caller. By pushing the original request context59 # (or None) on top of this and popping it we get exactly that60 # behavior. It's important to not use the push and pop61 # methods of the actual request context object since that would62 # mean that cleanup handlers are called63 _request_ctx_stack.push(outer_reqctx)64 try:65 yield sess66 finally:67 _request_ctx_stack.pop()6869 resp = app.response_class()70 if not app.session_interface.is_null_session(sess):71 app.save_session(sess, resp)72 if self.cookie_jar is not None:73 headers = resp.get_wsgi_headers(c.request.environ)74 self.cookie_jar.extract_wsgi(c.request.environ, headers)7576 def open(self, *args, **kwargs):77 if self.context_preserved:78 _request_ctx_stack.pop()79 self.context_preserved = False
38 unmodified lines
modified:tests/flask_tests.py+45 added
1026 unmodified lines
1027 rv = c.post('/foo', data={}, follow_redirects=True)1028 self.assertEqual(rv.data, 'success')102910301031class TestToolsTestCase(unittest.TestCase):10321033 def test_session_transactions(self):1034 app = flask.Flask(__name__)1035 app.testing = True1036 app.secret_key = 'testing'10371038 @app.route('/')1039 def index():1040 return unicode(flask.session['foo'])10411042 with app.test_client() as c:1043 with c.session_transaction() as sess:1044 self.assertEqual(len(sess), 0)1045 sess['foo'] = [42]1046 self.assertEqual(len(sess), 1)1047 rv = c.get('/')1048 self.assertEqual(rv.data, '[42]')10491050 def test_session_transactions_no_null_sessions(self):1051 app = flask.Flask(__name__)1052 app.testing = True10531054 with app.test_client() as c:1055 try:1056 with c.session_transaction() as sess:1057 pass1058 except RuntimeError, e:1059 self.assert_('Session backend did not open a session' in str(e))1060 else:1061 self.fail('Expected runtime error')10621063 def test_session_transactions_keep_context(self):1064 app = flask.Flask(__name__)1065 app.testing = True1066 app.secret_key = 'testing'10671068 with app.test_client() as c:1069 rv = c.get('/')1070 req = flask.request._get_current_object()1071 with c.session_transaction():1072 self.assert_(req is flask.request._get_current_object())107310741075class InstanceTestCase(unittest.TestCase):10761077 def test_explicit_instance_paths(self):1078 here = os.path.abspath(os.path.dirname(__file__))
1173 unmodified lines
2252 suite.addTest(unittest.makeSuite(ConfigTestCase))2253 suite.addTest(unittest.makeSuite(SubdomainTestCase))2254 suite.addTest(unittest.makeSuite(ViewTestCase))2255 suite.addTest(unittest.makeSuite(DeprecationsTestCase))2256 suite.addTest(unittest.makeSuite(TestToolsTestCase))2257 suite.addTest(unittest.makeSuite(InstanceTestCase))2258 if flask.json_available:2259 suite.addTest(unittest.makeSuite(JSONTestCase))2260 if flask.signals_available:
8 unmodified lines
modified:CHANGES+2 added
31 unmodified lines
32 conceptionally only instance depending and outside version control so it's33 the perfect place to put configuration files etc. For more information34 see :ref:`instance-folders`.35- Added the ``APPLICATION_ROOT`` configuration variable.36- Implemented :meth:`~flask.testing.TestClient.session_transaction` to37 easily modify sessions from the test environment.3839Version 0.7.340-------------41
238 unmodified lines