testing.rst
This file
Path
docs/testing.rst
456 lines · 15.3 KiB
Last changed by
Merge pull request #2834 from greyli/remove-unnecessary-periodDavid Lordbefore adoption7627d9c
History of this fileTake it
The walk stopped after 200 commits: lines older than 7a999cd point at it.
Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
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 branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
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.resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 16why, one step back16You can then use that with your favourite testing solution.Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
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 branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
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 pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
line 31why, one step back31source code from :gh:`the examples <examples/tutorial>`.Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 32–35why, one step back3233The Testing Skeleton34--------------------35resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 36–39why, one step back36We begin by adding a tests directory under the application root. Then37create a Python file to store our tests (:file:`test_flaskr.py`). When we38format the filename like ``test_*.py``, it will be auto-discoverable by39pytest.Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 40why, one step back40resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 41–42why, one step back41Next, we create a `pytest fixture`_ called42:func:`client` that configuresMerge pull request #2834 from greyli/remove-unnecessary-periodDavid Lordbefore adoption7627d9c
line 43why, one step back43the application for testing and initializes a new database::resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 44why, one step back44Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 45–47why, one step back45 import os46 import tempfile47resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 48why, one step back48 import pytestMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 49why, one step back49resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 50why, one step back50 from flaskr import flaskrMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 51–52why, one step back5152resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 53–57why, one step back53 @pytest.fixture54 def client():55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True57 client = flaskr.app.test_client()Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 58why, one step back58resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 59–60why, one step back59 with flaskr.app.app_context():60 flaskr.init_db()Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 61why, one step back61resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 62why, one step back62 yield clientMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 63why, one step back63resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 64–76why, one step back64 os.close(db_fd)65 os.unlink(flaskr.app.config['DATABASE'])6667This client fixture will be called by each individual test. It gives us a68simple interface to the application, where we can trigger test requests to the69application. The client will also keep track of cookies for us.7071During setup, the ``TESTING`` config flag is activated. What72this does is disable error catching during request handling, so that73you get better error reports when performing test requests against the74application.7576Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` moduleMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 77–82why, one step back77to create a temporary database and initialize it. The78:func:`~tempfile.mkstemp` function does two things for us: it returns a79low-level file handle and a random file name, the latter we use as80database name. We just have to keep the `db_fd` around so that we can use81the :func:`os.close` function to close the file.82resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 83–85why, one step back83To delete the database after the test, the fixture closes the file and removes84it from the filesystem.85Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 86–87why, one step back86If we now run the test suite, we should see the following output::87resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 88why, one step back88 $ pytestMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 89why, one step back89resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 90–92why, one step back90 ================ test session starts ================91 rootdir: ./flask/examples/flaskr, inifile: setup.cfg92 collected 0 itemsMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 93why, one step back93resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 94why, one step back94 =========== no tests ran in 0.07 seconds ============Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 95why, one step back95resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 96why, one step back96Even though it did not run any actual tests, we already know that our ``flaskr``Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 97–99why, one step back97application is syntactically valid, otherwise the import would have died98with an exception.99resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 100–102why, one step back100.. _pytest fixture:101 https://docs.pytest.org/en/latest/fixture.html102Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 103–107why, one step back103The First Test104--------------105106Now it's time to start testing the functionality of the application.107Let's check that the application shows "No entries here so far" if weresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 108–109why, one step back108access the root of the application (``/``). To do this, we add a new109test function to :file:`test_flaskr.py`, like this::Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 110why, one step back110resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 111–112why, one step back111 def test_empty_db(client):112 """Start with a blank database."""Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 113why, one step back113resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 114–115why, one step back114 rv = client.get('/')115 assert b'No entries here so far' in rv.dataMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 116–117why, one step back116117Notice that our test functions begin with the word `test`; this allowsresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 118why, one step back118`pytest`_ to automatically identify the function as a test to run.Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 119why, one step back119resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 120why, one step back120By using ``client.get`` we can send an HTTP ``GET`` request to the application withMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 121–127why, one step back121the given path. The return value will be a :class:`~flask.Flask.response_class` object.122We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect123the return value (as string) from the application. In this case, we ensure that124``'No entries here so far'`` is part of the output.125126Run it again and you should see one passing test::127resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 128why, one step back128 $ pytest -vMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 129why, one step back129resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 130–132why, one step back130 ================ test session starts ================131 rootdir: ./flask/examples/flaskr, inifile: setup.cfg132 collected 1 itemsMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 133why, one step back133resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 134–137why, one step back134 tests/test_flaskr.py::test_empty_db PASSED135136 ============= 1 passed in 0.10 seconds ==============137Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 138–146why, one step back138Logging In and Out139------------------140141The majority of the functionality of our application is only available for142the administrative user, so we need a way to log our test client in and out143of the application. To do this, we fire some requests to the login and logout144pages with the required form data (username and password). And because the145login and logout pages redirect, we tell the client to `follow_redirects`.146resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 147why, one step back147Add the following two functions to your :file:`test_flaskr.py` file::Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 148why, one step back148resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 149–153why, one step back149 def login(client, username, password):150 return client.post('/login', data=dict(151 username=username,152 password=password153 ), follow_redirects=True)Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 154–155why, one step back154155resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 156–158why, one step back156 def logout(client):157 return client.get('/logout', follow_redirects=True)158Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 159why, one step back159Now we can easily test that logging in and out works and that it fails withresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 160why, one step back160invalid credentials. Add this new test function::Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 161why, one step back161resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 162–163why, one step back162 def test_login_logout(client):163 """Make sure login and logout works."""Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 164why, one step back164resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 165–176why, one step back165 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])166 assert b'You were logged in' in rv.data167168 rv = logout(client)169 assert b'You were logged out' in rv.data170171 rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])172 assert b'Invalid username' in rv.data173174 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')175 assert b'Invalid password' in rv.data176Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 177–179why, one step back177Test Adding Messages178--------------------179resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 180why, one step back180We should also test that adding messages works. Add a new test functionMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 181–182why, one step back181like this::182resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 183–187why, one step back183 def test_messages(client):184 """Test that messages work."""185186 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])187 rv = client.post('/add', data=dict(Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 188–190why, one step back188 title='<Hello>',189 text='<strong>HTML</strong> allowed here'190 ), follow_redirects=True)resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 191–193why, one step back191 assert b'No entries here so far' not in rv.data192 assert b'<Hello>' in rv.data193 assert b'<strong>HTML</strong> allowed here' in rv.dataMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 194–199why, one step back194195Here we check that HTML is allowed in the text but not in the title,196which is the intended behavior.197198Running that should now give us three passing tests::199resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 200why, one step back200 $ pytest -vMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 201why, one step back201resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 202–204why, one step back202 ================ test session starts ================203 rootdir: ./flask/examples/flaskr, inifile: setup.cfg204 collected 3 itemsMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
line 205why, one step back205resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 206–211why, one step back206 tests/test_flaskr.py::test_empty_db PASSED207 tests/test_flaskr.py::test_login_logout PASSED208 tests/test_flaskr.py::test_messages PASSED209210 ============= 3 passed in 0.23 seconds ==============211Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 212–223why, one step back212213Other Testing Tricks214--------------------215216Besides using the test client as shown above, there is also the217:meth:`~flask.Flask.test_request_context` method that can be used218in combination with the ``with`` statement to activate a request context219temporarily. With this you can access the :class:`~flask.request`,220:class:`~flask.g` and :class:`~flask.session` objects like in view221functions. Here is a full example that demonstrates this approach::222223 import flaskresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 224why, one step back224Merge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 225–238why, one step back225 app = flask.Flask(__name__)226227 with app.test_request_context('/?name=Peter'):228 assert flask.request.path == '/'229 assert flask.request.args['name'] == 'Peter'230231All the other objects that are context bound can be used in the same232way.233234If you want to test your application with different configurations and235there does not seem to be a good way to do that, consider switching to236application factories (see :ref:`app-factories`).237238Note however that if you are using a test request context, theresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 239–240why, one step back239:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`240functions are not called automatically. HoweverMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 241–289why, one step back241:meth:`~flask.Flask.teardown_request` functions are indeed executed when242the test request context leaves the ``with`` block. If you do want the243:meth:`~flask.Flask.before_request` functions to be called as well, you244need to call :meth:`~flask.Flask.preprocess_request` yourself::245246 app = flask.Flask(__name__)247248 with app.test_request_context('/?name=Peter'):249 app.preprocess_request()250 ...251252This can be necessary to open database connections or something similar253depending on how your application was designed.254255If you want to call the :meth:`~flask.Flask.after_request` functions you256need to call into :meth:`~flask.Flask.process_response` which however257requires that you pass it a response object::258259 app = flask.Flask(__name__)260261 with app.test_request_context('/?name=Peter'):262 resp = Response('...')263 resp = app.process_response(resp)264 ...265266This in general is less useful because at that point you can directly267start using the test client.268269.. _faking-resources:270271Faking Resources and Context272----------------------------273274.. versionadded:: 0.10275276A very common pattern is to store user authorization information and277database connections on the application context or the :attr:`flask.g`278object. The general pattern for this is to put the object on there on279first usage and then to remove it on a teardown. Imagine for instance280this code to get the current user::281282 def get_user():283 user = getattr(g, 'user', None)284 if user is None:285 user = fetch_current_user_from_database()286 g.user = user287 return user288289For a test it would be nice to override this user from the outside withoutresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 290why, one step back290having to change some code. This can be accomplished withMerge branch 'AndrewBMartin-patch-1'Markus Unterwaditzerbefore adoption7a999cd
lines 291–368why, one step back291hooking the :data:`flask.appcontext_pushed` signal::292293 from contextlib import contextmanager294 from flask import appcontext_pushed, g295296 @contextmanager297 def user_set(app, user):298 def handler(sender, **kwargs):299 g.user = user300 with appcontext_pushed.connected_to(handler, app):301 yield302303And then to use it::304305 from flask import json, jsonify306307 @app.route('/users/me')308 def users_me():309 return jsonify(username=g.user.username)310311 with user_set(app, my_user):312 with app.test_client() as c:313 resp = c.get('/users/me')314 data = json.loads(resp.data)315 self.assert_equal(data['username'], my_user.username)316317318Keeping the Context Around319--------------------------320321.. versionadded:: 0.4322323Sometimes it is helpful to trigger a regular request but still keep the324context around for a little longer so that additional introspection can325happen. With Flask 0.4 this is possible by using the326:meth:`~flask.Flask.test_client` with a ``with`` block::327328 app = flask.Flask(__name__)329330 with app.test_client() as c:331 rv = c.get('/?tequila=42')332 assert request.args['tequila'] == '42'333334If you were to use just the :meth:`~flask.Flask.test_client` without335the ``with`` block, the ``assert`` would fail with an error because `request`336is no longer available (because you are trying to use it outside of the actual request).337338339Accessing and Modifying Sessions340--------------------------------341342.. versionadded:: 0.8343344Sometimes it can be very helpful to access or modify the sessions from the345test client. Generally there are two ways for this. If you just want to346ensure that a session has certain keys set to certain values you can just347keep the context around and access :data:`flask.session`::348349 with app.test_client() as c:350 rv = c.get('/')351 assert flask.session['foo'] == 42352353This however does not make it possible to also modify the session or to354access the session before a request was fired. Starting with Flask 0.8 we355provide a so called “session transaction” which simulates the appropriate356calls to open a session in the context of the test client and to modify357it. At the end of the transaction the session is stored. This works358independently of the session backend used::359360 with app.test_client() as c:361 with c.session_transaction() as sess:362 sess['a_key'] = 'a value'363364 # once this is reached the session was stored365366Note that in this case you have to use the ``sess`` object instead of the367:data:`flask.session` proxy. The object however itself will provide the368same interface.Merge pull request #2358 from davidism/json-mixinDavid Lordbefore adoption63129e8
lines 369–399why, one step back369370371Testing JSON APIs372-----------------373374.. versionadded:: 1.0375376Flask has great support for JSON, and is a popular choice for building JSON377APIs. Making requests with JSON data and examining JSON data in responses is378very convenient::379380 from flask import request, jsonify381382 @app.route('/api/auth')383 def auth():384 json_data = request.get_json()385 email = json_data['email']386 password = json_data['password']387 return jsonify(token=generate_token(email, password))388389 with app.test_client() as c:390 rv = c.post('/api/auth', json={391 'username': 'flask', 'password': 'secret'392 })393 json_data = rv.get_json()394 assert verify_token(email, json_data['token'])395396Passing the ``json`` argument in the test client methods sets the request data397to the JSON-serialized object and sets the content type to398``application/json``. You can get the JSON data from the request or response399with ``get_json``.Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 400–406why, one step back400401402.. _testing-cli:403404Testing CLI Commands405--------------------406Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 407–409why, one step back407Click comes with `utilities for testing`_ your CLI commands. A408:class:`~click.testing.CliRunner` runs commands in isolation and409captures the output in a :class:`~click.testing.Result` object.Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
line 410why, one step back410Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 411–415why, one step back411Flask provides :meth:`~flask.Flask.test_cli_runner` to create a412:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the413CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`414method to call commands in the same way they would be called from the415command line. ::Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 416–424why, one step back416417 import click418419 @app.cli.command('hello')420 @click.option('--name', default='World')421 def hello_command(name)422 click.echo(f'Hello, {name}!')423424 def test_hello():Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 425–427why, one step back425 runner = app.test_cli_runner()426427 # invoke the command directlyMerge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 428–430why, one step back428 result = runner.invoke(hello_command, ['--name', 'Flask'])429 assert 'Hello, Flask' in result.output430Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 431–437why, one step back431 # or by name432 result = runner.invoke(args=['hello'])433 assert 'World' in result.output434435In the example above, invoking the command by name is useful because it436verifies that the command was correctly registered with the app.437Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
line 438why, one step back438If you want to test how your command parses parameters, without runningMerge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 439–440why, one step back439the command, use its :meth:`~click.BaseCommand.make_context` method.440This is useful for testing complex validation rules and custom types. ::Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 441–456why, one step back441442 def upper(ctx, param, value):443 if value is not None:444 return value.upper()445446 @app.cli.command('hello')447 @click.option('--name', default='World', callback=upper)448 def hello_command(name)449 click.echo(f'Hello, {name}!')450451 def test_hello_params():452 context = hello_command.make_context('hello', ['--name', 'flask'])453 assert context.params['name'] == 'FLASK'454455.. _click: http://click.pocoo.org/456.. _utilities for testing: http://click.pocoo.org/testing