Skip to content

Commit 1f6be7f

Browse files
committed
Added example on faking resources and context
1 parent 0676bb8 commit 1f6be7f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

docs/testing.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,53 @@ This in general is less useful because at that point you can directly
251251
start using the test client.
252252

253253

254+
Faking Resources and Context
255+
----------------------------
256+
257+
.. versionadded:: 0.10
258+
259+
A very common pattern is to store user authorization information and
260+
database connections on the application context or the :attr:`flask.g`
261+
object. The general pattern for this is to put the object on there on
262+
first usage and then to remove it on a teardown. Imagine for instance
263+
this code to get the current user::
264+
265+
def get_user():
266+
user = getattr(g, 'user', None)
267+
if user is None:
268+
user = fetch_current_user_from_database()
269+
g.user = user
270+
return user
271+
272+
For a test it would be nice to override this user from the outside without
273+
having to change some code. This can trivially be accomplished with
274+
hooking the :data:`flask.appcontext_pushed` signal::
275+
276+
from contextlib import contextmanager
277+
from flask import appcontext_pushed
278+
279+
@contextmanager
280+
def user_set(app, user):
281+
def handler(sender, **kwargs):
282+
g.user = user
283+
with appcontext_pushed.connected_to(handler, app):
284+
yield
285+
286+
And then to use it::
287+
288+
from flask import json, jsonify
289+
290+
@app.route('/users/me')
291+
def users_me():
292+
return jsonify(username=g.user.username)
293+
294+
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)
299+
300+
254301
Keeping the Context Around
255302
--------------------------
256303

@@ -271,6 +318,7 @@ If you were to use just the :meth:`~flask.Flask.test_client` without
271318
the `with` block, the `assert` would fail with an error because `request`
272319
is no longer available (because you are trying to use it outside of the actual request).
273320

321+
274322
Accessing and Modifying Sessions
275323
--------------------------------
276324

0 commit comments

Comments
 (0)