Skip to content
Myr

Added example on faking resources and context

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 0676bb8 · Browse files · 1 file+48 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+48 added−0 removed

  • other:+48 added−0 removed

1 file+48 added−0 removed

modified:docs/testing.rst+48 added
249 unmodified lines
250This in general is less useful because at that point you can directly251start using the test client.252253254Faking Resources and Context255----------------------------256257.. versionadded:: 0.10258259A very common pattern is to store user authorization information and260database connections on the application context or the :attr:`flask.g`261object. The general pattern for this is to put the object on there on262first usage and then to remove it on a teardown. Imagine for instance263this code to get the current user::264265 def get_user():266 user = getattr(g, 'user', None)267 if user is None:268 user = fetch_current_user_from_database()269 g.user = user270 return user271272For a test it would be nice to override this user from the outside without273having to change some code. This can trivially be accomplished with274hooking the :data:`flask.appcontext_pushed` signal::275276 from contextlib import contextmanager277 from flask import appcontext_pushed278279 @contextmanager280 def user_set(app, user):281 def handler(sender, **kwargs):282 g.user = user283 with appcontext_pushed.connected_to(handler, app):284 yield285286And then to use it::287288 from flask import json, jsonify289290 @app.route('/users/me')291 def users_me():292 return jsonify(username=g.user.username)293294 with user_set(app, my_user):295 with app.test_client() as c:296 resp = c.get('/users/me')297 data = json.loads(resp.data)298 self.assert_equal(data['username'], my_user.username)299300301Keeping the Context Around302--------------------------303304.. versionadded:: 0.4
12 unmodified lines
317If you were to use just the :meth:`~flask.Flask.test_client` without318the `with` block, the `assert` would fail with an error because `request`319is no longer available (because you are trying to use it outside of the actual request).320321322Accessing and Modifying Sessions323--------------------------------324325.. versionadded:: 0.8
26 unmodified lines