Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

357 lines · 12.4 KiB

Last changed by

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

History of this file

Take it

The walk stopped after 200 commits: lines older than 81576c2 point at it.

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 1–13why, one step back
1.. _testing:
23Testing Flask Applications4==========================56 **Something that is untested is broken.**78The origin of this quote is unknown and while it is not entirely correct, it is also9not far from the truth. Untested applications make it hard to10improve existing code and developers of untested applications tend to11become pretty paranoid. If an application has automated tests, you can12safely make changes and instantly know if anything breaks.13

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

line 14why, one step back
14Flask provides a way to test your application by exposing the Werkzeug

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 15–21why, one step back
15test :class:`~werkzeug.test.Client` and handling the context locals for you.
16You can then use that with your favourite testing solution. In this documentation17we will use the :mod:`unittest` package that comes pre-installed with Python.1819The Application20---------------21

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

lines 22–23why, one step back
22First, we need an application to test; we will use the application from
23the :ref:`tutorial`. If you don't have that application yet, get the

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 24–26why, one step back
24sources from `the examples`_.
2526.. _the examples:

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 27why, one step back
27 https://github.com/pallets/flask/tree/master/examples/flaskr/

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 28–31why, one step back
28
29The Testing Skeleton30--------------------31

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

line 32why, one step back
32In order to test the application, we add a second module

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 33why, one step back
33(:file:`flaskr_tests.py`) and create a unittest skeleton there::

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 34–43why, one step back
34
35 import os36 import flaskr37 import unittest38 import tempfile3940 class FlaskrTestCase(unittest.TestCase):4142 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 44why, one step back
44 flaskr.app.testing = True

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 45–57why, one step back
45 self.app = flaskr.app.test_client()
46 with flaskr.app.app_context():47 flaskr.init_db()4849 def tearDown(self):50 os.close(self.db_fd)51 os.unlink(flaskr.app.config['DATABASE'])5253 if __name__ == '__main__':54 unittest.main()5556The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57client and initializes a new database. This function is called before

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

line 58why, one step back
58each individual test function is run. To delete the database after the

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 59–60why, one step back
59test, we close the file and remove it from the filesystem in the
60:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the

Merge pull request #1297 from nryoung/masterMarkus Unterwaditzerbefore adoptiondf256f0

line 61why, one step back
61``TESTING`` config flag is activated. What it does is disable the error

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 62–64why, one step back
62catching during request handling so that you get better error reports when
63performing test requests against the application.64

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

lines 65–66why, one step back
65This test client will give us a simple interface to the application. We can
66trigger test requests to the application, and the client will also keep track

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 67–91why, one step back
67of cookies for us.
6869Because SQLite3 is filesystem-based we can easily use the tempfile module70to create a temporary database and initialize it. The71:func:`~tempfile.mkstemp` function does two things for us: it returns a72low-level file handle and a random file name, the latter we use as73database name. We just have to keep the `db_fd` around so that we can use74the :func:`os.close` function to close the file.7576If we now run the test suite, we should see the following output::7778 $ python flaskr_tests.py7980 ----------------------------------------------------------------------81 Ran 0 tests in 0.000s8283 OK8485Even though it did not run any actual tests, we already know that our flaskr86application is syntactically valid, otherwise the import would have died87with an exception.8889The First Test90--------------91

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

lines 92–93why, one step back
92Now it's time to start testing the functionality of the application.
93Let's check that the application shows "No entries here so far" if we

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 94–100why, one step back
94access the root of the application (``/``). To do this, we add a new
95test method to our class, like this::9697 class FlaskrTestCase(unittest.TestCase):9899 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 101why, one step back
101 flaskr.app.testing = True

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 102why, one step back
102 self.app = flaskr.app.test_client()

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

lines 103–104why, one step back
103 with flaskr.app.app_context():
104 flaskr.init_db()

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 105–111why, one step back
105
106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])109110 def test_empty_db(self):111 rv = self.app.get('/')

Fix #1298Markus Unterwaditzerbefore adoptionbd2c8b6

line 112why, one step back
112 assert b'No entries here so far' in rv.data

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 113why, one step back
113

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

lines 114–115why, one step back
114Notice that our test functions begin with the word `test`; this allows
115:mod:`unittest` to automatically identify the method as a test to run.

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 116why, one step back
116

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 117why, one step back
117By using `self.app.get` we can send an HTTP ``GET`` request to the application with

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

line 118why, one step back
118the given path. The return value will be a :class:`~flask.Flask.response_class` object.

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 119why, one step back
119We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

line 120why, one step back
120the return value (as string) from the application. In this case, we ensure that

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 121–136why, one step back
121``'No entries here so far'`` is part of the output.
122123Run it again and you should see one passing test::124125 $ python flaskr_tests.py126 .127 ----------------------------------------------------------------------128 Ran 1 test in 0.034s129130 OK131132Logging In and Out133------------------134135The majority of the functionality of our application is only available for136the administrative user, so we need a way to log our test client in and out

Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01

lines 137–138why, one step back
137of the application. To do this, we fire some requests to the login and logout
138pages with the required form data (username and password). And because the

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 139–156why, one step back
139login and logout pages redirect, we tell the client to `follow_redirects`.
140141Add the following two methods to your `FlaskrTestCase` class::142143 def login(self, username, password):144 return self.app.post('/login', data=dict(145 username=username,146 password=password147 ), follow_redirects=True)148149 def logout(self):150 return self.app.get('/logout', follow_redirects=True)151152Now we can easily test that logging in and out works and that it fails with153invalid credentials. Add this new test to the class::154155 def test_login_logout(self):156 rv = self.login('admin', 'default')

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 157why, one step back
157 assert b'You were logged in' in rv.data

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 158why, one step back
158 rv = self.logout()

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 159why, one step back
159 assert b'You were logged out' in rv.data

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 160why, one step back
160 rv = self.login('adminx', 'default')

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 161why, one step back
161 assert b'Invalid username' in rv.data

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 162why, one step back
162 rv = self.login('admin', 'defaultx')

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 163why, one step back
163 assert b'Invalid password' in rv.data

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 164–176why, one step back
164
165Test Adding Messages166--------------------167168We should also test that adding messages works. Add a new test method169like this::170171 def test_messages(self):172 self.login('admin', 'default')173 rv = self.app.post('/add', data=dict(174 title='<Hello>',175 text='<strong>HTML</strong> allowed here'176 ), follow_redirects=True)

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

lines 177–179why, one step back
177 assert b'No entries here so far' not in rv.data
178 assert b'&lt;Hello&gt;' in rv.data179 assert b'<strong>HTML</strong> allowed here' in rv.data

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 180–198why, one step back
180
181Here we check that HTML is allowed in the text but not in the title,182which is the intended behavior.183184Running that should now give us three passing tests::185186 $ python flaskr_tests.py187 ...188 ----------------------------------------------------------------------189 Ran 3 tests in 0.332s190191 OK192193For more complex tests with headers and status codes, check out the194`MiniTwit Example`_ from the sources which contains a larger test195suite.196197198.. _MiniTwit Example:

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 199why, one step back
199 https://github.com/pallets/flask/tree/master/examples/minitwit/

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 200–206why, one step back
200
201202Other Testing Tricks203--------------------204205Besides using the test client as shown above, there is also the206:meth:`~flask.Flask.test_request_context` method that can be used

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 207why, one step back
207in combination with the ``with`` statement to activate a request context

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 208–211why, one step back
208temporarily. With this you can access the :class:`~flask.request`,
209:class:`~flask.g` and :class:`~flask.session` objects like in view210functions. Here is a full example that demonstrates this approach::211

Merge pull request #1380 from KWinston/masterMarkus Unterwaditzerbefore adoptionb57a076

line 212why, one step back
212 import flask

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

line 213why, one step back
213

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 214–227why, one step back
214 app = flask.Flask(__name__)
215216 with app.test_request_context('/?name=Peter'):217 assert flask.request.path == '/'218 assert flask.request.args['name'] == 'Peter'219220All the other objects that are context bound can be used in the same221way.222223If you want to test your application with different configurations and224there does not seem to be a good way to do that, consider switching to225application factories (see :ref:`app-factories`).226227Note however that if you are using a test request context, the

Merge branch 'master' into jrmccarthy-masterDavid Lordbefore adoption8ad4f47

lines 228–229why, one step back
228:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`
229functions are not called automatically. However

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

line 230why, one step back
230:meth:`~flask.Flask.teardown_request` functions are indeed executed when

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 231why, one step back
231the test request context leaves the ``with`` block. If you do want the

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 232–278why, one step back
232:meth:`~flask.Flask.before_request` functions to be called as well, you
233need to call :meth:`~flask.Flask.preprocess_request` yourself::234235 app = flask.Flask(__name__)236237 with app.test_request_context('/?name=Peter'):238 app.preprocess_request()239 ...240241This can be necessary to open database connections or something similar242depending on how your application was designed.243244If you want to call the :meth:`~flask.Flask.after_request` functions you245need to call into :meth:`~flask.Flask.process_response` which however246requires that you pass it a response object::247248 app = flask.Flask(__name__)249250 with app.test_request_context('/?name=Peter'):251 resp = Response('...')252 resp = app.process_response(resp)253 ...254255This in general is less useful because at that point you can directly256start using the test client.257258.. _faking-resources:259260Faking Resources and Context261----------------------------262263.. versionadded:: 0.10264265A very common pattern is to store user authorization information and266database connections on the application context or the :attr:`flask.g`267object. The general pattern for this is to put the object on there on268first usage and then to remove it on a teardown. Imagine for instance269this code to get the current user::270271 def get_user():272 user = getattr(g, 'user', None)273 if user is None:274 user = fetch_current_user_from_database()275 g.user = user276 return user277278For a test it would be nice to override this user from the outside without

Merge pull request #1491 from nvie/patch-1Markus Unterwaditzerbefore adoption3e07b9c

line 279why, one step back
279having to change some code. This can be accomplished with

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 280–282why, one step back
280hooking the :data:`flask.appcontext_pushed` signal::
281282 from contextlib import contextmanager

Merge pull request #1313 from homeworkprod/patch-1Markus Unterwaditzerbefore adoptionb68dc78

line 283why, one step back
283 from flask import appcontext_pushed, g

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 284–314why, one step back
284
285 @contextmanager286 def user_set(app, user):287 def handler(sender, **kwargs):288 g.user = user289 with appcontext_pushed.connected_to(handler, app):290 yield291292And then to use it::293294 from flask import json, jsonify295296 @app.route('/users/me')297 def users_me():298 return jsonify(username=g.user.username)299300 with user_set(app, my_user):301 with app.test_client() as c:302 resp = c.get('/users/me')303 data = json.loads(resp.data)304 self.assert_equal(data['username'], my_user.username)305306307Keeping the Context Around308--------------------------309310.. versionadded:: 0.4311312Sometimes it is helpful to trigger a regular request but still keep the313context around for a little longer so that additional introspection can314happen. With Flask 0.4 this is possible by using the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 315why, one step back
315:meth:`~flask.Flask.test_client` with a ``with`` block::

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 316–323why, one step back
316
317 app = flask.Flask(__name__)318319 with app.test_client() as c:320 rv = c.get('/?tequila=42')321 assert request.args['tequila'] == '42'322323If you were to use just the :meth:`~flask.Flask.test_client` without

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 324why, one step back
324the ``with`` block, the ``assert`` would fail with an error because `request`

Further refactored script system to allow more customization for special apps.Armin Ronacherbefore adoption81576c2

lines 325–357why, one step back
325is no longer available (because you are trying to use it outside of the actual request).
326327328Accessing and Modifying Sessions329--------------------------------330331.. versionadded:: 0.8332333Sometimes it can be very helpful to access or modify the sessions from the334test client. Generally there are two ways for this. If you just want to335ensure that a session has certain keys set to certain values you can just336keep the context around and access :data:`flask.session`::337338 with app.test_client() as c:339 rv = c.get('/')340 assert flask.session['foo'] == 42341342This however does not make it possible to also modify the session or to343access the session before a request was fired. Starting with Flask 0.8 we344provide a so called “session transaction” which simulates the appropriate345calls to open a session in the context of the test client and to modify346it. At the end of the transaction the session is stored. This works347independently of the session backend used::348349 with app.test_client() as c:350 with c.session_transaction() as sess:351 sess['a_key'] = 'a value'352353 # once this is reached the session was stored354355Note that in this case you have to use the ``sess`` object instead of the356:data:`flask.session` proxy. The object however itself will provide the357same interface.