Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

241 lines · 8.4 KiB

Last changed by

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

History of this file

Take it

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

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 1–7why, one step back
1.. _testing:
23Testing Flask Applications4==========================56 **Something that is untested is broken.**7

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 8–9why, one step back
8The origin of this quote is unknown and while it is not entirely correct, it is also
9not far from the truth. Untested applications make it hard to

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 10–11why, one step back
10improve existing code and developers of untested applications tend to
11become pretty paranoid. If an application has automated tests, you can

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 12why, one step back
12safely make changes and instantly know if anything breaks.

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

line 13why, one step back
13

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 14–17why, one step back
14Flask provides a way to test your application by exposing the Werkzeug
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.

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 18–21why, one step back
18
19The Application20---------------21

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 22–24why, 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 24sources from `the examples`_.

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 25–31why, one step back
25
26.. _the examples:27 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/2829The Testing Skeleton30--------------------31

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 32–33why, one step back
32In order to test the application, we add a second module
33(`flaskr_tests.py`) and create a unittest skeleton there::

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 34–42why, one step back
34
35 import os36 import flaskr37 import unittest38 import tempfile3940 class FlaskrTestCase(unittest.TestCase):4142 def setUp(self):

Fixed testing exampleArmin Ronacherbefore adoption0566abc

line 43why, one step back
43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 44–48why, one step back
44 self.app = flaskr.app.test_client()
45 flaskr.init_db()4647 def tearDown(self):48 os.close(self.db_fd)

Fixed a refacotring error in the docs. This fixes #100Armin Ronacherbefore adoptiond17b6d7

line 49why, one step back
49 os.unlink(flaskr.app.config['DATABASE'])

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 50–54why, one step back
50
51 if __name__ == '__main__':52 unittest.main()5354The code in the :meth:`~unittest.TestCase.setUp` method creates a new test

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 55–58why, one step back
55client and initializes a new database. This function is called before
56each individual test function is run. To delete the database after the 57test, we close the file and remove it from the filesystem in the58:meth:`~unittest.TestCase.tearDown` method.

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

line 59why, one step back
59

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 60–63why, one step back
60This test client will give us a simple interface to the application. We can
61trigger test requests to the application, and the client will also keep track 62of cookies for us.63

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 64–70why, one step back
64Because SQLite3 is filesystem-based we can easily use the tempfile module
65to create a temporary database and initialize it. The66:func:`~tempfile.mkstemp` function does two things for us: it returns a67low-level file handle and a random file name, the latter we use as68database name. We just have to keep the `db_fd` around so that we can use69the :func:`os.close` function to close the file.70

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 71why, one step back
71If we now run the test suite, we should see the following output::

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 72–79why, one step back
72
73 $ python flaskr_tests.py7475 ----------------------------------------------------------------------76 Ran 0 tests in 0.000s7778 OK79

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 80why, one step back
80Even though it did not run any actual tests, we already know that our flaskr

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 81–86why, one step back
81application is syntactically valid, otherwise the import would have died
82with an exception.8384The First Test85--------------86

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 87–90why, one step back
87Now it's time to start testing the functionality of the application.
88Let's check that the application shows "No entries here so far" if we 89access the root of the application (``/``). To do this, we add a new90test method to our class, like this::

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 91–106why, one step back
91
92 class FlaskrTestCase(unittest.TestCase):9394 def setUp(self):95 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()96 self.app = flaskr.app.test_client()97 flaskr.init_db()9899 def tearDown(self):100 os.close(self.db_fd)101 os.unlink(flaskr.DATABASE)102103 def test_empty_db(self):104 rv = self.app.get('/')105 assert 'No entries here so far' in rv.data106

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

line 109why, one step back
109

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 110–115why, one step back
110By using `self.app.get` we can send an HTTP `GET` request to the application with
111the given path. The return value will be a :class:`~flask.Flask.response_class` object. 112We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect113the return value (as string) from the application. In this case, we ensure that 114``'No entries here so far'`` is part of the output.115

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 116–128why, one step back
116Run it again and you should see one passing test::
117118 $ python flaskr_tests.py119 .120 ----------------------------------------------------------------------121 Ran 1 test in 0.034s122123 OK124125Logging In and Out126------------------127128The majority of the functionality of our application is only available for

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 129–132why, one step back
129the administrative user, so we need a way to log our test client in and out
130of the application. To do this, we fire some requests to the login and logout 131pages with the required form data (username and password). And because the 132login and logout pages redirect, we tell the client to `follow_redirects`.

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 133–144why, one step back
133
134Add the following two methods to your `FlaskrTestCase` class::135136 def login(self, username, password):137 return self.app.post('/login', data=dict(138 username=username,139 password=password140 ), follow_redirects=True)141142 def logout(self):143 return self.app.get('/logout', follow_redirects=True)144

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 145why, one step back
145Now we can easily test that logging in and out works and that it fails with

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 146–160why, one step back
146invalid credentials. Add this new test to the class::
147148 def test_login_logout(self):149 rv = self.login('admin', 'default')150 assert 'You were logged in' in rv.data151 rv = self.logout()152 assert 'You were logged out' in rv.data153 rv = self.login('adminx', 'default')154 assert 'Invalid username' in rv.data155 rv = self.login('admin', 'defaultx')156 assert 'Invalid password' in rv.data157158Test Adding Messages159--------------------160

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 161why, one step back
161We should also test that adding messages works. Add a new test method

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 162–170why, one step back
162like this::
163164 def test_messages(self):165 self.login('admin', 'default')166 rv = self.app.post('/add', data=dict(167 title='<Hello>',168 text='<strong>HTML</strong> allowed here'169 ), follow_redirects=True)170 assert 'No entries here so far' not in rv.data

Add missing semicolon to testDaniel Haakerbefore adoption94a7312

line 171why, one step back
171 assert '&lt;Hello&gt;' in rv.data

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 172–186why, one step back
172 assert '<strong>HTML</strong> allowed here' in rv.data
173174Here we check that HTML is allowed in the text but not in the title,175which is the intended behavior.176177Running that should now give us three passing tests::178179 $ python flaskr_tests.py180 ...181 ----------------------------------------------------------------------182 Ran 3 tests in 0.332s183184 OK185186For more complex tests with headers and status codes, check out the

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 187why, one step back
187`MiniTwit Example`_ from the sources which contains a larger test

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 188–197why, one step back
188suite.
189190191.. _MiniTwit Example:192 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/193194195Other Testing Tricks196--------------------197

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 198–201why, one step back
198Besides using the test client as shown above, there is also the
199:meth:`~flask.Flask.test_request_context` method that can be used200in combination with the `with` statement to activate a request context201temporarily. With this you can access the :class:`~flask.request`,

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

line 202why, one step back
202:class:`~flask.g` and :class:`~flask.session` objects like in view

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 203why, one step back
203functions. Here is a full example that demonstrates this approach::

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 204–210why, one step back
204
205 app = flask.Flask(__name__)206207 with app.test_request_context('/?name=Peter'):208 assert flask.request.path == '/'209 assert flask.request.args['name'] == 'Peter'210

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 211–212why, one step back
211All the other objects that are context bound can be used in the same
212way.

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 213–223why, one step back
213
214If you want to test your application with different configurations and215there does not seem to be a good way to do that, consider switching to216application factories (see :ref:`app-factories`).217218219Keeping the Context Around220--------------------------221222.. versionadded:: 0.4223

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 224why, one step back
224Sometimes it is helpful to trigger a regular request but still keep the

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 225–234why, one step back
225context around for a little longer so that additional introspection can
226happen. With Flask 0.4 this is possible by using the227:meth:`~flask.Flask.test_client` with a `with` block::228229 app = flask.Flask(__name__)230231 with app.test_client() as c:232 rv = c.get('/?tequila=42')233 assert request.args['tequila'] == '42'234

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 235why, one step back
235If you were to use just the :meth:`~flask.Flask.test_client` without

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

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

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 237–239why, one step back
237is no longer available (because you are trying to use it outside of the actual request).
238However, keep in mind that any :meth:`~flask.Flask.after_request` functions239are already called at this point so your database connection and

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

line 240why, one step back
240everything involved is probably already closed down.

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

line 241why, one step back
241