Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

463 lines · 15.5 KiB

Last changed by

Merge pull request #4165 from yuxiaoy1/patch-1David Lordbefore adoption49cbb77

History of this file

Take 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_app51    from flaskr.db import init_db525354    @pytest.fixture55    def client():56        db_fd, db_path = tempfile.mkstemp()57        app = create_app({'TESTING': True, 'DATABASE': db_path})5859        with app.test_client() as client:60            with app.app_context():61                init_db()62            yield client6364        os.close(db_fd)65        os.unlink(db_path)6667This client fixture will be called by each individual test.  It gives us a68simple interface to the application, where we can trigger test requests to the69application.  The client will also keep track of cookies for us.7071During setup, the ``TESTING`` config flag is activated.  What72this does is disable error catching during request handling, so that73you get better error reports when performing test requests against the74application.7576Because SQLite3 is filesystem-based, we can easily use the77:mod:`tempfile` module to create a temporary database and initialize it.78The :func:`~tempfile.mkstemp` function does two things for us: it returns a79low-level file handle and a random file name, the latter we use as80database name.  We just have to keep the `db_fd` around so that we can use81the :func:`os.close` function to close the file.8283To delete the database after the test, the fixture closes the file and removes84it from the filesystem.8586If we now run the test suite, we should see the following output::8788    $ pytest8990    ================ test session starts ================91    rootdir: ./flask/examples/flaskr, inifile: setup.cfg92    collected 0 items9394    =========== no tests ran in 0.07 seconds ============9596Even though it did not run any actual tests, we already know that our97``flaskr`` application is syntactically valid, otherwise the import98would have died with an exception.99100.. _pytest fixture:101   https://docs.pytest.org/en/latest/fixture.html102103The First Test104--------------105106Now it's time to start testing the functionality of the application.107Let's check that the application shows "No entries here so far" if we108access the root of the application (``/``).  To do this, we add a new109test function to :file:`test_flaskr.py`, like this::110111    def test_empty_db(client):112        """Start with a blank database."""113114        rv = client.get('/')115        assert b'No entries here so far' in rv.data116117Notice that our test functions begin with the word `test`; this allows118`pytest`_ to automatically identify the function as a test to run.119120By using ``client.get`` we can send an HTTP ``GET`` request to the121application with the given path.  The return value will be a122:class:`~flask.Flask.response_class` object. We can now use the123:attr:`~werkzeug.wrappers.Response.data` attribute to inspect124the return value (as string) from the application.125In this case, we ensure that ``'No entries here so far'``126is part of the output.127128Run it again and you should see one passing test::129130    $ pytest -v131132    ================ test session starts ================133    rootdir: ./flask/examples/flaskr, inifile: setup.cfg134    collected 1 items135136    tests/test_flaskr.py::test_empty_db PASSED137138    ============= 1 passed in 0.10 seconds ==============139140Logging In and Out141------------------142143The majority of the functionality of our application is only available for144the administrative user, so we need a way to log our test client in and out145of the application.  To do this, we fire some requests to the login and logout146pages with the required form data (username and password).  And because the147login and logout pages redirect, we tell the client to `follow_redirects`.148149Add the following two functions to your :file:`test_flaskr.py` file::150151    def login(client, username, password):152        return client.post('/login', data=dict(153            username=username,154            password=password155        ), follow_redirects=True)156157158    def logout(client):159        return client.get('/logout', follow_redirects=True)160161Now we can easily test that logging in and out works and that it fails with162invalid credentials.  Add this new test function::163164    def test_login_logout(client):165        """Make sure login and logout works."""166167        username = flaskr.app.config["USERNAME"]168        password = flaskr.app.config["PASSWORD"]169170        rv = login(client, username, password)171        assert b'You were logged in' in rv.data172173        rv = logout(client)174        assert b'You were logged out' in rv.data175176        rv = login(client, f"{username}x", password)177        assert b'Invalid username' in rv.data178179        rv = login(client, username, f'{password}x')180        assert b'Invalid password' in rv.data181182Test Adding Messages183--------------------184185We should also test that adding messages works.  Add a new test function186like this::187188    def test_messages(client):189        """Test that messages work."""190191        login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])192        rv = client.post('/add', data=dict(193            title='<Hello>',194            text='<strong>HTML</strong> allowed here'195        ), follow_redirects=True)196        assert b'No entries here so far' not in rv.data197        assert b'&lt;Hello&gt;' in rv.data198        assert b'<strong>HTML</strong> allowed here' in rv.data199200Here we check that HTML is allowed in the text but not in the title,201which is the intended behavior.202203Running that should now give us three passing tests::204205    $ pytest -v206207    ================ test session starts ================208    rootdir: ./flask/examples/flaskr, inifile: setup.cfg209    collected 3 items210211    tests/test_flaskr.py::test_empty_db PASSED212    tests/test_flaskr.py::test_login_logout PASSED213    tests/test_flaskr.py::test_messages PASSED214215    ============= 3 passed in 0.23 seconds ==============216217218Other Testing Tricks219--------------------220221Besides using the test client as shown above, there is also the222:meth:`~flask.Flask.test_request_context` method that can be used223in combination with the ``with`` statement to activate a request context224temporarily.  With this you can access the :class:`~flask.request`,225:class:`~flask.g` and :class:`~flask.session` objects like in view226functions.  Here is a full example that demonstrates this approach::227228    from flask import Flask, request229230    app = Flask(__name__)231232    with app.test_request_context('/?name=Peter'):233        assert request.path == '/'234        assert request.args['name'] == 'Peter'235236All the other objects that are context bound can be used in the same237way.238239If you want to test your application with different configurations and240there does not seem to be a good way to do that, consider switching to241application factories (see :doc:`patterns/appfactories`).242243Note however that if you are using a test request context, the244:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`245functions are not called automatically.  However246:meth:`~flask.Flask.teardown_request` functions are indeed executed when247the test request context leaves the ``with`` block.  If you do want the248:meth:`~flask.Flask.before_request` functions to be called as well, you249need to call :meth:`~flask.Flask.preprocess_request` yourself::250251    app = Flask(__name__)252253    with app.test_request_context('/?name=Peter'):254        app.preprocess_request()255        ...256257This can be necessary to open database connections or something similar258depending on how your application was designed.259260If you want to call the :meth:`~flask.Flask.after_request` functions you261need to call into :meth:`~flask.Flask.process_response` which however262requires that you pass it a response object::263264    app = Flask(__name__)265266    with app.test_request_context('/?name=Peter'):267        resp = Response('...')268        resp = app.process_response(resp)269        ...270271This in general is less useful because at that point you can directly272start using the test client.273274.. _faking-resources:275276Faking Resources and Context277----------------------------278279.. versionadded:: 0.10280281A very common pattern is to store user authorization information and282database connections on the application context or the :attr:`flask.g`283object.  The general pattern for this is to put the object on there on284first usage and then to remove it on a teardown.  Imagine for instance285this code to get the current user::286287    def get_user():288        user = getattr(g, 'user', None)289        if user is None:290            user = fetch_current_user_from_database()291            g.user = user292        return user293294For a test it would be nice to override this user from the outside without295having to change some code.  This can be accomplished with296hooking the :data:`flask.appcontext_pushed` signal::297298    from contextlib import contextmanager299    from flask import appcontext_pushed, g300301    @contextmanager302    def user_set(app, user):303        def handler(sender, **kwargs):304            g.user = user305        with appcontext_pushed.connected_to(handler, app):306            yield307308And then to use it::309310    from flask import json, jsonify311312    @app.route('/users/me')313    def users_me():314        return jsonify(username=g.user.username)315316    with user_set(app, my_user):317        with app.test_client() as c:318            resp = c.get('/users/me')319            data = json.loads(resp.data)320            assert data['username'] == my_user.username321322323Keeping the Context Around324--------------------------325326.. versionadded:: 0.4327328Sometimes it is helpful to trigger a regular request but still keep the329context around for a little longer so that additional introspection can330happen.  With Flask 0.4 this is possible by using the331:meth:`~flask.Flask.test_client` with a ``with`` block::332333    app = Flask(__name__)334335    with app.test_client() as c:336        rv = c.get('/?tequila=42')337        assert request.args['tequila'] == '42'338339If you were to use just the :meth:`~flask.Flask.test_client` without340the ``with`` block, the ``assert`` would fail with an error because `request`341is no longer available (because you are trying to use it342outside of the actual request).343344345Accessing and Modifying Sessions346--------------------------------347348.. versionadded:: 0.8349350Sometimes it can be very helpful to access or modify the sessions from the351test client.  Generally there are two ways for this.  If you just want to352ensure that a session has certain keys set to certain values you can just353keep the context around and access :data:`flask.session`::354355    with app.test_client() as c:356        rv = c.get('/')357        assert session['foo'] == 42358359This however does not make it possible to also modify the session or to360access the session before a request was fired.  Starting with Flask 0.8 we361provide a so called “session transaction” which simulates the appropriate362calls to open a session in the context of the test client and to modify363it. At the end of the transaction the session is stored and ready to be364used by the test client. This works independently of the session backend used::365366    with app.test_client() as c:367        with c.session_transaction() as sess:368            sess['a_key'] = 'a value'369370        # once this is reached the session was stored and ready to be used by the client371        c.get(...)372373Note that in this case you have to use the ``sess`` object instead of the374:data:`flask.session` proxy.  The object however itself will provide the375same interface.376377378Testing JSON APIs379-----------------380381.. versionadded:: 1.0382383Flask has great support for JSON, and is a popular choice for building JSON384APIs. Making requests with JSON data and examining JSON data in responses is385very convenient::386387    from flask import request, jsonify388389    @app.route('/api/auth')390    def auth():391        json_data = request.get_json()392        email = json_data['email']393        password = json_data['password']394        return jsonify(token=generate_token(email, password))395396    with app.test_client() as c:397        rv = c.post('/api/auth', json={398            'email': 'flask@example.com', 'password': 'secret'399        })400        json_data = rv.get_json()401        assert verify_token(email, json_data['token'])402403Passing the ``json`` argument in the test client methods sets the request data404to the JSON-serialized object and sets the content type to405``application/json``. You can get the JSON data from the request or response406with ``get_json``.407408409.. _testing-cli:410411Testing CLI Commands412--------------------413414Click comes with `utilities for testing`_ your CLI commands. A415:class:`~click.testing.CliRunner` runs commands in isolation and416captures the output in a :class:`~click.testing.Result` object.417418Flask provides :meth:`~flask.Flask.test_cli_runner` to create a419:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the420CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`421method to call commands in the same way they would be called from the422command line. ::423424    import click425426    @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 = app.test_cli_runner()433434        # invoke the command directly435        result = runner.invoke(hello_command, ['--name', 'Flask'])436        assert 'Hello, Flask' in result.output437438        # or by name439        result = runner.invoke(args=['hello'])440        assert 'World' in result.output441442In the example above, invoking the command by name is useful because it443verifies that the command was correctly registered with the app.444445If you want to test how your command parses parameters, without running446the command, use its :meth:`~click.BaseCommand.make_context` method.447This is useful for testing complex validation rules and custom types. ::448449    def upper(ctx, param, value):450        if value is not None:451            return value.upper()452453    @app.cli.command('hello')454    @click.option('--name', default='World', callback=upper)455    def hello_command(name):456        click.echo(f'Hello, {name}!')457458    def test_hello_params():459        context = hello_command.make_context('hello', ['--name', 'flask'])460        assert context.params['name'] == 'FLASK'461462.. _click: https://click.palletsprojects.com/463.. _utilities for testing: https://click.palletsprojects.com/testing/