testing.rst
This file
Path
docs/testing.rst
455 lines · 15.2 KiB
Last changed by
document testing cli commandsDavid Lordbefore adoptionae30fe7
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:24 https://pytest.org2526The 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 the31source code from `the examples`_.3233.. _the examples:34 https://github.com/pallets/flask/tree/master/examples/flaskr/3536The Testing Skeleton37--------------------3839We begin by adding a tests directory under the application root. Then40create a Python file to store our tests (:file:`test_flaskr.py`). When we41format the filename like ``test_*.py``, it will be auto-discoverable by42pytest.4344Next, we create a `pytest fixture`_ called45:func:`client` that configures46the application for testing and initializes a new database.::4748 import os49 import tempfile5051 import pytest5253 from flaskr import flaskr545556 @pytest.fixture57 def client():58 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()59 flaskr.app.config['TESTING'] = True60 client = flaskr.app.test_client()6162 with flaskr.app.app_context():63 flaskr.init_db()6465 yield client6667 os.close(db_fd)68 os.unlink(flaskr.app.config['DATABASE'])6970This client fixture will be called by each individual test. It gives us a71simple interface to the application, where we can trigger test requests to the72application. The client will also keep track of cookies for us.7374During setup, the ``TESTING`` config flag is activated. What75this does is disable error catching during request handling, so that76you get better error reports when performing test requests against the77application.7879Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module80to create a temporary database and initialize it. The81:func:`~tempfile.mkstemp` function does two things for us: it returns a82low-level file handle and a random file name, the latter we use as83database name. We just have to keep the `db_fd` around so that we can use84the :func:`os.close` function to close the file.8586To delete the database after the test, the fixture closes the file and removes87it from the filesystem.8889If we now run the test suite, we should see the following output::9091 $ pytest9293 ================ test session starts ================94 rootdir: ./flask/examples/flaskr, inifile: setup.cfg95 collected 0 items9697 =========== no tests ran in 0.07 seconds ============9899Even though it did not run any actual tests, we already know that our ``flaskr``100application is syntactically valid, otherwise the import would have died101with an exception.102103.. _pytest fixture:104 https://docs.pytest.org/en/latest/fixture.html105106The First Test107--------------108109Now it's time to start testing the functionality of the application.110Let's check that the application shows "No entries here so far" if we111access the root of the application (``/``). To do this, we add a new112test function to :file:`test_flaskr.py`, like this::113114 def test_empty_db(client):115 """Start with a blank database."""116117 rv = client.get('/')118 assert b'No entries here so far' in rv.data119120Notice that our test functions begin with the word `test`; this allows121`pytest`_ to automatically identify the function as a test to run.122123By using ``client.get`` we can send an HTTP ``GET`` request to the application with124the given path. The return value will be a :class:`~flask.Flask.response_class` object.125We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect126the return value (as string) from the application. In this case, we ensure that127``'No entries here so far'`` is 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 ==============214215For more complex tests with headers and status codes, check out the216`MiniTwit Example`_ from the sources which contains a larger test217suite.218219.. _MiniTwit Example:220 https://github.com/pallets/flask/tree/master/examples/minitwit/221222Other Testing Tricks223--------------------224225Besides using the test client as shown above, there is also the226:meth:`~flask.Flask.test_request_context` method that can be used227in combination with the ``with`` statement to activate a request context228temporarily. With this you can access the :class:`~flask.request`,229:class:`~flask.g` and :class:`~flask.session` objects like in view230functions. Here is a full example that demonstrates this approach::231232 import flask233234 app = flask.Flask(__name__)235236 with app.test_request_context('/?name=Peter'):237 assert flask.request.path == '/'238 assert flask.request.args['name'] == 'Peter'239240All the other objects that are context bound can be used in the same241way.242243If you want to test your application with different configurations and244there does not seem to be a good way to do that, consider switching to245application factories (see :ref:`app-factories`).246247Note however that if you are using a test request context, the248:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`249functions are not called automatically. However250:meth:`~flask.Flask.teardown_request` functions are indeed executed when251the test request context leaves the ``with`` block. If you do want the252:meth:`~flask.Flask.before_request` functions to be called as well, you253need to call :meth:`~flask.Flask.preprocess_request` yourself::254255 app = flask.Flask(__name__)256257 with app.test_request_context('/?name=Peter'):258 app.preprocess_request()259 ...260261This can be necessary to open database connections or something similar262depending on how your application was designed.263264If you want to call the :meth:`~flask.Flask.after_request` functions you265need to call into :meth:`~flask.Flask.process_response` which however266requires that you pass it a response object::267268 app = flask.Flask(__name__)269270 with app.test_request_context('/?name=Peter'):271 resp = Response('...')272 resp = app.process_response(resp)273 ...274275This in general is less useful because at that point you can directly276start using the test client.277278.. _faking-resources:279280Faking Resources and Context281----------------------------282283.. versionadded:: 0.10284285A very common pattern is to store user authorization information and286database connections on the application context or the :attr:`flask.g`287object. The general pattern for this is to put the object on there on288first usage and then to remove it on a teardown. Imagine for instance289this code to get the current user::290291 def get_user():292 user = getattr(g, 'user', None)293 if user is None:294 user = fetch_current_user_from_database()295 g.user = user296 return user297298For a test it would be nice to override this user from the outside without299having to change some code. This can be accomplished with300hooking the :data:`flask.appcontext_pushed` signal::301302 from contextlib import contextmanager303 from flask import appcontext_pushed, g304305 @contextmanager306 def user_set(app, user):307 def handler(sender, **kwargs):308 g.user = user309 with appcontext_pushed.connected_to(handler, app):310 yield311312And then to use it::313314 from flask import json, jsonify315316 @app.route('/users/me')317 def users_me():318 return jsonify(username=g.user.username)319320 with user_set(app, my_user):321 with app.test_client() as c:322 resp = c.get('/users/me')323 data = json.loads(resp.data)324 self.assert_equal(data['username'], my_user.username)325326327Keeping the Context Around328--------------------------329330.. versionadded:: 0.4331332Sometimes it is helpful to trigger a regular request but still keep the333context around for a little longer so that additional introspection can334happen. With Flask 0.4 this is possible by using the335:meth:`~flask.Flask.test_client` with a ``with`` block::336337 app = flask.Flask(__name__)338339 with app.test_client() as c:340 rv = c.get('/?tequila=42')341 assert request.args['tequila'] == '42'342343If you were to use just the :meth:`~flask.Flask.test_client` without344the ``with`` block, the ``assert`` would fail with an error because `request`345is no longer available (because you are trying to use it outside of the actual request).346347348Accessing and Modifying Sessions349--------------------------------350351.. versionadded:: 0.8352353Sometimes it can be very helpful to access or modify the sessions from the354test client. Generally there are two ways for this. If you just want to355ensure that a session has certain keys set to certain values you can just356keep the context around and access :data:`flask.session`::357358 with app.test_client() as c:359 rv = c.get('/')360 assert flask.session['foo'] == 42361362This however does not make it possible to also modify the session or to363access the session before a request was fired. Starting with Flask 0.8 we364provide a so called “session transaction” which simulates the appropriate365calls to open a session in the context of the test client and to modify366it. At the end of the transaction the session is stored. This works367independently of the session backend used::368369 with app.test_client() as c:370 with c.session_transaction() as sess:371 sess['a_key'] = 'a value'372373 # once this is reached the session was stored374375Note that in this case you have to use the ``sess`` object instead of the376:data:`flask.session` proxy. The object however itself will provide the377same interface.378379380Testing JSON APIs381-----------------382383.. versionadded:: 1.0384385Flask has great support for JSON, and is a popular choice for building JSON386APIs. Making requests with JSON data and examining JSON data in responses is387very convenient::388389 from flask import request, jsonify390391 @app.route('/api/auth')392 def auth():393 json_data = request.get_json()394 email = json_data['email']395 password = json_data['password']396 return jsonify(token=generate_token(email, password))397398 with app.test_client() as c:399 rv = c.post('/api/auth', json={400 'username': 'flask', 'password': 'secret'401 })402 json_data = rv.get_json()403 assert verify_token(email, json_data['token'])404405Passing the ``json`` argument in the test client methods sets the request data406to the JSON-serialized object and sets the content type to407``application/json``. You can get the JSON data from the request or response408with ``get_json``.409410411.. _testing-cli:412413Testing CLI Commands414--------------------415416Click comes with `utilities for testing`_ your CLI commands.417418Use :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` to call419commands in the same way they would be called from the command line. The420:class:`~click.testing.CliRunner` runs the command in isolation and421captures the output in a :class:`~click.testing.Result` object. ::422423 import click424 from click.testing import CliRunner425426 @app.cli.command('hello')427 @click.option('--name', default='World')428 def hello_command(name)429 click.echo(f'Hello, {name}!')430431 def test_hello():432 runner = CliRunner()433 result = runner.invoke(hello_command, ['--name', 'Flask'])434 assert 'Hello, Flask' in result.output435436If you want to test how your command parses parameters, without running437the command, use the command's :meth:`~click.BaseCommand.make_context`438method. This is useful for testing complex validation rules and custom439types. ::440441 def upper(ctx, param, value):442 if value is not None:443 return value.upper()444445 @app.cli.command('hello')446 @click.option('--name', default='World', callback=upper)447 def hello_command(name)448 click.echo(f'Hello, {name}!')449450 def test_hello_params():451 context = hello_command.make_context('hello', ['--name', 'flask'])452 assert context.params['name'] == 'FLASK'453454.. _click: http://click.pocoo.org/455.. _utilities for testing: http://click.pocoo.org/testing