testing.rst
This file
Path
docs/testing.rst
319 lines · 10.2 KiB
Last changed by
docs/testing.rst: fix follow_redirects sample code (#5303)David Lordbefore adoptionbeedaa4
History of this fileTake it
The walk stopped after 200 commits: lines older than 979e0ad point at it.
fix pr linkDavid Lordbefore adoption979e0ad
lines 1–194why, one step back1Testing Flask Applications2==========================34Flask provides utilities for testing an application. This documentation5goes over techniques for working with different parts of the application6in tests.78We will use the `pytest`_ framework to set up and run our tests.910.. code-block:: text1112 $ pip install pytest1314.. _pytest: https://docs.pytest.org/1516The :doc:`tutorial </tutorial/index>` goes over how to write tests for17100% coverage of the sample Flaskr blog application. See18:doc:`the tutorial on tests </tutorial/tests>` for a detailed19explanation of specific tests for an application.202122Identifying Tests23-----------------2425Tests are typically located in the ``tests`` folder. Tests are functions26that start with ``test_``, in Python modules that start with ``test_``.27Tests can also be further grouped in classes that start with ``Test``.2829It can be difficult to know what to test. Generally, try to test the30code that you write, not the code of libraries that you use, since they31are already tested. Try to extract complex behaviors as separate32functions to test individually.333435Fixtures36--------3738Pytest *fixtures* allow writing pieces of code that are reusable across39tests. A simple fixture returns a value, but a fixture can also do40setup, yield a value, then do teardown. Fixtures for the application,41test client, and CLI runner are shown below, they can be placed in42``tests/conftest.py``.4344If you're using an45:doc:`application factory </patterns/appfactories>`, define an ``app``46fixture to create and configure an app instance. You can add code before47and after the ``yield`` to set up and tear down other resources, such as48creating and clearing a database.4950If you're not using a factory, you already have an app object you can51import and configure directly. You can still use an ``app`` fixture to52set up and tear down resources.5354.. code-block:: python5556 import pytest57 from my_project import create_app5859 @pytest.fixture()60 def app():61 app = create_app()62 app.config.update({63 "TESTING": True,64 })6566 # other setup can go here6768 yield app6970 # clean up / reset resources here717273 @pytest.fixture()74 def client(app):75 return app.test_client()767778 @pytest.fixture()79 def runner(app):80 return app.test_cli_runner()818283Sending Requests with the Test Client84-------------------------------------8586The test client makes requests to the application without running a live87server. Flask's client extends88:doc:`Werkzeug's client <werkzeug:test>`, see those docs for additional89information.9091The ``client`` has methods that match the common HTTP request methods,92such as ``client.get()`` and ``client.post()``. They take many arguments93for building the request; you can find the full documentation in94:class:`~werkzeug.test.EnvironBuilder`. Typically you'll use ``path``,95``query_string``, ``headers``, and ``data`` or ``json``.9697To make a request, call the method the request should use with the path98to the route to test. A :class:`~werkzeug.test.TestResponse` is returned99to examine the response data. It has all the usual properties of a100response object. You'll usually look at ``response.data``, which is the101bytes returned by the view. If you want to use text, Werkzeug 2.1102provides ``response.text``, or use ``response.get_data(as_text=True)``.103104.. code-block:: python105106 def test_request_example(client):107 response = client.get("/posts")108 assert b"<h2>Hello, World!</h2>" in response.data109110111Pass a dict ``query_string={"key": "value", ...}`` to set arguments in112the query string (after the ``?`` in the URL). Pass a dict113``headers={}`` to set request headers.114115To 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,117you'll pass a dict to set form data.118119120Form Data121~~~~~~~~~122123To send form data, pass a dict to ``data``. The ``Content-Type`` header124will be set to ``multipart/form-data`` or125``application/x-www-form-urlencoded`` automatically.126127If a value is a file object opened for reading bytes (``"rb"`` mode), it128will be treated as an uploaded file. To change the detected filename and129content type, pass a ``(file, filename, content_type)`` tuple. File130objects will be closed after making the request, so they do not need to131use the usual ``with open() as f:`` pattern.132133It can be useful to store files in a ``tests/resources`` folder, then134use ``pathlib.Path`` to get files relative to the current test file.135136.. code-block:: python137138 from pathlib import Path139140 # get the resources folder in the tests folder141 resources = Path(__file__).parent / "resources"142143 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 == 200150151152JSON Data153~~~~~~~~~154155To send JSON data, pass an object to ``json``. The ``Content-Type``156header will be set to ``application/json`` automatically.157158Similarly, if the response contains JSON data, the ``response.json``159attribute will contain the deserialized object.160161.. code-block:: python162163 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"177178179Following Redirects180-------------------181182By default, the client does not make additional requests if the response183is a redirect. By passing ``follow_redirects=True`` to a request method,184the client will continue to make requests until a non-redirect response185is returned.186187:attr:`TestResponse.history <werkzeug.test.TestResponse.history>` is188a tuple of the responses that led up to the final response. Each189response has a :attr:`~werkzeug.test.TestResponse.request` attribute190which records the request that produced that response.191192.. code-block:: python193194 def test_logout_redirect(client):docs/testing.rst: fix follow_redirects sample code (#5303)David Lordbefore adoptionbeedaa4
line 195why, one step back195 response = client.get("/logout", follow_redirects=True)fix pr linkDavid Lordbefore adoption979e0ad
lines 196–319why, one step back196 # 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"200201202Accessing and Modifying the Session203-----------------------------------204205To access Flask's context variables, mainly206:data:`~flask.session`, use the client in a ``with`` statement.207The app and request context will remain active *after* making a request,208until the ``with`` block ends.209210.. code-block:: python211212 from flask import session213214 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"] == 1219220 # session is no longer accessible221222If you want to access or set a value in the session *before* making a223request, use the client's224:meth:`~flask.testing.FlaskClient.session_transaction` method in a225``with`` statement. It returns a session object, and will save the226session once the block ends.227228.. code-block:: python229230 from flask import session231232 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"] = 1236237 # session is saved now238239 response = client.get("/users/me")240 assert response.json["username"] == "flask"241242243.. _testing-cli:244245Running Commands with the CLI Runner246------------------------------------247248Flask provides :meth:`~flask.Flask.test_cli_runner` to create a249:class:`~flask.testing.FlaskCliRunner`, which runs CLI commands in250isolation and captures the output in a :class:`~click.testing.Result`251object. Flask's runner extends :doc:`Click's runner <click:testing>`,252see those docs for additional information.253254Use the runner's :meth:`~flask.testing.FlaskCliRunner.invoke` method to255call commands in the same way they would be called with the ``flask``256command from the command line.257258.. code-block:: python259260 import click261262 @app.cli.command("hello")263 @click.option("--name", default="World")264 def hello_command(name):265 click.echo(f"Hello, {name}!")266267 def test_hello_command(runner):268 result = runner.invoke(args="hello")269 assert "World" in result.output270271 result = runner.invoke(args=["hello", "--name", "Flask"])272 assert "Flask" in result.output273274275Tests that depend on an Active Context276--------------------------------------277278You may have functions that are called from views or commands, that279expect 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 a282request or invoking the command, you can create and activate a context283directly.284285Use ``with app.app_context()`` to push an application context. For286example, database extensions usually require an active app context to287make queries.288289.. code-block:: python290291 def test_db_post_model(app):292 with app.app_context():293 post = db.session.query(Post).get(1)294295Use ``with app.test_request_context()`` to push a request context. It296takes the same arguments as the test client's request methods.297298.. code-block:: python299300 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()306307 assert messages["name"][0] == "Name cannot be empty."308309Creating a test request context doesn't run any of the Flask dispatching310code, so ``before_request`` functions are not called. If you need to311call these, usually it's better to make a full request instead. However,312it's possible to call them manually.313314.. code-block:: python315316 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"