Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

377 lines · 12.8 KiB

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

History of this file

Take it

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 10–13why, one step back
10improve existing code and developers of untested applications tend to
11become 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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 15why, one step back
15test :class:`~werkzeug.test.Client` and handling the context locals for you.

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 16why, one step back
16You can then use that with your favourite testing solution.

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 17why, one step back
17

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 18–25why, one step back
18In this documentation we will use the `pytest`_ package as the base
19framework for our tests. You can install it with ``pip``, like so::2021 pip install pytest2223.. _pytest:24 https://pytest.org25

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 26–28why, one step back
26The Application
27---------------28

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

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 31why, one step back
31source code from `the examples`_.

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 32–33why, one step back
32
33.. _the examples:

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 35–38why, one step back
35
36The Testing Skeleton37--------------------38

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 39–42why, one step back
39We begin by adding a tests directory under the application root. Then
40create a Python file to store our tests (:file:`test_flaskr.py`). When we41format the filename like ``test_*.py``, it will be auto-discoverable by42pytest.

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 43why, one step back
43

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 44–47why, one step back
44Next, we create a `pytest fixture`_ called
45:func:`client` that configures46the application for testing and initializes a new database.::47

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 48–50why, one step back
48 import os
49 import tempfile50

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 51why, one step back
51 import pytest

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 52why, one step back
52

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 53why, one step back
53 from flaskr import flaskr

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 54–55why, one step back
54
55

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 56–60why, one step back
56 @pytest.fixture
57 def client():58 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()59 flaskr.app.config['TESTING'] = True60 client = flaskr.app.test_client()

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 61why, one step back
61

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 64why, one step back
64

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 65why, one step back
65 yield client

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 66why, one step back
66

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 67–79why, one step back
67 os.close(db_fd)
68 os.unlink(flaskr.app.config['DATABASE'])6970This client fixture will be called by each individual test. It gives us a71simple interface to the application, where we can trigger test requests to the72application. The client will also keep track of cookies for us.7374During setup, the ``TESTING`` config flag is activated. What75this does is disable error catching during request handling, so that76you get better error reports when performing test requests against the77application.7879Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 80–85why, one step back
80to create a temporary database and initialize it. The
81:func:`~tempfile.mkstemp` function does two things for us: it returns a82low-level file handle and a random file name, the latter we use as83database name. We just have to keep the `db_fd` around so that we can use84the :func:`os.close` function to close the file.85

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 86–88why, one step back
86To delete the database after the test, the fixture closes the file and removes
87it from the filesystem.88

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 89–90why, one step back
89If we now run the test suite, we should see the following output::
90

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 91why, one step back
91 $ pytest

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 92why, one step back
92

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 93–95why, one step back
93 ================ test session starts ================
94 rootdir: ./flask/examples/flaskr, inifile: setup.cfg95 collected 0 items

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 96why, one step back
96

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 97why, one step back
97 =========== no tests ran in 0.07 seconds ============

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 98why, one step back
98

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 100–102why, one step back
100application is syntactically valid, otherwise the import would have died
101with an exception.102

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 103–105why, one step back
103.. _pytest fixture:
104 https://docs.pytest.org/en/latest/fixture.html105

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 106–108why, one step back
106The First Test
107--------------108

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

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 111–112why, one step back
111access the root of the application (``/``). To do this, we add a new
112test function to :file:`test_flaskr.py`, like this::

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 113why, one step back
113

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 114–115why, one step back
114 def test_empty_db(client):
115 """Start with a blank database."""

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 116why, one step back
116

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 117–118why, one step back
117 rv = client.get('/')
118 assert b'No entries here so far' in rv.data

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 119why, one step back
119

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

line 120why, one step back
120Notice that our test functions begin with the word `test`; this allows

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 121why, one step back
121`pytest`_ to automatically identify the function as a test to run.

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 122why, one step back
122

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

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

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

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

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

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 127–130why, one step back
127``'No entries here so far'`` is part of the output.
128129Run it again and you should see one passing test::130

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 131why, one step back
131 $ pytest -v

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 132why, one step back
132

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 133–135why, one step back
133 ================ test session starts ================
134 rootdir: ./flask/examples/flaskr, inifile: setup.cfg135 collected 1 items

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 136why, one step back
136

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 137–140why, one step back
137 tests/test_flaskr.py::test_empty_db PASSED
138139 ============= 1 passed in 0.10 seconds ==============140

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 141–145why, one step back
141Logging In and Out
142------------------143144The majority of the functionality of our application is only available for145the 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 146–147why, one step back
146of the application. To do this, we fire some requests to the login and logout
147pages with the required form data (username and password). And because the

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 148–149why, one step back
148login and logout pages redirect, we tell the client to `follow_redirects`.
149

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 150why, one step back
150Add the following two functions to your :file:`test_flaskr.py` file::

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 151why, one step back
151

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 152–156why, one step back
152 def login(client, username, password):
153 return client.post('/login', data=dict(154 username=username,155 password=password156 ), follow_redirects=True)

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 157–158why, one step back
157
158

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 159–161why, one step back
159 def logout(client):
160 return client.get('/logout', follow_redirects=True)161

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 163why, one step back
163invalid credentials. Add this new test function::

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 164why, one step back
164

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 165–166why, one step back
165 def test_login_logout(client):
166 """Make sure login and logout works."""

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 167why, one step back
167

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 168–179why, one step back
168 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])
169 assert b'You were logged in' in rv.data170171 rv = logout(client)172 assert b'You were logged out' in rv.data173174 rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])175 assert b'Invalid username' in rv.data176177 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')178 assert b'Invalid password' in rv.data179

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 180–182why, one step back
180Test Adding Messages
181--------------------182

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 184–185why, one step back
184like this::
185

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 186–190why, one step back
186 def test_messages(client):
187 """Test that messages work."""188189 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])190 rv = client.post('/add', data=dict(

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 191–193why, one step back
191 title='<Hello>',
192 text='<strong>HTML</strong> allowed here'193 ), follow_redirects=True)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 194–196why, one step back
194 assert b'No entries here so far' not in rv.data
195 assert b'&lt;Hello&gt;' in rv.data196 assert b'<strong>HTML</strong> allowed here' in rv.data

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 197–202why, one step back
197
198Here we check that HTML is allowed in the text but not in the title,199which is the intended behavior.200201Running that should now give us three passing tests::202

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 203why, one step back
203 $ pytest -v

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 204why, one step back
204

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 205–207why, one step back
205 ================ test session starts ================
206 rootdir: ./flask/examples/flaskr, inifile: setup.cfg207 collected 3 items

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

line 208why, one step back
208

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 209–214why, one step back
209 tests/test_flaskr.py::test_empty_db PASSED
210 tests/test_flaskr.py::test_login_logout PASSED211 tests/test_flaskr.py::test_messages PASSED212213 ============= 3 passed in 0.23 seconds ==============214

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 215–219why, one step back
215For more complex tests with headers and status codes, check out the
216`MiniTwit Example`_ from the sources which contains a larger test217suite.218219.. _MiniTwit Example:

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 221–226why, one step back
221
222Other Testing Tricks223--------------------224225Besides using the test client as shown above, there is also the226:meth:`~flask.Flask.test_request_context` method that can be used

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

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

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

Merge pull request #1380 from KWinston/masterMarkus Unterwaditzerbefore adoptionb57a076

line 232why, one step back
232 import flask

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 233why, one step back
233

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 234–247why, one step back
234 app = flask.Flask(__name__)
235236 with app.test_request_context('/?name=Peter'):237 assert flask.request.path == '/'238 assert flask.request.args['name'] == 'Peter'239240All the other objects that are context bound can be used in the same241way.242243If you want to test your application with different configurations and244there does not seem to be a good way to do that, consider switching to245application factories (see :ref:`app-factories`).246247Note however that if you are using a test request context, the

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

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

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

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 252–298why, one step back
252:meth:`~flask.Flask.before_request` functions to be called as well, you
253need to call :meth:`~flask.Flask.preprocess_request` yourself::254255 app = flask.Flask(__name__)256257 with app.test_request_context('/?name=Peter'):258 app.preprocess_request()259 ...260261This can be necessary to open database connections or something similar262depending on how your application was designed.263264If you want to call the :meth:`~flask.Flask.after_request` functions you265need to call into :meth:`~flask.Flask.process_response` which however266requires that you pass it a response object::267268 app = flask.Flask(__name__)269270 with app.test_request_context('/?name=Peter'):271 resp = Response('...')272 resp = app.process_response(resp)273 ...274275This in general is less useful because at that point you can directly276start using the test client.277278.. _faking-resources:279280Faking Resources and Context281----------------------------282283.. versionadded:: 0.10284285A very common pattern is to store user authorization information and286database connections on the application context or the :attr:`flask.g`287object. The general pattern for this is to put the object on there on288first usage and then to remove it on a teardown. Imagine for instance289this code to get the current user::290291 def get_user():292 user = getattr(g, 'user', None)293 if user is None:294 user = fetch_current_user_from_database()295 g.user = user296 return user297298For a test it would be nice to override this user from the outside without

resolve merge conflictsKenneth Reitzbefore adoption31174fe

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 300–302why, one step back
300hooking the :data:`flask.appcontext_pushed` signal::
301302 from contextlib import contextmanager

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

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 304–334why, one step back
304
305 @contextmanager306 def user_set(app, user):307 def handler(sender, **kwargs):308 g.user = user309 with appcontext_pushed.connected_to(handler, app):310 yield311312And then to use it::313314 from flask import json, jsonify315316 @app.route('/users/me')317 def users_me():318 return jsonify(username=g.user.username)319320 with user_set(app, my_user):321 with app.test_client() as c:322 resp = c.get('/users/me')323 data = json.loads(resp.data)324 self.assert_equal(data['username'], my_user.username)325326327Keeping the Context Around328--------------------------329330.. versionadded:: 0.4331332Sometimes it is helpful to trigger a regular request but still keep the333context around for a little longer so that additional introspection can334happen. With Flask 0.4 this is possible by using the

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

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

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 336–343why, one step back
336
337 app = flask.Flask(__name__)338339 with app.test_client() as c:340 rv = c.get('/?tequila=42')341 assert request.args['tequila'] == '42'342343If 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 344why, one step back
344the ``with`` block, the ``assert`` would fail with an error because `request`

Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b

lines 345–377why, one step back
345is no longer available (because you are trying to use it outside of the actual request).
346347348Accessing and Modifying Sessions349--------------------------------350351.. versionadded:: 0.8352353Sometimes it can be very helpful to access or modify the sessions from the354test client. Generally there are two ways for this. If you just want to355ensure that a session has certain keys set to certain values you can just356keep the context around and access :data:`flask.session`::357358 with app.test_client() as c:359 rv = c.get('/')360 assert flask.session['foo'] == 42361362This however does not make it possible to also modify the session or to363access the session before a request was fired. Starting with Flask 0.8 we364provide a so called “session transaction” which simulates the appropriate365calls to open a session in the context of the test client and to modify366it. At the end of the transaction the session is stored. This works367independently of the session backend used::368369 with app.test_client() as c:370 with c.session_transaction() as sess:371 sess['a_key'] = 'a value'372373 # once this is reached the session was stored374375Note that in this case you have to use the ``sess`` object instead of the376:data:`flask.session` proxy. The object however itself will provide the377same interface.