testing.rst
This file
Path
docs/testing.rst
377 lines · 12.8 KiB
Last changed by
Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
History of this fileTake it
The walk stopped after 200 commits: lines older than 7df543d point at it.
Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 1–7why, one step back1.. _testing:23Testing Flask Applications4==========================56 **Something that is untested is broken.**7Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 8–9why, one step back8The origin of this quote is unknown and while it is not entirely correct, it9is also not far from the truth. Untested applications make it hard toMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 10–15why, one step back10improve 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.1314Flask provides a way to test your application by exposing the Werkzeug15test :class:`~werkzeug.test.Client` and handling the context locals for you.Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 16why, one step back16You can then use that with your favourite testing solution.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 17why, one step back17Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 18–25why, one step back18In this documentation we will use the `pytest`_ package as the base19framework for our tests. You can install it with ``pip``, like so::2021 pip install pytest2223.. _pytest:24 https://pytest.org25Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 26–30why, one step back26The Application27---------------2829First, we need an application to test; we will use the application from30the :ref:`tutorial`. If you don't have that application yet, get theMerge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 31why, one step back31source code from `the examples`_.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 32–33why, one step back3233.. _the examples:Change to Pallets projectJosé Carlos Garcíabefore adoption567fff9
line 34why, one step back34 https://github.com/pallets/flask/tree/master/examples/flaskr/Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 35–38why, one step back3536The Testing Skeleton37--------------------38Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 39–42why, one step back39We begin by adding a tests directory under the application root. Then40create 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 #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 43why, one step back43Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 44–47why, one step back44Next, we create a `pytest fixture`_ called45:func:`client` that configures46the application for testing and initializes a new database.::47Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 48–50why, one step back48 import os49 import tempfile50Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 51why, one step back51 import pytestMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 52why, one step back52Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 53why, one step back53 from flaskr import flaskrMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 54–55why, one step back5455Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 56–60why, one step back56 @pytest.fixture57 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 #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 61why, one step back61Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 62–63why, one step back62 with flaskr.app.app_context():63 flaskr.init_db()Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 64why, one step back64Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 65why, one step back65 yield clientMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 66why, one step back66Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 67–79why, one step back67 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` moduleMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 80–85why, one step back80to create a temporary database and initialize it. The81: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.85Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 86–88why, one step back86To delete the database after the test, the fixture closes the file and removes87it from the filesystem.88Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 89–90why, one step back89If we now run the test suite, we should see the following output::90Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 91why, one step back91 $ pytestMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 92why, one step back92Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 93–95why, one step back93 ================ test session starts ================94 rootdir: ./flask/examples/flaskr, inifile: setup.cfg95 collected 0 itemsMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 96why, one step back96Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 97why, one step back97 =========== no tests ran in 0.07 seconds ============Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 98why, one step back98Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 99why, one step back99Even though it did not run any actual tests, we already know that our ``flaskr``Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 100–102why, one step back100application is syntactically valid, otherwise the import would have died101with an exception.102Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 103–105why, one step back103.. _pytest fixture:104 https://docs.pytest.org/en/latest/fixture.html105Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 106–110why, one step back106The First Test107--------------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 weMerge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 111–112why, one step back111access the root of the application (``/``). To do this, we add a new112test function to :file:`test_flaskr.py`, like this::Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 113why, one step back113Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 114–115why, one step back114 def test_empty_db(client):115 """Start with a blank database."""Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 116why, one step back116Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 117–118why, one step back117 rv = client.get('/')118 assert b'No entries here so far' in rv.dataMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 119–120why, one step back119120Notice that our test functions begin with the word `test`; this allowsMerge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 121why, one step back121`pytest`_ to automatically identify the function as a test to run.Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 122why, one step back122Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 123why, one step back123By using ``client.get`` we can send an HTTP ``GET`` request to the application withMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 124–130why, one step back124the 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::130Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 131why, one step back131 $ pytest -vMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 132why, one step back132Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 133–135why, one step back133 ================ test session starts ================134 rootdir: ./flask/examples/flaskr, inifile: setup.cfg135 collected 1 itemsMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 136why, one step back136Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 137–140why, one step back137 tests/test_flaskr.py::test_empty_db PASSED138139 ============= 1 passed in 0.10 seconds ==============140Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 141–149why, one step back141Logging In and Out142------------------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`.149Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 150why, one step back150Add the following two functions to your :file:`test_flaskr.py` file::Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 151why, one step back151Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 152–156why, one step back152 def login(client, username, password):153 return client.post('/login', data=dict(154 username=username,155 password=password156 ), follow_redirects=True)Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 157–158why, one step back157158Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 159–161why, one step back159 def logout(client):160 return client.get('/logout', follow_redirects=True)161Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 162why, one step back162Now we can easily test that logging in and out works and that it fails withMerge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 163why, one step back163invalid credentials. Add this new test function::Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 164why, one step back164Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 165–166why, one step back165 def test_login_logout(client):166 """Make sure login and logout works."""Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 167why, one step back167Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 168–179why, one step back168 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.data179Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 180–182why, one step back180Test Adding Messages181--------------------182Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 183why, one step back183We should also test that adding messages works. Add a new test functionMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 184–185why, one step back184like this::185Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 186–190why, one step back186 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 #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 191–193why, one step back191 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 back194 assert b'No entries here so far' not in rv.data195 assert b'<Hello>' in rv.data196 assert b'<strong>HTML</strong> allowed here' in rv.dataMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 197–202why, one step back197198Here 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::202Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 203why, one step back203 $ pytest -vMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 204why, one step back204Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 205–207why, one step back205 ================ test session starts ================206 rootdir: ./flask/examples/flaskr, inifile: setup.cfg207 collected 3 itemsMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
line 208why, one step back208Merge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
lines 209–214why, one step back209 tests/test_flaskr.py::test_empty_db PASSED210 tests/test_flaskr.py::test_login_logout PASSED211 tests/test_flaskr.py::test_messages PASSED212213 ============= 3 passed in 0.23 seconds ==============214Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 215–219why, one step back215For more complex tests with headers and status codes, check out the216`MiniTwit Example`_ from the sources which contains a larger test217suite.218219.. _MiniTwit Example:Change to Pallets projectJosé Carlos Garcíabefore adoption567fff9
line 220why, one step back220 https://github.com/pallets/flask/tree/master/examples/minitwit/Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 221–232why, one step back221222Other 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 flaskMerge branch 'master' into masterKenneth Reitzbefore adoptiond911c89
line 233why, one step back233Merge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 234–247why, one step back234 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, theminor revision of documentation.bagrattebefore adoption9a80fe6
lines 248–249why, one step back248:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`249functions are not called automatically. HoweverMerge pull request #1703 from jeffwidman/masterDavid Lordbefore adoption7df543d
lines 250–377why, one step back250: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.