Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

307 lines · 11.0 KiB

Last changed by

Merge pull request #308 from DasIch/patch-1Armin Ronacherbefore adoptione28e146

History of this file

Take it

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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.

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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.

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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`_.

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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::

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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()

Mention the TESTING flag in the docsArmin Ronacherbefore adoption7e55b50

line 44why, one step back
44 flaskr.app.config['TESTING'] = True

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 45–55why, one step back
45 self.app = flaskr.app.test_client()
46 flaskr.init_db()4748 def tearDown(self):49 os.close(self.db_fd)50 os.unlink(flaskr.app.config['DATABASE'])5152 if __name__ == '__main__':53 unittest.main()5455The code in the :meth:`~unittest.TestCase.setUp` method creates a new test

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

lines 56–58why, one step back
56client and initializes a new database. This function is called before
57each individual test function is run. To delete the database after the 58test, we close the file and remove it from the filesystem in the

Mention the TESTING flag in the docsArmin Ronacherbefore adoption7e55b50

lines 59–62why, one step back
59:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the
60``TESTING`` config flag is activated. What it does is disabling the error61catching during request handling so that you get better error reports when62performing test requests against the application.

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

line 63why, one step back
63

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 76–83why, one step back
76
77 $ python flaskr_tests.py7879 ----------------------------------------------------------------------80 Ran 0 tests in 0.000s8182 OK83

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 85–90why, one step back
85application is syntactically valid, otherwise the import would have died
86with an exception.8788The First Test89--------------90

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 95–110why, one step back
95
96 class FlaskrTestCase(unittest.TestCase):9798 def setUp(self):99 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()100 self.app = flaskr.app.test_client()101 flaskr.init_db()102103 def tearDown(self):104 os.close(self.db_fd)105 os.unlink(flaskr.DATABASE)106107 def test_empty_db(self):108 rv = self.app.get('/')109 assert 'No entries here so far' in rv.data110

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

line 113why, one step back
113

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 120–132why, one step back
120Run it again and you should see one passing test::
121122 $ python flaskr_tests.py123 .124 ----------------------------------------------------------------------125 Ran 1 test in 0.034s126127 OK128129Logging In and Out130------------------131132The majority of the functionality of our application is only available for

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 137–148why, one step back
137
138Add the following two methods to your `FlaskrTestCase` class::139140 def login(self, username, password):141 return self.app.post('/login', data=dict(142 username=username,143 password=password144 ), follow_redirects=True)145146 def logout(self):147 return self.app.get('/logout', follow_redirects=True)148

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 150–164why, one step back
150invalid credentials. Add this new test to the class::
151152 def test_login_logout(self):153 rv = self.login('admin', 'default')154 assert 'You were logged in' in rv.data155 rv = self.logout()156 assert 'You were logged out' in rv.data157 rv = self.login('adminx', 'default')158 assert 'Invalid username' in rv.data159 rv = self.login('admin', 'defaultx')160 assert 'Invalid password' in rv.data161162Test Adding Messages163--------------------164

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 166–190why, one step back
166like this::
167168 def test_messages(self):169 self.login('admin', 'default')170 rv = self.app.post('/add', data=dict(171 title='<Hello>',172 text='<strong>HTML</strong> allowed here'173 ), follow_redirects=True)174 assert 'No entries here so far' not in rv.data175 assert '&lt;Hello&gt;' in rv.data176 assert '<strong>HTML</strong> allowed here' in rv.data177178Here we check that HTML is allowed in the text but not in the title,179which is the intended behavior.180181Running that should now give us three passing tests::182183 $ python flaskr_tests.py184 ...185 ----------------------------------------------------------------------186 Ran 3 tests in 0.332s187188 OK189190For more complex tests with headers and status codes, check out the

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 192–201why, one step back
192suite.
193194195.. _MiniTwit Example:196 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/197198199Other Testing Tricks200--------------------201

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 208–214why, one step back
208
209 app = flask.Flask(__name__)210211 with app.test_request_context('/?name=Peter'):212 assert flask.request.path == '/'213 assert flask.request.args['name'] == 'Peter'214

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 217–221why, one step back
217
218If you want to test your application with different configurations and219there does not seem to be a good way to do that, consider switching to220application factories (see :ref:`app-factories`).221

Mention the TESTING flag in the docsArmin Ronacherbefore adoption7e55b50

lines 222–223why, one step back
222Note however that if you are using a test request context, the
223:meth:`~flask.Flask.before_request` functions are not automatically called

Fixed a typo in the docs.Armin Ronacherbefore adoptionc8663e8

line 224why, one step back
224same for :meth:`~flask.Flask.after_request` functions. However

Mention the TESTING flag in the docsArmin Ronacherbefore adoption7e55b50

lines 225–228why, one step back
225:meth:`~flask.Flask.teardown_request` functions are indeed executed when
226the test request context leaves the `with` block. If you do want the227:meth:`~flask.Flask.before_request` functions to be called as well, you228need to call :meth:`~flask.Flask.preprocess_request` yourself::

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

line 229why, one step back
229

Mention the TESTING flag in the docsArmin Ronacherbefore adoption7e55b50

lines 230–238why, one step back
230 app = flask.Flask(__name__)
231232 with app.test_request_context('/?name=Peter'):233 app.preprocess_request()234 ...235236This can be necessary to open database connections or something similar237depending on how your application was designed.238

Added an example of how to postprocess requests in the testing docs.Armin Ronacherbefore adoption99c2def

lines 239–252why, one step back
239If you want to call the :meth:`~flask.Flask.after_request` functions you
240need to call into :meth:`~flask.Flask.process_response` which however241requires that you pass it a response object::242243 app = flask.Flask(__name__)244245 with app.test_request_context('/?name=Peter'):246 resp = Response('...')247 resp = app.process_response(resp)248 ...249250This in general is less useful because at that point you can directly251start using the test client.252

Mention the TESTING flag in the docsArmin Ronacherbefore adoption7e55b50

line 253why, one step back
253

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 254–258why, one step back
254Keeping the Context Around
255--------------------------256257.. versionadded:: 0.4258

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

lines 260–269why, one step back
260context around for a little longer so that additional introspection can
261happen. With Flask 0.4 this is possible by using the262:meth:`~flask.Flask.test_client` with a `with` block::263264 app = flask.Flask(__name__)265266 with app.test_client() as c:267 rv = c.get('/?tequila=42')268 assert request.args['tequila'] == '42'269

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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

fixing some wording issues on the testing pagematt swansonbefore adoptionf58c989

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

Fix typo in send_file docsDag Odenhallbefore adoption4a45345

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

Updated documentation regarding the session transactionsArmin Ronacherbefore adoption1ea3d4e

lines 276–283why, one step back
276
277278Accessing and Modifying Sessions279--------------------------------280281.. versionadded:: 0.8282283Sometimes it can be very helpful to access or modify the sessions from the

Merge pull request #308 from DasIch/patch-1Armin Ronacherbefore adoptione28e146

line 284why, one step back
284test client. Generally there are two ways for this. If you just want to

Updated documentation regarding the session transactionsArmin Ronacherbefore adoption1ea3d4e

lines 285–307why, one step back
285ensure that a session has certain keys set to certain values you can just
286keep the context around and access :data:`flask.session`::287288 with app.test_client() as c:289 rv = c.get('/')290 assert flask.session['foo'] == 42291292This however does not make it possible to also modify the session or to293access the session before a request was fired. Starting with Flask 0.8 we294provide a so called “session transaction” which simulates the appropriate295calls to open a session in the context of the test client and to modify296it. At the end of the transaction the session is stored. This works297independently of the session backend used::298299 with app.test_client() as c:300 with c.session_transaction() as sess:301 sess['a_key'] = 'a value'302303 # once this is reached the session was stored304305Note that in this case you have to use the ``sess`` object instead of the306:data:`flask.session` proxy. The object however itself will provide the307same interface.