testing.rst
This file
Path
docs/testing.rst
462 lines · 15.5 KiB
Last changed by
Merge pull request #3894 from pallets/update-werkzeugDavid Lordbefore adoption9f7ac04
History of this fileTake it
1Testing Flask Applications2==========================34 **Something that is untested is broken.**56The origin of this quote is unknown and while it is not entirely correct, it7is also not far from the truth. Untested applications make it hard to8improve existing code and developers of untested applications tend to9become pretty paranoid. If an application has automated tests, you can10safely make changes and instantly know if anything breaks.1112Flask provides a way to test your application by exposing the Werkzeug13test :class:`~werkzeug.test.Client` and handling the context locals for you.14You can then use that with your favourite testing solution.1516In this documentation we will use the `pytest`_ package as the base17framework for our tests. You can install it with ``pip``, like so::1819 $ pip install pytest2021.. _pytest: https://docs.pytest.org/2223The Application24---------------2526First, we need an application to test; we will use the application from27the :doc:`tutorial/index`. If you don't have that application yet, get28the source code from :gh:`the examples <examples/tutorial>`.2930So that we can import the module ``flaskr`` correctly, we need to run31``pip install -e .`` in the folder ``tutorial``.3233The Testing Skeleton34--------------------3536We 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.4041Next, we create a `pytest fixture`_ called42:func:`client` that configures43the application for testing and initializes a new database::4445 import os46 import tempfile4748 import pytest4950 from flaskr import create_app515253 @pytest.fixture54 def client():55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True5758 with flaskr.app.test_client() as client:59 with flaskr.app.app_context():60 flaskr.init_db()61 yield client6263 os.close(db_fd)64 os.unlink(flaskr.app.config['DATABASE'])6566This client fixture will be called by each individual test. It gives us a67simple interface to the application, where we can trigger test requests to the68application. The client will also keep track of cookies for us.6970During setup, the ``TESTING`` config flag is activated. What71this does is disable error catching during request handling, so that72you get better error reports when performing test requests against the73application.7475Because SQLite3 is filesystem-based, we can easily use the76:mod:`tempfile` module to create a temporary database and initialize it.77The :func:`~tempfile.mkstemp` function does two things for us: it returns a78low-level file handle and a random file name, the latter we use as79database name. We just have to keep the `db_fd` around so that we can use80the :func:`os.close` function to close the file.8182To delete the database after the test, the fixture closes the file and removes83it from the filesystem.8485If we now run the test suite, we should see the following output::8687 $ pytest8889 ================ test session starts ================90 rootdir: ./flask/examples/flaskr, inifile: setup.cfg91 collected 0 items9293 =========== no tests ran in 0.07 seconds ============9495Even though it did not run any actual tests, we already know that our96``flaskr`` application is syntactically valid, otherwise the import97would have died with an exception.9899.. _pytest fixture:100 https://docs.pytest.org/en/latest/fixture.html101102The First Test103--------------104105Now it's time to start testing the functionality of the application.106Let's check that the application shows "No entries here so far" if we107access the root of the application (``/``). To do this, we add a new108test function to :file:`test_flaskr.py`, like this::109110 def test_empty_db(client):111 """Start with a blank database."""112113 rv = client.get('/')114 assert b'No entries here so far' in rv.data115116Notice that our test functions begin with the word `test`; this allows117`pytest`_ to automatically identify the function as a test to run.118119By using ``client.get`` we can send an HTTP ``GET`` request to the120application with the given path. The return value will be a121:class:`~flask.Flask.response_class` object. We can now use the122:attr:`~werkzeug.wrappers.Response.data` attribute to inspect123the return value (as string) from the application.124In this case, we ensure that ``'No entries here so far'``125is part of the output.126127Run it again and you should see one passing test::128129 $ pytest -v130131 ================ test session starts ================132 rootdir: ./flask/examples/flaskr, inifile: setup.cfg133 collected 1 items134135 tests/test_flaskr.py::test_empty_db PASSED136137 ============= 1 passed in 0.10 seconds ==============138139Logging In and Out140------------------141142The majority of the functionality of our application is only available for143the administrative user, so we need a way to log our test client in and out144of the application. To do this, we fire some requests to the login and logout145pages with the required form data (username and password). And because the146login and logout pages redirect, we tell the client to `follow_redirects`.147148Add the following two functions to your :file:`test_flaskr.py` file::149150 def login(client, username, password):151 return client.post('/login', data=dict(152 username=username,153 password=password154 ), follow_redirects=True)155156157 def logout(client):158 return client.get('/logout', follow_redirects=True)159160Now we can easily test that logging in and out works and that it fails with161invalid credentials. Add this new test function::162163 def test_login_logout(client):164 """Make sure login and logout works."""165166 username = flaskr.app.config["USERNAME"]167 password = flaskr.app.config["PASSWORD"]168169 rv = login(client, username, password)170 assert b'You were logged in' in rv.data171172 rv = logout(client)173 assert b'You were logged out' in rv.data174175 rv = login(client, f"{username}x", password)176 assert b'Invalid username' in rv.data177178 rv = login(client, username, f'{password}x')179 assert b'Invalid password' in rv.data180181Test Adding Messages182--------------------183184We should also test that adding messages works. Add a new test function185like this::186187 def test_messages(client):188 """Test that messages work."""189190 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])191 rv = client.post('/add', data=dict(192 title='<Hello>',193 text='<strong>HTML</strong> allowed here'194 ), follow_redirects=True)195 assert b'No entries here so far' not in rv.data196 assert b'<Hello>' in rv.data197 assert b'<strong>HTML</strong> allowed here' in rv.data198199Here we check that HTML is allowed in the text but not in the title,200which is the intended behavior.201202Running that should now give us three passing tests::203204 $ pytest -v205206 ================ test session starts ================207 rootdir: ./flask/examples/flaskr, inifile: setup.cfg208 collected 3 items209210 tests/test_flaskr.py::test_empty_db PASSED211 tests/test_flaskr.py::test_login_logout PASSED212 tests/test_flaskr.py::test_messages PASSED213214 ============= 3 passed in 0.23 seconds ==============215216217Other Testing Tricks218--------------------219220Besides using the test client as shown above, there is also the221:meth:`~flask.Flask.test_request_context` method that can be used222in combination with the ``with`` statement to activate a request context223temporarily. With this you can access the :class:`~flask.request`,224:class:`~flask.g` and :class:`~flask.session` objects like in view225functions. Here is a full example that demonstrates this approach::226227 import flask228229 app = flask.Flask(__name__)230231 with app.test_request_context('/?name=Peter'):232 assert flask.request.path == '/'233 assert flask.request.args['name'] == 'Peter'234235All the other objects that are context bound can be used in the same236way.237238If you want to test your application with different configurations and239there does not seem to be a good way to do that, consider switching to240application factories (see :doc:`patterns/appfactories`).241242Note however that if you are using a test request context, the243:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`244functions are not called automatically. However245:meth:`~flask.Flask.teardown_request` functions are indeed executed when246the test request context leaves the ``with`` block. If you do want the247:meth:`~flask.Flask.before_request` functions to be called as well, you248need to call :meth:`~flask.Flask.preprocess_request` yourself::249250 app = flask.Flask(__name__)251252 with app.test_request_context('/?name=Peter'):253 app.preprocess_request()254 ...255256This can be necessary to open database connections or something similar257depending on how your application was designed.258259If you want to call the :meth:`~flask.Flask.after_request` functions you260need to call into :meth:`~flask.Flask.process_response` which however261requires that you pass it a response object::262263 app = flask.Flask(__name__)264265 with app.test_request_context('/?name=Peter'):266 resp = Response('...')267 resp = app.process_response(resp)268 ...269270This in general is less useful because at that point you can directly271start using the test client.272273.. _faking-resources:274275Faking Resources and Context276----------------------------277278.. versionadded:: 0.10279280A very common pattern is to store user authorization information and281database connections on the application context or the :attr:`flask.g`282object. The general pattern for this is to put the object on there on283first usage and then to remove it on a teardown. Imagine for instance284this code to get the current user::285286 def get_user():287 user = getattr(g, 'user', None)288 if user is None:289 user = fetch_current_user_from_database()290 g.user = user291 return user292293For a test it would be nice to override this user from the outside without294having to change some code. This can be accomplished with295hooking the :data:`flask.appcontext_pushed` signal::296297 from contextlib import contextmanager298 from flask import appcontext_pushed, g299300 @contextmanager301 def user_set(app, user):302 def handler(sender, **kwargs):303 g.user = user304 with appcontext_pushed.connected_to(handler, app):305 yield306307And then to use it::308309 from flask import json, jsonify310311 @app.route('/users/me')312 def users_me():313 return jsonify(username=g.user.username)314315 with user_set(app, my_user):316 with app.test_client() as c:317 resp = c.get('/users/me')318 data = json.loads(resp.data)319 assert data['username'] == my_user.username320321322Keeping the Context Around323--------------------------324325.. versionadded:: 0.4326327Sometimes it is helpful to trigger a regular request but still keep the328context around for a little longer so that additional introspection can329happen. With Flask 0.4 this is possible by using the330:meth:`~flask.Flask.test_client` with a ``with`` block::331332 app = flask.Flask(__name__)333334 with app.test_client() as c:335 rv = c.get('/?tequila=42')336 assert request.args['tequila'] == '42'337338If you were to use just the :meth:`~flask.Flask.test_client` without339the ``with`` block, the ``assert`` would fail with an error because `request`340is no longer available (because you are trying to use it341outside of the actual request).342343344Accessing and Modifying Sessions345--------------------------------346347.. versionadded:: 0.8348349Sometimes it can be very helpful to access or modify the sessions from the350test client. Generally there are two ways for this. If you just want to351ensure that a session has certain keys set to certain values you can just352keep the context around and access :data:`flask.session`::353354 with app.test_client() as c:355 rv = c.get('/')356 assert flask.session['foo'] == 42357358This however does not make it possible to also modify the session or to359access the session before a request was fired. Starting with Flask 0.8 we360provide a so called “session transaction” which simulates the appropriate361calls to open a session in the context of the test client and to modify362it. At the end of the transaction the session is stored and ready to be363used by the test client. This works independently of the session backend used::364365 with app.test_client() as c:366 with c.session_transaction() as sess:367 sess['a_key'] = 'a value'368369 # once this is reached the session was stored and ready to be used by the client370 c.get(...)371372Note that in this case you have to use the ``sess`` object instead of the373:data:`flask.session` proxy. The object however itself will provide the374same interface.375376377Testing JSON APIs378-----------------379380.. versionadded:: 1.0381382Flask has great support for JSON, and is a popular choice for building JSON383APIs. Making requests with JSON data and examining JSON data in responses is384very convenient::385386 from flask import request, jsonify387388 @app.route('/api/auth')389 def auth():390 json_data = request.get_json()391 email = json_data['email']392 password = json_data['password']393 return jsonify(token=generate_token(email, password))394395 with app.test_client() as c:396 rv = c.post('/api/auth', json={397 'email': 'flask@example.com', 'password': 'secret'398 })399 json_data = rv.get_json()400 assert verify_token(email, json_data['token'])401402Passing the ``json`` argument in the test client methods sets the request data403to the JSON-serialized object and sets the content type to404``application/json``. You can get the JSON data from the request or response405with ``get_json``.406407408.. _testing-cli:409410Testing CLI Commands411--------------------412413Click comes with `utilities for testing`_ your CLI commands. A414:class:`~click.testing.CliRunner` runs commands in isolation and415captures the output in a :class:`~click.testing.Result` object.416417Flask provides :meth:`~flask.Flask.test_cli_runner` to create a418:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the419CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`420method to call commands in the same way they would be called from the421command line. ::422423 import click424425 @app.cli.command('hello')426 @click.option('--name', default='World')427 def hello_command(name):428 click.echo(f'Hello, {name}!')429430 def test_hello():431 runner = app.test_cli_runner()432433 # invoke the command directly434 result = runner.invoke(hello_command, ['--name', 'Flask'])435 assert 'Hello, Flask' in result.output436437 # or by name438 result = runner.invoke(args=['hello'])439 assert 'World' in result.output440441In the example above, invoking the command by name is useful because it442verifies that the command was correctly registered with the app.443444If you want to test how your command parses parameters, without running445the command, use its :meth:`~click.BaseCommand.make_context` method.446This is useful for testing complex validation rules and custom types. ::447448 def upper(ctx, param, value):449 if value is not None:450 return value.upper()451452 @app.cli.command('hello')453 @click.option('--name', default='World', callback=upper)454 def hello_command(name):455 click.echo(f'Hello, {name}!')456457 def test_hello_params():458 context = hello_command.make_context('hello', ['--name', 'flask'])459 assert context.params['name'] == 'FLASK'460461.. _click: https://click.palletsprojects.com/462.. _utilities for testing: https://click.palletsprojects.com/testing/