testing.rst
This file
Path
docs/testing.rst
456 lines · 15.4 KiB
Last changed by
fix docks linkcheckDavid Lordbefore adoptioncb6272c
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>`.3132The 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 configures42the application for testing and initializes a new database.::4344 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'] = True56 client = flaskr.app.test_client()5758 with flaskr.app.app_context():59 flaskr.init_db()6061 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 the :mod:`tempfile` module76to create a temporary database and initialize it. The77: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 our ``flaskr``96application is syntactically valid, otherwise the import would have died97with 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 the application with120the given path. The return value will be a :class:`~flask.Flask.response_class` object.121We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect122the return value (as string) from the application. In this case, we ensure that123``'No entries here so far'`` is part of the output.124125Run it again and you should see one passing test::126127 $ pytest -v128129 ================ test session starts ================130 rootdir: ./flask/examples/flaskr, inifile: setup.cfg131 collected 1 items132133 tests/test_flaskr.py::test_empty_db PASSED134135 ============= 1 passed in 0.10 seconds ==============136137Logging In and Out138------------------139140The majority of the functionality of our application is only available for141the administrative user, so we need a way to log our test client in and out142of the application. To do this, we fire some requests to the login and logout143pages with the required form data (username and password). And because the144login and logout pages redirect, we tell the client to `follow_redirects`.145146Add the following two functions to your :file:`test_flaskr.py` file::147148 def login(client, username, password):149 return client.post('/login', data=dict(150 username=username,151 password=password152 ), follow_redirects=True)153154155 def logout(client):156 return client.get('/logout', follow_redirects=True)157158Now we can easily test that logging in and out works and that it fails with159invalid credentials. Add this new test function::160161 def test_login_logout(client):162 """Make sure login and logout works."""163164 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])165 assert b'You were logged in' in rv.data166167 rv = logout(client)168 assert b'You were logged out' in rv.data169170 rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])171 assert b'Invalid username' in rv.data172173 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')174 assert b'Invalid password' in rv.data175176Test Adding Messages177--------------------178179We should also test that adding messages works. Add a new test function180like this::181182 def test_messages(client):183 """Test that messages work."""184185 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])186 rv = client.post('/add', data=dict(187 title='<Hello>',188 text='<strong>HTML</strong> allowed here'189 ), follow_redirects=True)190 assert b'No entries here so far' not in rv.data191 assert b'<Hello>' in rv.data192 assert b'<strong>HTML</strong> allowed here' in rv.data193194Here we check that HTML is allowed in the text but not in the title,195which is the intended behavior.196197Running that should now give us three passing tests::198199 $ pytest -v200201 ================ test session starts ================202 rootdir: ./flask/examples/flaskr, inifile: setup.cfg203 collected 3 items204205 tests/test_flaskr.py::test_empty_db PASSED206 tests/test_flaskr.py::test_login_logout PASSED207 tests/test_flaskr.py::test_messages PASSED208209 ============= 3 passed in 0.23 seconds ==============210211212Other Testing Tricks213--------------------214215Besides using the test client as shown above, there is also the216:meth:`~flask.Flask.test_request_context` method that can be used217in combination with the ``with`` statement to activate a request context218temporarily. With this you can access the :class:`~flask.request`,219:class:`~flask.g` and :class:`~flask.session` objects like in view220functions. Here is a full example that demonstrates this approach::221222 import flask223224 app = flask.Flask(__name__)225226 with app.test_request_context('/?name=Peter'):227 assert flask.request.path == '/'228 assert flask.request.args['name'] == 'Peter'229230All the other objects that are context bound can be used in the same231way.232233If you want to test your application with different configurations and234there does not seem to be a good way to do that, consider switching to235application factories (see :ref:`app-factories`).236237Note however that if you are using a test request context, the238:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`239functions are not called automatically. However240:meth:`~flask.Flask.teardown_request` functions are indeed executed when241the test request context leaves the ``with`` block. If you do want the242:meth:`~flask.Flask.before_request` functions to be called as well, you243need to call :meth:`~flask.Flask.preprocess_request` yourself::244245 app = flask.Flask(__name__)246247 with app.test_request_context('/?name=Peter'):248 app.preprocess_request()249 ...250251This can be necessary to open database connections or something similar252depending on how your application was designed.253254If you want to call the :meth:`~flask.Flask.after_request` functions you255need to call into :meth:`~flask.Flask.process_response` which however256requires that you pass it a response object::257258 app = flask.Flask(__name__)259260 with app.test_request_context('/?name=Peter'):261 resp = Response('...')262 resp = app.process_response(resp)263 ...264265This in general is less useful because at that point you can directly266start using the test client.267268.. _faking-resources:269270Faking Resources and Context271----------------------------272273.. versionadded:: 0.10274275A very common pattern is to store user authorization information and276database connections on the application context or the :attr:`flask.g`277object. The general pattern for this is to put the object on there on278first usage and then to remove it on a teardown. Imagine for instance279this code to get the current user::280281 def get_user():282 user = getattr(g, 'user', None)283 if user is None:284 user = fetch_current_user_from_database()285 g.user = user286 return user287288For a test it would be nice to override this user from the outside without289having to change some code. This can be accomplished with290hooking the :data:`flask.appcontext_pushed` signal::291292 from contextlib import contextmanager293 from flask import appcontext_pushed, g294295 @contextmanager296 def user_set(app, user):297 def handler(sender, **kwargs):298 g.user = user299 with appcontext_pushed.connected_to(handler, app):300 yield301302And then to use it::303304 from flask import json, jsonify305306 @app.route('/users/me')307 def users_me():308 return jsonify(username=g.user.username)309310 with user_set(app, my_user):311 with app.test_client() as c:312 resp = c.get('/users/me')313 data = json.loads(resp.data)314 self.assert_equal(data['username'], my_user.username)315316317Keeping the Context Around318--------------------------319320.. versionadded:: 0.4321322Sometimes it is helpful to trigger a regular request but still keep the323context around for a little longer so that additional introspection can324happen. With Flask 0.4 this is possible by using the325:meth:`~flask.Flask.test_client` with a ``with`` block::326327 app = flask.Flask(__name__)328329 with app.test_client() as c:330 rv = c.get('/?tequila=42')331 assert request.args['tequila'] == '42'332333If you were to use just the :meth:`~flask.Flask.test_client` without334the ``with`` block, the ``assert`` would fail with an error because `request`335is no longer available (because you are trying to use it outside of the actual request).336337338Accessing and Modifying Sessions339--------------------------------340341.. versionadded:: 0.8342343Sometimes it can be very helpful to access or modify the sessions from the344test client. Generally there are two ways for this. If you just want to345ensure that a session has certain keys set to certain values you can just346keep the context around and access :data:`flask.session`::347348 with app.test_client() as c:349 rv = c.get('/')350 assert flask.session['foo'] == 42351352This however does not make it possible to also modify the session or to353access the session before a request was fired. Starting with Flask 0.8 we354provide a so called “session transaction” which simulates the appropriate355calls to open a session in the context of the test client and to modify356it. At the end of the transaction the session is stored and ready to be357used by the test client. This works independently of the session backend used::358359 with app.test_client() as c:360 with c.session_transaction() as sess:361 sess['a_key'] = 'a value'362363 # once this is reached the session was stored and ready to be used by the client364 c.get(...)365366Note 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.369370371Testing 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``.400401402.. _testing-cli:403404Testing CLI Commands405--------------------406407Click 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.410411Flask 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. ::416417 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():425 runner = app.test_cli_runner()426427 # invoke the command directly428 result = runner.invoke(hello_command, ['--name', 'Flask'])429 assert 'Hello, Flask' in result.output430431 # 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.437438If you want to test how your command parses parameters, without running439the command, use its :meth:`~click.BaseCommand.make_context` method.440This is useful for testing complex validation rules and custom types. ::441442 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: https://click.palletsprojects.com/456.. _utilities for testing: https://click.palletsprojects.com/testing/