Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

377 lines · 12.8 KiB

Last changed by

Merge pull request #2318 from bovarysme/fix-testing-docsDavid Lordbefore adoption81c2440

History of this file

Take it

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 10–15why, 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.1314Flask provides a way to test your application by exposing the Werkzeug15test :class:`~werkzeug.test.Client` and handling the context locals for you.

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 17why, one step back
17

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 26–30why, one step back
26The Application
27---------------2829First, we need an application to test; we will use the application from30the :ref:`tutorial`. If you don't have that application yet, get the

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 32–38why, one step back
32
33.. _the examples:34 https://github.com/pallets/flask/tree/master/examples/flaskr/3536The Testing Skeleton37--------------------38

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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.

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 43why, one step back
43

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

line 51why, one step back
51 import pytest

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 52why, one step back
52

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 54–55why, one step back
54
55

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

line 56why, one step back
56 @pytest.fixture

Merge pull request #2318 from bovarysme/fix-testing-docsDavid Lordbefore adoption81c2440

line 57why, one step back
57 def client():

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 61why, one step back
61

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 64why, one step back
64

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

line 65why, one step back
65 yield client

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 66why, one step back
66

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

line 91why, one step back
91 $ pytest

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 92why, one step back
92

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 96why, one step back
96

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 98why, one step back
98

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 106–110why, one step back
106The First Test
107--------------108109Now 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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 113why, one step back
113

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 116why, one step back
116

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 122why, one step back
122

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 124–130why, one step back
124the given path. The return value will be a :class:`~flask.Flask.response_class` object.
125We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect126the return value (as string) from the application. In this case, we ensure that127``'No entries here so far'`` is part of the output.128129Run it again and you should see one passing test::130

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 132why, one step back
132

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 136why, one step back
136

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 141–149why, 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 out146of the application. To do this, we fire some requests to the login and logout147pages with the required form data (username and password). And because the148login and logout pages redirect, we tell the client to `follow_redirects`.149

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 151why, one step back
151

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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)

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 157–158why, one step back
157
158

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 164why, one step back
164

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 167why, one step back
167

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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(

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Update testing.rst (#1987)teichopsia-before adoption5044f3d

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

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

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 204why, one step back
204

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

line 208why, one step back
208

Merge pull request #2307 from neilvictorgrey/masterDavid Lordbefore adoptioncd593bf

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

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 215–232why, 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:220 https://github.com/pallets/flask/tree/master/examples/minitwit/221222Other Testing Tricks223--------------------224225Besides using the test client as shown above, there is also the226:meth:`~flask.Flask.test_request_context` method that can be used227in combination with the ``with`` statement to activate a request context228temporarily. 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::231232 import flask

Merge pull request #2117 from accraze/testing-docs-fixDavid Lordbefore adoption5b9b180

line 233why, one step back
233

Expanding contribution documentation (#1883)Joshbefore adoptionbbd6c8c

lines 234–377why, 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, the248:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`249functions are not called automatically. However250:meth:`~flask.Flask.teardown_request` functions are indeed executed when251the test request context leaves the ``with`` block. If you do want the252:meth:`~flask.Flask.before_request` functions to be called as well, you253need 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 without299having to change some code. This can be accomplished with300hooking the :data:`flask.appcontext_pushed` signal::301302 from contextlib import contextmanager303 from flask import appcontext_pushed, g304305 @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 the335:meth:`~flask.Flask.test_client` with a ``with`` block::336337 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` without344the ``with`` block, the ``assert`` would fail with an error because `request`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.