Merge pull request #4448 from pallets/testing-docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
rewrite testing docs
authored by David Lord · committed by GitHub · parents d6496c8, 761d7e1 · Browse files · 2 files·+226 added−370 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+226 added−370 removed
- other:+226 added−370 removed
Provenance
- Commit
c15f74c- Tree
c35ba7c- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d6496c8- Parent 2
761d7e1
2 files changed+226 added−370 removed
modified:docs/api.rst+3 added-3 removed
166 unmodified lines167 :doc:`application context </appcontext>`. This is an instance of168 :attr:`Flask.app_ctx_globals_class`, which defaults to169 :class:`ctx._AppCtxGlobals`.170 171- This is a good place to store resources during a request. During172- testing, you can use the :ref:`faking-resources` pattern to173- pre-configure such resources.171+ This is a good place to store resources during a request. For172+ example, a ``before_request`` function could load a user object from173+ a session id, then set ``g.user`` to be used in the view function.174 175 This is a proxy. See :ref:`notes-on-proxies` for more information.176 177 .. versionchanged:: 0.10598 unmodified linesmodified:docs/testing.rst+223 added-367 removed
1 Testing Flask Applications2 ==========================3 4- **Something that is untested is broken.**4+Flask provides utilities for testing an application. This documentation5+goes over techniques for working with different parts of the application6+in tests.7 6-The origin of this quote is unknown and while it is not entirely correct, it7-is also not far from the truth. Untested applications make it hard to8-improve existing code and developers of untested applications tend to9-become pretty paranoid. If an application has automated tests, you can10-safely make changes and instantly know if anything breaks.8+We will use the `pytest`_ framework to set up and run our tests.9 12-Flask provides a way to test your application by exposing the Werkzeug13-test :class:`~werkzeug.test.Client` and handling the context locals for you.14-You can then use that with your favourite testing solution.10+.. code-block:: text11 16-In this documentation we will use the `pytest`_ package as the base17-framework for our tests. You can install it with ``pip``, like so::18-12 $ pip install pytest13 14 .. _pytest: https://docs.pytest.org/15 23-The Application24----------------16+The :doc:`tutorial </tutorial/index>` goes over how to write tests for17+100% coverage of the sample Flaskr blog application. See18+:doc:`the tutorial on tests </tutorial/tests>` for a detailed19+explanation of specific tests for an application.20 26-First, we need an application to test; we will use the application from27-the :doc:`tutorial/index`. If you don't have that application yet, get28-the source code from :gh:`the examples <examples/tutorial>`.21 30-So that we can import the module ``flaskr`` correctly, we need to run31-``pip install -e .`` in the folder ``tutorial``.22+Identifying Tests23+-----------------24 33-The Testing Skeleton34---------------------25+Tests are typically located in the ``tests`` folder. Tests are functions26+that start with ``test_``, in Python modules that start with ``test_``.27+Tests can also be further grouped in classes that start with ``Test``.28 36-We begin by adding a tests directory under the application root. Then37-create a Python file to store our tests (:file:`test_flaskr.py`). When we38-format the filename like ``test_*.py``, it will be auto-discoverable by39-pytest.29+It can be difficult to know what to test. Generally, try to test the30+code that you write, not the code of libraries that you use, since they31+are already tested. Try to extract complex behaviors as separate32+functions to test individually.33 41-Next, we create a `pytest fixture`_ called42-:func:`client` that configures43-the application for testing and initializes a new database::34 45- import os46- import tempfile35+Fixtures36+--------37 48- import pytest38+Pytest *fixtures* allow writing pieces of code that are reusable across39+tests. A simple fixture returns a value, but a fixture can also do40+setup, yield a value, then do teardown. Fixtures for the application,41+test client, and CLI runner are shown below, they can be placed in42+``tests/conftest.py``.43 50- from flaskr import create_app51- from flaskr.db import init_db44+If you're using an45+:doc:`application factory </patterns/appfactories>`, define an ``app``46+fixture to create and configure an app instance. You can add code before47+and after the ``yield`` to set up and tear down other resources, such as48+creating and clearing a database.49 50+If you're not using a factory, you already have an app object you can51+import and configure directly. You can still use an ``app`` fixture to52+set up and tear down resources.53 54- @pytest.fixture55- def client():56- db_fd, db_path = tempfile.mkstemp()57- app = create_app({'TESTING': True, 'DATABASE': db_path})54+.. code-block:: python55 59- with app.test_client() as client:60- with app.app_context():61- init_db()62- yield client56+ import pytest57+ from my_project import create_app58 64- os.close(db_fd)65- os.unlink(db_path)59+ @pytest.fixture()60+ def app():61+ app = create_app()62+ app.config.update({63+ "TESTING": True,64+ })65 67-This client fixture will be called by each individual test. It gives us a68-simple interface to the application, where we can trigger test requests to the69-application. The client will also keep track of cookies for us.66+ # other setup can go here67 71-During setup, the ``TESTING`` config flag is activated. What72-this does is disable error catching during request handling, so that73-you get better error reports when performing test requests against the74-application.68+ yield app69 76-Because SQLite3 is filesystem-based, we can easily use the77-:mod:`tempfile` module to create a temporary database and initialize it.78-The :func:`~tempfile.mkstemp` function does two things for us: it returns a79-low-level file handle and a random file name, the latter we use as80-database name. We just have to keep the `db_fd` around so that we can use81-the :func:`os.close` function to close the file.70+ # clean up / reset resources here71 83-To delete the database after the test, the fixture closes the file and removes84-it from the filesystem.72 86-If we now run the test suite, we should see the following output::73+ @pytest.fixture()74+ def client(app):75+ return app.test_client()76 88- $ pytest77 90- ================ test session starts ================91- rootdir: ./flask/examples/flaskr, inifile: setup.cfg92- collected 0 items78+ @pytest.fixture()79+ def runner(app):80+ return app.test_cli_runner()81 94- =========== no tests ran in 0.07 seconds ============82 96-Even though it did not run any actual tests, we already know that our97-``flaskr`` application is syntactically valid, otherwise the import98-would have died with an exception.83+Sending Requests with the Test Client84+-------------------------------------85 100-.. _pytest fixture:101- https://docs.pytest.org/en/latest/fixture.html86+The test client makes requests to the application without running a live87+server. Flask's client extends88+:doc:`Werkzeug's client <werkzeug:test>`, see those docs for additional89+information.90 103-The First Test104---------------91+The ``client`` has methods that match the common HTTP request methods,92+such as ``client.get()`` and ``client.post()``. They take many arguments93+for building the request; you can find the full documentation in94+:class:`~werkzeug.test.EnvironBuilder`. Typically you'll use ``path``,95+``query``, ``headers``, and ``data`` or ``json``.96 106-Now it's time to start testing the functionality of the application.107-Let's check that the application shows "No entries here so far" if we108-access the root of the application (``/``). To do this, we add a new109-test function to :file:`test_flaskr.py`, like this::97+To make a request, call the method the request should use with the path98+to the route to test. A :class:`~werkzeug.test.TestResponse` is returned99+to examine the response data. It has all the usual properties of a100+response object. You'll usually look at ``response.data``, which is the101+bytes returned by the view. If you want to use text, Werkzeug 2.1102+provides ``response.text``, or use ``response.get_data(as_text=True)``.103 111- def test_empty_db(client):112- """Start with a blank database."""104+.. code-block:: python105 114- rv = client.get('/')115- assert b'No entries here so far' in rv.data106+ def test_request_example(client):107+ response = client.get("/posts")108+ assert b"<h2>Hello, World!</h2>" in response.data109 117-Notice that our test functions begin with the word `test`; this allows118-`pytest`_ to automatically identify the function as a test to run.110 120-By using ``client.get`` we can send an HTTP ``GET`` request to the121-application 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 inspect124-the return value (as string) from the application.125-In this case, we ensure that ``'No entries here so far'``126-is part of the output.111+Pass a dict ``query={"key": "value", ...}`` to set arguments in the112+query string (after the ``?`` in the URL). Pass a dict ``headers={}``113+to set request headers.114 128-Run it again and you should see one passing test::115+To send a request body in a POST or PUT request, pass a value to116+``data``. If raw bytes are passed, that exact body is used. Usually,117+you'll pass a dict to set form data.118 130- $ pytest -v119 132- ================ test session starts ================133- rootdir: ./flask/examples/flaskr, inifile: setup.cfg134- collected 1 items120+Form Data121+~~~~~~~~~122 136- tests/test_flaskr.py::test_empty_db PASSED123+To send form data, pass a dict to ``data``. The ``Content-Type`` header124+will be set to ``multipart/form-data`` or125+``application/x-www-form-urlencoded`` automatically.126 138- ============= 1 passed in 0.10 seconds ==============127+If a value is a file object opened for reading bytes (``"rb"`` mode), it128+will be treated as an uploaded file. To change the detected filename and129+content type, pass a ``(file, filename, content_type)`` tuple. File130+objects will be closed after making the request, so they do not need to131+use the usual ``with open() as f:`` pattern.132 140-Logging In and Out141-------------------133+It can be useful to store files in a ``tests/resources`` folder, then134+use ``pathlib.Path`` to get files relative to the current test file.135 143-The majority of the functionality of our application is only available for144-the administrative user, so we need a way to log our test client in and out145-of the application. To do this, we fire some requests to the login and logout146-pages with the required form data (username and password). And because the147-login and logout pages redirect, we tell the client to `follow_redirects`.136+.. code-block:: python137 149-Add the following two functions to your :file:`test_flaskr.py` file::138+ from pathlib import Path139 151- def login(client, username, password):152- return client.post('/login', data=dict(153- username=username,154- password=password155- ), follow_redirects=True)140+ # get the resources folder in the tests folder141+ resources = Path(__file__).parent / "resources"142 143+ def test_edit_user(client):144+ response = client.post("/user/2/edit", data={145+ name="Flask",146+ theme="dark",147+ picture=(resources / "picture.png").open("rb"),148+ })149+ assert response.status_code == 200150 158- def logout(client):159- return client.get('/logout', follow_redirects=True)151 161-Now we can easily test that logging in and out works and that it fails with162-invalid credentials. Add this new test function::152+JSON Data153+~~~~~~~~~154 164- def test_login_logout(client):165- """Make sure login and logout works."""155+To send JSON data, pass an object to ``json``. The ``Content-Type``156+header will be set to ``application/json`` automatically.157 167- username = flaskr.app.config["USERNAME"]168- password = flaskr.app.config["PASSWORD"]158+Similarly, if the response contains JSON data, the ``response.json``159+attribute will contain the deserialized object.160 170- rv = login(client, username, password)171- assert b'You were logged in' in rv.data161+.. code-block:: python162 173- rv = logout(client)174- assert b'You were logged out' in rv.data163+ def test_json_data(client):164+ response = client.post("/graphql", json={165+ "query": """166+ query User($id: String!) {167+ user(id: $id) {168+ name169+ theme170+ picture_url171+ }172+ }173+ """,174+ variables={"id": 2},175+ })176+ assert response.json["data"]["user"]["name"] == "Flask"177 176- rv = login(client, f"{username}x", password)177- assert b'Invalid username' in rv.data178 179- rv = login(client, username, f'{password}x')180- assert b'Invalid password' in rv.data179+Following Redirects180+-------------------181 182-Test Adding Messages183---------------------182+By default, the client does not make additional requests if the response183+is a redirect. By passing ``follow_redirects=True`` to a request method,184+the client will continue to make requests until a non-redirect response185+is returned.186 185-We should also test that adding messages works. Add a new test function186-like this::187+:attr:`TestResponse.history <werkzeug.test.TestResponse.history>` is188+a tuple of the responses that led up to the final response. Each189+response has a :attr:`~werkzeug.test.TestResponse.request` attribute190+which records the request that produced that response.191 188- def test_messages(client):189- """Test that messages work."""192+.. code-block:: python193 191- 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'<Hello>' in rv.data198- assert b'<strong>HTML</strong> allowed here' in rv.data194+ def test_logout_redirect(client):195+ response = client.get("/logout")196+ # Check that there was one redirect response.197+ assert len(response.history) == 1198+ # Check that the second request was to the index page.199+ assert response.request.path == "/index"200 200-Here we check that HTML is allowed in the text but not in the title,201-which is the intended behavior.201 203-Running that should now give us three passing tests::202+Accessing and Modifying the Session203+-----------------------------------204 205- $ pytest -v205+To access Flask's context variables, mainly206+:data:`~flask.session`, use the client in a ``with`` statement.207+The app and request context will remain active *after* making a request,208+until the ``with`` block ends.209 207- ================ test session starts ================208- rootdir: ./flask/examples/flaskr, inifile: setup.cfg209- collected 3 items210+.. code-block:: python211 211- tests/test_flaskr.py::test_empty_db PASSED212- tests/test_flaskr.py::test_login_logout PASSED213- tests/test_flaskr.py::test_messages PASSED212+ from flask import session213 215- ============= 3 passed in 0.23 seconds ==============214+ def test_access_session(client):215+ with client:216+ client.post("/auth/login", data={"username": "flask"})217+ # session is still accessible218+ assert session["user_id"] == 1219 220+ # session is no longer accessible221 218-Other Testing Tricks219---------------------222+If you want to access or set a value in the session *before* making a223+request, use the client's224+:meth:`~flask.testing.FlaskClient.session_transaction` method in a225+``with`` statement. It returns a session object, and will save the226+session once the block ends.227 221-Besides using the test client as shown above, there is also the222-:meth:`~flask.Flask.test_request_context` method that can be used223-in combination with the ``with`` statement to activate a request context224-temporarily. With this you can access the :class:`~flask.request`,225-:class:`~flask.g` and :class:`~flask.session` objects like in view226-functions. Here is a full example that demonstrates this approach::228+.. code-block:: python229 228- from flask import Flask, request230+ from flask import session231 230- app = Flask(__name__)232+ def test_modify_session(client):233+ with client.session_transaction() as session:234+ # set a user id without going through the login route235+ session["user_id"] = 1236 232- with app.test_request_context('/?name=Peter'):233- assert request.path == '/'234- assert request.args['name'] == 'Peter'237+ # session is saved now238 236-All the other objects that are context bound can be used in the same237-way.239+ response = client.get("/users/me")240+ assert response.json["username"] == "flask"241 239-If you want to test your application with different configurations and240-there does not seem to be a good way to do that, consider switching to241-application factories (see :doc:`patterns/appfactories`).242 243-Note however that if you are using a test request context, the244-:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`245-functions are not called automatically. However246-:meth:`~flask.Flask.teardown_request` functions are indeed executed when247-the test request context leaves the ``with`` block. If you do want the248-:meth:`~flask.Flask.before_request` functions to be called as well, you249-need to call :meth:`~flask.Flask.preprocess_request` yourself::243+.. _testing-cli:244 251- app = Flask(__name__)245+Running Commands with the CLI Runner246+------------------------------------247 253- with app.test_request_context('/?name=Peter'):254- app.preprocess_request()255- ...248+Flask provides :meth:`~flask.Flask.test_cli_runner` to create a249+:class:`~flask.testing.FlaskCliRunner`, which runs CLI commands in250+isolation and captures the output in a :class:`~click.testing.Result`251+object. Flask's runner extends :doc:`Click's runner <click:testing>`,252+see those docs for additional information.253 257-This can be necessary to open database connections or something similar258-depending on how your application was designed.254+Use the runner's :meth:`~flask.testing.FlaskCliRunner.invoke` method to255+call commands in the same way they would be called with the ``flask``256+command from the command line.257 260-If you want to call the :meth:`~flask.Flask.after_request` functions you261-need to call into :meth:`~flask.Flask.process_response` which however262-requires that you pass it a response object::258+.. code-block:: python259 264- app = Flask(__name__)260+ import click261 266- with app.test_request_context('/?name=Peter'):267- resp = Response('...')268- resp = app.process_response(resp)269- ...262+ @app.cli.command("hello")263+ @click.option("--name", default="World")264+ def hello_command(name):265+ click.echo(f"Hello, {name}!")266 271-This in general is less useful because at that point you can directly272-start using the test client.267+ def test_hello_command(runner):268+ result = runner.invoke(["hello"])269+ assert "World" in result.output270 274-.. _faking-resources:271+ result = runner.invoke(["hello", "--name", "Flask"])272+ assert "Flask" in result.output273 276-Faking Resources and Context277-----------------------------274 279-.. versionadded:: 0.10275+Tests that depend on an Active Context276+--------------------------------------277 281-A very common pattern is to store user authorization information and282-database connections on the application context or the :attr:`flask.g`283-object. The general pattern for this is to put the object on there on284-first usage and then to remove it on a teardown. Imagine for instance285-this code to get the current user::278+You may have functions that are called from views or commands, that279+expect an active :doc:`application context </appcontext>` or280+:doc:`request context </reqcontext>` because they access ``request``,281+``session``, or ``current_app``. Rather than testing them by making a282+request or invoking the command, you can create and activate a context283+directly.284 287- 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 user285+Use ``with app.app_context()`` to push an application context. For286+example, database extensions usually require an active app context to287+make queries.288 294-For a test it would be nice to override this user from the outside without295-having to change some code. This can be accomplished with296-hooking the :data:`flask.appcontext_pushed` signal::289+.. code-block:: python290 298- from contextlib import contextmanager299- from flask import appcontext_pushed, g291+ def test_db_post_model(app):292+ with app.app_context():293+ post = db.session.query(Post).get(1)294 301- @contextmanager302- def user_set(app, user):303- def handler(sender, **kwargs):304- g.user = user305- with appcontext_pushed.connected_to(handler, app):306- yield295+Use ``with app.test_request_context()`` to push a request context. It296+takes the same arguments as the test client's request methods.297 308-And then to use it::298+.. code-block:: python299 310- from flask import json, jsonify300+ def test_validate_user_edit(app):301+ with app.test_request_context(302+ "/user/2/edit", method="POST", data={"name": ""}303+ ):304+ # call a function that accesses `request`305+ messages = validate_edit_user()306 312- @app.route('/users/me')313- def users_me():314- return jsonify(username=g.user.username)307+ assert messages["name"][0] == "Name cannot be empty."308 316- 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.username309+Creating a test request context doesn't run any of the Flask dispatching310+code, so ``before_request`` functions are not called. If you need to311+call these, usually it's better to make a full request instead. However,312+it's possible to call them manually.313 314+.. code-block:: python315 323-Keeping the Context Around324---------------------------325-326-.. versionadded:: 0.4327-328-Sometimes it is helpful to trigger a regular request but still keep the329-context around for a little longer so that additional introspection can330-happen. With Flask 0.4 this is possible by using the331-:meth:`~flask.Flask.test_client` with a ``with`` block::332-333- app = Flask(__name__)334-335- with app.test_client() as c:336- rv = c.get('/?tequila=42')337- assert request.args['tequila'] == '42'338-339-If you were to use just the :meth:`~flask.Flask.test_client` without340-the ``with`` block, the ``assert`` would fail with an error because `request`341-is no longer available (because you are trying to use it342-outside of the actual request).343-344-345-Accessing and Modifying Sessions346---------------------------------347-348-.. versionadded:: 0.8349-350-Sometimes it can be very helpful to access or modify the sessions from the351-test client. Generally there are two ways for this. If you just want to352-ensure that a session has certain keys set to certain values you can just353-keep the context around and access :data:`flask.session`::354-355- with app.test_client() as c:356- rv = c.get('/')357- assert session['foo'] == 42358-359-This however does not make it possible to also modify the session or to360-access the session before a request was fired. Starting with Flask 0.8 we361-provide a so called “session transaction” which simulates the appropriate362-calls to open a session in the context of the test client and to modify363-it. At the end of the transaction the session is stored and ready to be364-used by the test client. This works independently of the session backend used::365-366- with app.test_client() as c:367- with c.session_transaction() as sess:368- sess['a_key'] = 'a value'369-370- # once this is reached the session was stored and ready to be used by the client371- c.get(...)372-373-Note that in this case you have to use the ``sess`` object instead of the374-:data:`flask.session` proxy. The object however itself will provide the375-same interface.376-377-378-Testing JSON APIs379------------------380-381-.. versionadded:: 1.0382-383-Flask has great support for JSON, and is a popular choice for building JSON384-APIs. Making requests with JSON data and examining JSON data in responses is385-very convenient::386-387- from flask import request, jsonify388-389- @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))395-396- 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'])402-403-Passing the ``json`` argument in the test client methods sets the request data404-to the JSON-serialized object and sets the content type to405-``application/json``. You can get the JSON data from the request or response406-with ``get_json``.407-408-409-.. _testing-cli:410-411-Testing CLI Commands412---------------------413-414-Click comes with `utilities for testing`_ your CLI commands. A415-:class:`~click.testing.CliRunner` runs commands in isolation and416-captures the output in a :class:`~click.testing.Result` object.417-418-Flask provides :meth:`~flask.Flask.test_cli_runner` to create a419-:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the420-CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`421-method to call commands in the same way they would be called from the422-command line. ::423-424- import click425-426- @app.cli.command('hello')427- @click.option('--name', default='World')428- def hello_command(name):429- click.echo(f'Hello, {name}!')430-431- def test_hello():432- runner = app.test_cli_runner()433-434- # invoke the command directly435- result = runner.invoke(hello_command, ['--name', 'Flask'])436- assert 'Hello, Flask' in result.output437-438- # or by name439- result = runner.invoke(args=['hello'])440- assert 'World' in result.output441-442-In the example above, invoking the command by name is useful because it443-verifies that the command was correctly registered with the app.444-445-If you want to test how your command parses parameters, without running446-the command, use its :meth:`~click.BaseCommand.make_context` method.447-This is useful for testing complex validation rules and custom types. ::448-449- def upper(ctx, param, value):450- if value is not None:451- return value.upper()452-453- @app.cli.command('hello')454- @click.option('--name', default='World', callback=upper)455- def hello_command(name):456- click.echo(f'Hello, {name}!')457-458- def test_hello_params():459- context = hello_command.make_context('hello', ['--name', 'flask'])460- assert context.params['name'] == 'FLASK'461-462-.. _click: https://click.palletsprojects.com/463-.. _utilities for testing: https://click.palletsprojects.com/testing/316+ def test_auth_token(app):317+ with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}):318+ app.preprocess_request()319+ assert g.user.name == "Flask"