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
Provenance
- Commit
a5da2c9- Tree
da1af74- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c844d02
5 files changed+112 added−4 removed
modified:docs/api.rst+9 added
216 unmodified lines217 .. autoclass:: SessionMixin218 :members:219 220 221+Test Client222+-----------223+224+.. currentmodule:: flask.testing225+226+.. autoclass:: TestClient227+ :members:228+229+230 Application Globals231 -------------------232 233 .. currentmodule:: flask270 unmodified linesmodified:flask/app.py+2 added
704 unmodified lines705 with app.test_client() as c:706 rv = c.get('/?vodka=42')707 assert request.args['vodka'] == '42'708 709+ See :class:`~flask.testing.TestClient` for more information.710+711 .. versionchanged:: 0.4712 added support for `with` block usage for the client.713 714 .. versionadded:: 0.7825 unmodified linesmodified:flask/testing.py+54 added-4 removed
8 unmodified lines9 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13+from contextlib import contextmanager14 from werkzeug.test import Client, EnvironBuilder15 from flask import _request_ctx_stack16 17 18 class 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`.23+24+ Basic usage is outlined in the :ref:`testing` chapter.25 """26 27 preserve_context = context_preserved = False28 29+ @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.35+36+ with client.session_transaction() as session:37+ session['value'] = 4238+39+ 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')55+56+ # 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()68+69+ 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)75+76 def open(self, *args, **kwargs):77 if self.context_preserved:78 _request_ctx_stack.pop()79 self.context_preserved = False38 unmodified linesmodified:tests/flask_tests.py+45 added
1026 unmodified lines1027 rv = c.post('/foo', data={}, follow_redirects=True)1028 self.assertEqual(rv.data, 'success')1029 1030 1031+class TestToolsTestCase(unittest.TestCase):1032+1033+ def test_session_transactions(self):1034+ app = flask.Flask(__name__)1035+ app.testing = True1036+ app.secret_key = 'testing'1037+1038+ @app.route('/')1039+ def index():1040+ return unicode(flask.session['foo'])1041+1042+ 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]')1049+1050+ def test_session_transactions_no_null_sessions(self):1051+ app = flask.Flask(__name__)1052+ app.testing = True1053+1054+ 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')1062+1063+ def test_session_transactions_keep_context(self):1064+ app = flask.Flask(__name__)1065+ app.testing = True1066+ app.secret_key = 'testing'1067+1068+ 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())1073+1074+1075 class InstanceTestCase(unittest.TestCase):1076 1077 def test_explicit_instance_paths(self):1078 here = os.path.abspath(os.path.dirname(__file__))1173 unmodified lines2252 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 linesmodified:CHANGES+2 added
31 unmodified lines32 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.38 39 Version 0.7.340 -------------41 238 unmodified lines