testing.rst
This file
Path
docs/testing.rst
461 lines · 15.5 KiB
Last changed by
Merge pull request #3349 from nathanmp/masterDavid Lordbefore adoption12666af
History of this fileTake it
1.. _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::2021 $ pip install pytest2223.. _pytest: https://docs.pytest.org/2425The 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 the30source code from :gh:`the examples <examples/tutorial>`.3132So that we can import the module ``flaskr`` correctly, we need to run33``pip install -e .`` in the folder ``tutorial``.3435The Testing Skeleton36--------------------3738We begin by adding a tests directory under the application root. Then39create a Python file to store our tests (:file:`test_flaskr.py`). When we40format the filename like ``test_*.py``, it will be auto-discoverable by41pytest.4243Next, we create a `pytest fixture`_ called44:func:`client` that configures45the application for testing and initializes a new database::4647 import os48 import tempfile4950 import pytest5152 from flaskr import create_app535455 @pytest.fixture56 def client():57 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()58 flaskr.app.config['TESTING'] = True5960 with flaskr.app.test_client() as client:61 with flaskr.app.app_context():62 flaskr.init_db()63 yield client6465 os.close(db_fd)66 os.unlink(flaskr.app.config['DATABASE'])6768This client fixture will be called by each individual test. It gives us a69simple interface to the application, where we can trigger test requests to the70application. The client will also keep track of cookies for us.7172During setup, the ``TESTING`` config flag is activated. What73this does is disable error catching during request handling, so that74you get better error reports when performing test requests against the75application.7677Because SQLite3 is filesystem-based, we can easily use the78:mod:`tempfile` module to create a temporary database and initialize it.79The :func:`~tempfile.mkstemp` function does two things for us: it returns a80low-level file handle and a random file name, the latter we use as81database name. We just have to keep the `db_fd` around so that we can use82the :func:`os.close` function to close the file.8384To delete the database after the test, the fixture closes the file and removes85it from the filesystem.8687If we now run the test suite, we should see the following output::8889 $ pytest9091 ================ test session starts ================92 rootdir: ./flask/examples/flaskr, inifile: setup.cfg93 collected 0 items9495 =========== no tests ran in 0.07 seconds ============9697Even though it did not run any actual tests, we already know that our98``flaskr`` application is syntactically valid, otherwise the import99would have died with an exception.100101.. _pytest fixture:102 https://docs.pytest.org/en/latest/fixture.html103104The First Test105--------------106107Now it's time to start testing the functionality of the application.108Let's check that the application shows "No entries here so far" if we109access the root of the application (``/``). To do this, we add a new110test function to :file:`test_flaskr.py`, like this::111112 def test_empty_db(client):113 """Start with a blank database."""114115 rv = client.get('/')116 assert b'No entries here so far' in rv.data117118Notice that our test functions begin with the word `test`; this allows119`pytest`_ to automatically identify the function as a test to run.120121By using ``client.get`` we can send an HTTP ``GET`` request to the122application with the given path. The return value will be a123:class:`~flask.Flask.response_class` object. We can now use the124:attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect125the return value (as string) from the application.126In this case, we ensure that ``'No entries here so far'``127is part of the output.128129Run it again and you should see one passing test::130131 $ pytest -v132133 ================ test session starts ================134 rootdir: ./flask/examples/flaskr, inifile: setup.cfg135 collected 1 items136137 tests/test_flaskr.py::test_empty_db PASSED138139 ============= 1 passed in 0.10 seconds ==============140141Logging 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`.149150Add the following two functions to your :file:`test_flaskr.py` file::151152 def login(client, username, password):153 return client.post('/login', data=dict(154 username=username,155 password=password156 ), follow_redirects=True)157158159 def logout(client):160 return client.get('/logout', follow_redirects=True)161162Now we can easily test that logging in and out works and that it fails with163invalid credentials. Add this new test function::164165 def test_login_logout(client):166 """Make sure login and logout works."""167168 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.data179180Test Adding Messages181--------------------182183We should also test that adding messages works. Add a new test function184like this::185186 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(191 title='<Hello>',192 text='<strong>HTML</strong> allowed here'193 ), follow_redirects=True)194 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.data197198Here 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::202203 $ pytest -v204205 ================ test session starts ================206 rootdir: ./flask/examples/flaskr, inifile: setup.cfg207 collected 3 items208209 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 ==============214215216Other Testing Tricks217--------------------218219Besides using the test client as shown above, there is also the220:meth:`~flask.Flask.test_request_context` method that can be used221in combination with the ``with`` statement to activate a request context222temporarily. With this you can access the :class:`~flask.request`,223:class:`~flask.g` and :class:`~flask.session` objects like in view224functions. Here is a full example that demonstrates this approach::225226 import flask227228 app = flask.Flask(__name__)229230 with app.test_request_context('/?name=Peter'):231 assert flask.request.path == '/'232 assert flask.request.args['name'] == 'Peter'233234All the other objects that are context bound can be used in the same235way.236237If you want to test your application with different configurations and238there does not seem to be a good way to do that, consider switching to239application factories (see :ref:`app-factories`).240241Note however that if you are using a test request context, the242:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`243functions are not called automatically. However244:meth:`~flask.Flask.teardown_request` functions are indeed executed when245the test request context leaves the ``with`` block. If you do want the246:meth:`~flask.Flask.before_request` functions to be called as well, you247need to call :meth:`~flask.Flask.preprocess_request` yourself::248249 app = flask.Flask(__name__)250251 with app.test_request_context('/?name=Peter'):252 app.preprocess_request()253 ...254255This can be necessary to open database connections or something similar256depending on how your application was designed.257258If you want to call the :meth:`~flask.Flask.after_request` functions you259need to call into :meth:`~flask.Flask.process_response` which however260requires that you pass it a response object::261262 app = flask.Flask(__name__)263264 with app.test_request_context('/?name=Peter'):265 resp = Response('...')266 resp = app.process_response(resp)267 ...268269This in general is less useful because at that point you can directly270start using the test client.271272.. _faking-resources:273274Faking Resources and Context275----------------------------276277.. versionadded:: 0.10278279A very common pattern is to store user authorization information and280database connections on the application context or the :attr:`flask.g`281object. The general pattern for this is to put the object on there on282first usage and then to remove it on a teardown. Imagine for instance283this code to get the current user::284285 def get_user():286 user = getattr(g, 'user', None)287 if user is None:288 user = fetch_current_user_from_database()289 g.user = user290 return user291292For a test it would be nice to override this user from the outside without293having to change some code. This can be accomplished with294hooking the :data:`flask.appcontext_pushed` signal::295296 from contextlib import contextmanager297 from flask import appcontext_pushed, g298299 @contextmanager300 def user_set(app, user):301 def handler(sender, **kwargs):302 g.user = user303 with appcontext_pushed.connected_to(handler, app):304 yield305306And then to use it::307308 from flask import json, jsonify309310 @app.route('/users/me')311 def users_me():312 return jsonify(username=g.user.username)313314 with user_set(app, my_user):315 with app.test_client() as c:316 resp = c.get('/users/me')317 data = json.loads(resp.data)318 self.assert_equal(data['username'], my_user.username)319320321Keeping the Context Around322--------------------------323324.. versionadded:: 0.4325326Sometimes it is helpful to trigger a regular request but still keep the327context around for a little longer so that additional introspection can328happen. With Flask 0.4 this is possible by using the329:meth:`~flask.Flask.test_client` with a ``with`` block::330331 app = flask.Flask(__name__)332333 with app.test_client() as c:334 rv = c.get('/?tequila=42')335 assert request.args['tequila'] == '42'336337If you were to use just the :meth:`~flask.Flask.test_client` without338the ``with`` block, the ``assert`` would fail with an error because `request`339is no longer available (because you are trying to use it340outside of the actual request).341342343Accessing and Modifying Sessions344--------------------------------345346.. versionadded:: 0.8347348Sometimes it can be very helpful to access or modify the sessions from the349test client. Generally there are two ways for this. If you just want to350ensure that a session has certain keys set to certain values you can just351keep the context around and access :data:`flask.session`::352353 with app.test_client() as c:354 rv = c.get('/')355 assert flask.session['foo'] == 42356357This however does not make it possible to also modify the session or to358access the session before a request was fired. Starting with Flask 0.8 we359provide a so called “session transaction” which simulates the appropriate360calls to open a session in the context of the test client and to modify361it. At the end of the transaction the session is stored and ready to be362used by the test client. This works independently of the session backend used::363364 with app.test_client() as c:365 with c.session_transaction() as sess:366 sess['a_key'] = 'a value'367368 # once this is reached the session was stored and ready to be used by the client369 c.get(...)370371Note that in this case you have to use the ``sess`` object instead of the372:data:`flask.session` proxy. The object however itself will provide the373same interface.374375376Testing JSON APIs377-----------------378379.. versionadded:: 1.0380381Flask has great support for JSON, and is a popular choice for building JSON382APIs. Making requests with JSON data and examining JSON data in responses is383very convenient::384385 from flask import request, jsonify386387 @app.route('/api/auth')388 def auth():389 json_data = request.get_json()390 email = json_data['email']391 password = json_data['password']392 return jsonify(token=generate_token(email, password))393394 with app.test_client() as c:395 rv = c.post('/api/auth', json={396 'email': 'flask@example.com', 'password': 'secret'397 })398 json_data = rv.get_json()399 assert verify_token(email, json_data['token'])400401Passing the ``json`` argument in the test client methods sets the request data402to the JSON-serialized object and sets the content type to403``application/json``. You can get the JSON data from the request or response404with ``get_json``.405406407.. _testing-cli:408409Testing CLI Commands410--------------------411412Click comes with `utilities for testing`_ your CLI commands. A413:class:`~click.testing.CliRunner` runs commands in isolation and414captures the output in a :class:`~click.testing.Result` object.415416Flask provides :meth:`~flask.Flask.test_cli_runner` to create a417:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the418CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`419method to call commands in the same way they would be called from the420command line. ::421422 import click423424 @app.cli.command('hello')425 @click.option('--name', default='World')426 def hello_command(name)427 click.echo(f'Hello, {name}!')428429 def test_hello():430 runner = app.test_cli_runner()431432 # invoke the command directly433 result = runner.invoke(hello_command, ['--name', 'Flask'])434 assert 'Hello, Flask' in result.output435436 # or by name437 result = runner.invoke(args=['hello'])438 assert 'World' in result.output439440In the example above, invoking the command by name is useful because it441verifies that the command was correctly registered with the app.442443If you want to test how your command parses parameters, without running444the command, use its :meth:`~click.BaseCommand.make_context` method.445This is useful for testing complex validation rules and custom types. ::446447 def upper(ctx, param, value):448 if value is not None:449 return value.upper()450451 @app.cli.command('hello')452 @click.option('--name', default='World', callback=upper)453 def hello_command(name)454 click.echo(f'Hello, {name}!')455456 def test_hello_params():457 context = hello_command.make_context('hello', ['--name', 'flask'])458 assert context.params['name'] == 'FLASK'459460.. _click: https://click.palletsprojects.com/461.. _utilities for testing: https://click.palletsprojects.com/testing/