testing.rst
This file
Path
docs/testing.rst
377 lines · 12.8 KiB
Last changed by
resolve merge conflictsKenneth Reitzbefore adoption31174fe
History of this fileTake 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 back1.. _testing:23Testing Flask Applications4==========================56 **Something that is untested is broken.**7resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 10–13why, 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.13Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 14why, one step back14Flask provides a way to test your application by exposing the WerkzeugMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 15why, one step back15test :class:`~werkzeug.test.Client` and handling the context locals for you.resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 16why, one step back16You can then use that with your favourite testing solution.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 17why, one step back17resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 26–28why, one step back26The Application27---------------28Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 29–30why, one step back29First, we need an application to test; we will use the application from30the :ref:`tutorial`. If you don't have that application yet, get theresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 31why, one step back31source code from `the examples`_.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 32–33why, one step back3233.. _the examples:resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 34why, one step back34 https://github.com/pallets/flask/tree/master/examples/flaskr/Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 35–38why, one step back3536The Testing Skeleton37--------------------38resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 43why, one step back43resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 48–50why, one step back48 import os49 import tempfile50resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 51why, one step back51 import pytestMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 52why, one step back52resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 53why, one step back53 from flaskr import flaskrMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 54–55why, one step back5455resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 61why, one step back61resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 62–63why, one step back62 with flaskr.app.app_context():63 flaskr.init_db()Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 64why, one step back64resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 65why, one step back65 yield clientMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 66why, one step back66resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
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.85resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 89–90why, one step back89If we now run the test suite, we should see the following output::90resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 91why, one step back91 $ pytestMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 92why, one step back92resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 93–95why, one step back93 ================ test session starts ================94 rootdir: ./flask/examples/flaskr, inifile: setup.cfg95 collected 0 itemsMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 96why, one step back96resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 97why, one step back97 =========== no tests ran in 0.07 seconds ============Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 98why, one step back98resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 99why, one step back99Even 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 back100application is syntactically valid, otherwise the import would have died101with an exception.102resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 103–105why, one step back103.. _pytest fixture:104 https://docs.pytest.org/en/latest/fixture.html105Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 106–108why, one step back106The First Test107--------------108Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 109–110why, one step back109Now it's time to start testing the functionality of the application.110Let's check that the application shows "No entries here so far" if weresolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 113why, one step back113resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 114–115why, one step back114 def test_empty_db(client):115 """Start with a blank database."""Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 116why, one step back116resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 117–118why, one step back117 rv = client.get('/')118 assert b'No entries here so far' in rv.dataMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 119why, one step back119Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 120why, one step back120Notice that our test functions begin with the word `test`; this allowsresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 121why, one step back121`pytest`_ to automatically identify the function as a test to run.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 122why, one step back122resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 123why, one step back123By using ``client.get`` we can send an HTTP ``GET`` request to the application withMerge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 124why, one step back124the 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 back125We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspectMerge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 126why, one step back126the return value (as string) from the application. In this case, we ensure thatMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 127–130why, one step back127``'No entries here so far'`` is part of the output.128129Run it again and you should see one passing test::130resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 131why, one step back131 $ pytest -vMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 132why, one step back132resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 133–135why, one step back133 ================ test session starts ================134 rootdir: ./flask/examples/flaskr, inifile: setup.cfg135 collected 1 itemsMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 136why, one step back136resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 137–140why, one step back137 tests/test_flaskr.py::test_empty_db PASSED138139 ============= 1 passed in 0.10 seconds ==============140Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 141–145why, 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 outMerge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 146–147why, one step back146of the application. To do this, we fire some requests to the login and logout147pages with the required form data (username and password). And because theMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 148–149why, one step back148login and logout pages redirect, we tell the client to `follow_redirects`.149resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 150why, one step back150Add the following two functions to your :file:`test_flaskr.py` file::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 151why, one step back151resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 157–158why, one step back157158resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 159–161why, one step back159 def logout(client):160 return client.get('/logout', follow_redirects=True)161Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 162why, one step back162Now we can easily test that logging in and out works and that it fails withresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 163why, one step back163invalid credentials. Add this new test function::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 164why, one step back164resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 165–166why, one step back165 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 back167resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 180–182why, one step back180Test Adding Messages181--------------------182resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 183why, one step back183We should also test that adding messages works. Add a new test functionMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 184–185why, one step back184like this::185resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 191–193why, one step back191 title='<Hello>',192 text='<strong>HTML</strong> allowed here'193 ), follow_redirects=True)resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
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::202resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 203why, one step back203 $ pytest -vMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 204why, one step back204resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 205–207why, one step back205 ================ test session starts ================206 rootdir: ./flask/examples/flaskr, inifile: setup.cfg207 collected 3 itemsMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 208why, one step back208resolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
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:resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 220why, one step back220 https://github.com/pallets/flask/tree/master/examples/minitwit/Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 221–226why, 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 usedMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 227why, one step back227in combination with the ``with`` statement to activate a request contextMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 228–231why, one step back228temporarily. 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::231Merge pull request #1380 from KWinston/masterMarkus Unterwaditzerbefore adoptionb57a076
line 232why, one step back232 import flaskresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 233why, one step back233Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
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, theresolve merge conflictsKenneth Reitzbefore adoption31174fe
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 #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 250why, one step back250:meth:`~flask.Flask.teardown_request` functions are indeed executed whenMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 251why, one step back251the test request context leaves the ``with`` block. If you do want theMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 252–298why, one step back252: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 withoutresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 299why, one step back299having to change some code. This can be accomplished withMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 300–302why, one step back300hooking the :data:`flask.appcontext_pushed` signal::301302 from contextlib import contextmanagerMerge pull request #1313 from homeworkprod/patch-1Markus Unterwaditzerbefore adoptionb68dc78
line 303why, one step back303 from flask import appcontext_pushed, gMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 304–334why, one step back304305 @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 theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 335why, one step back335:meth:`~flask.Flask.test_client` with a ``with`` block::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 336–343why, one step back336337 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` withoutMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 344why, one step back344the ``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 back345is 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.