testing.rst
This file
Path
docs/testing.rst
458 lines · 15.4 KiB
Last changed by
Merge branch '1.0.x'David Lordbefore adoption1351d0a
History of this fileTake it
The walk stopped after 200 commits: lines older than 40745bb point at it.
Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 1–20why, one step back1.. _testing:23Testing Flask Applications4==========================56 **Something that is untested is broken.**78The 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 to10improve 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.16You can then use that with your favourite testing solution.1718In this documentation we will use the `pytest`_ package as the base19framework for our tests. You can install it with ``pip``, like so::20Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 21why, one step back21 $ pip install pytestMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
line 22why, one step back22Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 23why, one step back23.. _pytest: https://docs.pytest.org/Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 24–29why, one step back2425The Application26---------------2728First, we need an application to test; we will use the application from29the :ref:`tutorial`. If you don't have that application yet, get theMerge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2
line 30why, one step back30source code from :gh:`the examples <examples/tutorial>`.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 31–41why, one step back3132The Testing Skeleton33--------------------3435We begin by adding a tests directory under the application root. Then36create a Python file to store our tests (:file:`test_flaskr.py`). When we37format the filename like ``test_*.py``, it will be auto-discoverable by38pytest.3940Next, we create a `pytest fixture`_ called41:func:`client` that configuresMerge pull request #2834 from greyli/remove-unnecessary-periodDavid Lordbefore adoption7627d9c
line 42why, one step back42the application for testing and initializes a new database::Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 43–55why, one step back4344 import os45 import tempfile4647 import pytest4849 from flaskr import flaskr505152 @pytest.fixture53 def client():54 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()55 flaskr.app.config['TESTING'] = TrueMerge pull request #3241 from jon-stumpf/jss-updatesDavid Lordbefore adoption48d0e86
line 56why, one step back56Merge pull request #3240 from ultimecia7/docfixDavid Lordbefore adoption6e995f2
lines 57–60why, one step back57 with flaskr.app.test_client() as client:58 with flaskr.app.app_context():59 flaskr.init_db()60 yield clientMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 61–73why, one step back6162 os.close(db_fd)63 os.unlink(flaskr.app.config['DATABASE'])6465This client fixture will be called by each individual test. It gives us a66simple interface to the application, where we can trigger test requests to the67application. The client will also keep track of cookies for us.6869During setup, the ``TESTING`` config flag is activated. What70this does is disable error catching during request handling, so that71you get better error reports when performing test requests against the72application.73Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 74–76why, one step back74Because SQLite3 is filesystem-based, we can easily use the75:mod:`tempfile` module to create a temporary database and initialize it.76The :func:`~tempfile.mkstemp` function does two things for us: it returns aMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 77–93why, one step back77low-level file handle and a random file name, the latter we use as78database name. We just have to keep the `db_fd` around so that we can use79the :func:`os.close` function to close the file.8081To delete the database after the test, the fixture closes the file and removes82it from the filesystem.8384If we now run the test suite, we should see the following output::8586 $ pytest8788 ================ test session starts ================89 rootdir: ./flask/examples/flaskr, inifile: setup.cfg90 collected 0 items9192 =========== no tests ran in 0.07 seconds ============93Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 94–96why, one step back94Even though it did not run any actual tests, we already know that our95``flaskr`` application is syntactically valid, otherwise the import96would have died with an exception.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 97–117why, one step back9798.. _pytest fixture:99 https://docs.pytest.org/en/latest/fixture.html100101The First Test102--------------103104Now it's time to start testing the functionality of the application.105Let's check that the application shows "No entries here so far" if we106access the root of the application (``/``). To do this, we add a new107test function to :file:`test_flaskr.py`, like this::108109 def test_empty_db(client):110 """Start with a blank database."""111112 rv = client.get('/')113 assert b'No entries here so far' in rv.data114115Notice that our test functions begin with the word `test`; this allows116`pytest`_ to automatically identify the function as a test to run.117Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 118–124why, one step back118By using ``client.get`` we can send an HTTP ``GET`` request to the119application with the given path. The return value will be a120:class:`~flask.Flask.response_class` object. We can now use the121:attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect122the return value (as string) from the application.123In this case, we ensure that ``'No entries here so far'``124is part of the output.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 125–335why, one step back125126Run it again and you should see one passing test::127128 $ pytest -v129130 ================ test session starts ================131 rootdir: ./flask/examples/flaskr, inifile: setup.cfg132 collected 1 items133134 tests/test_flaskr.py::test_empty_db PASSED135136 ============= 1 passed in 0.10 seconds ==============137138Logging 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`.146147Add the following two functions to your :file:`test_flaskr.py` file::148149 def login(client, username, password):150 return client.post('/login', data=dict(151 username=username,152 password=password153 ), follow_redirects=True)154155156 def logout(client):157 return client.get('/logout', follow_redirects=True)158159Now we can easily test that logging in and out works and that it fails with160invalid credentials. Add this new test function::161162 def test_login_logout(client):163 """Make sure login and logout works."""164165 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.data176177Test Adding Messages178--------------------179180We should also test that adding messages works. Add a new test function181like this::182183 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(188 title='<Hello>',189 text='<strong>HTML</strong> allowed here'190 ), follow_redirects=True)191 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.data194195Here 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::199200 $ pytest -v201202 ================ test session starts ================203 rootdir: ./flask/examples/flaskr, inifile: setup.cfg204 collected 3 items205206 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 ==============211212213Other 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 flask224225 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, the239:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`240functions are not called automatically. However241: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 without290having to change some code. This can be accomplished with291hooking 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`Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 336–337why, one step back336is no longer available (because you are trying to use it337outside of the actual request).Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 338–357why, one step back338339340Accessing and Modifying Sessions341--------------------------------342343.. versionadded:: 0.8344345Sometimes it can be very helpful to access or modify the sessions from the346test client. Generally there are two ways for this. If you just want to347ensure that a session has certain keys set to certain values you can just348keep the context around and access :data:`flask.session`::349350 with app.test_client() as c:351 rv = c.get('/')352 assert flask.session['foo'] == 42353354This however does not make it possible to also modify the session or to355access the session before a request was fired. Starting with Flask 0.8 we356provide a so called “session transaction” which simulates the appropriate357calls to open a session in the context of the test client and to modifyMerge branch '1.0.x'David Lordbefore adoption05a4e15
lines 358–359why, one step back358it. At the end of the transaction the session is stored and ready to be359used by the test client. This works independently of the session backend used::Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 360–364why, one step back360361 with app.test_client() as c:362 with c.session_transaction() as sess:363 sess['a_key'] = 'a value'364Merge branch '1.0.x'David Lordbefore adoption05a4e15
lines 365–366why, one step back365 # once this is reached the session was stored and ready to be used by the client366 c.get(...)Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 367–392why, one step back367368Note that in this case you have to use the ``sess`` object instead of the369:data:`flask.session` proxy. The object however itself will provide the370same interface.371372373Testing JSON APIs374-----------------375376.. versionadded:: 1.0377378Flask has great support for JSON, and is a popular choice for building JSON379APIs. Making requests with JSON data and examining JSON data in responses is380very convenient::381382 from flask import request, jsonify383384 @app.route('/api/auth')385 def auth():386 json_data = request.get_json()387 email = json_data['email']388 password = json_data['password']389 return jsonify(token=generate_token(email, password))390391 with app.test_client() as c:392 rv = c.post('/api/auth', json={Merge pull request #2976 from cykerway/masterDavid Lordbefore adoptiondcc02d6
line 393why, one step back393 'email': 'flask@example.com', 'password': 'secret'Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 394–401why, one step back394 })395 json_data = rv.get_json()396 assert verify_token(email, json_data['token'])397398Passing the ``json`` argument in the test client methods sets the request data399to the JSON-serialized object and sets the content type to400``application/json``. You can get the JSON data from the request or response401with ``get_json``.Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 402–408why, one step back402403404.. _testing-cli:405406Testing CLI Commands407--------------------408Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 409–411why, one step back409Click comes with `utilities for testing`_ your CLI commands. A410:class:`~click.testing.CliRunner` runs commands in isolation and411captures the output in a :class:`~click.testing.Result` object.Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
line 412why, one step back412Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 413–417why, one step back413Flask provides :meth:`~flask.Flask.test_cli_runner` to create a414:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the415CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`416method to call commands in the same way they would be called from the417command line. ::Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 418–426why, one step back418419 import click420421 @app.cli.command('hello')422 @click.option('--name', default='World')423 def hello_command(name)424 click.echo(f'Hello, {name}!')425426 def test_hello():Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 427–429why, one step back427 runner = app.test_cli_runner()428429 # invoke the command directlyMerge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 430–432why, one step back430 result = runner.invoke(hello_command, ['--name', 'Flask'])431 assert 'Hello, Flask' in result.output432Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 433–439why, one step back433 # or by name434 result = runner.invoke(args=['hello'])435 assert 'World' in result.output436437In the example above, invoking the command by name is useful because it438verifies that the command was correctly registered with the app.439Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
line 440why, one step back440If you want to test how your command parses parameters, without runningMerge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66
lines 441–442why, one step back441the command, use its :meth:`~click.BaseCommand.make_context` method.442This is useful for testing complex validation rules and custom types. ::Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802
lines 443–456why, one step back443444 def upper(ctx, param, value):445 if value is not None:446 return value.upper()447448 @app.cli.command('hello')449 @click.option('--name', default='World', callback=upper)450 def hello_command(name)451 click.echo(f'Hello, {name}!')452453 def test_hello_params():454 context = hello_command.make_context('hello', ['--name', 'flask'])455 assert context.params['name'] == 'FLASK'456Merge branch '1.0.x'David Lordbefore adoption1351d0a
lines 457–458why, one step back457.. _click: https://click.palletsprojects.com/458.. _utilities for testing: https://click.palletsprojects.com/testing/