Skip to content
Myr

Merge branch '2.0.x'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parents 48ee204, ef557b3 · Browse files · 3 files+227 added−371 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+227 added−371 removed

  • other:+227 added−371 removed

3 files+227 added−371 removed

modified:docs/api.rst+3 added-3 removed
166 unmodified lines
167 :doc:`application context </appcontext>`. This is an instance of168 :attr:`Flask.app_ctx_globals_class`, which defaults to169 :class:`ctx._AppCtxGlobals`.170171 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.174175 This is a proxy. See :ref:`notes-on-proxies` for more information.176177 .. versionchanged:: 0.10
596 unmodified lines
modified:docs/testing.rst+223 added-367 removed
1Testing Flask Applications2==========================34 **Something that is untested is broken.**4Flask provides utilities for testing an application. This documentation5goes over techniques for working with different parts of the application6in tests.76The 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.8We will use the `pytest`_ framework to set up and run our tests.912Flask 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.10.. code-block:: text1116In this documentation we will use the `pytest`_ package as the base17framework for our tests. You can install it with ``pip``, like so::1812 $ pip install pytest1314.. _pytest: https://docs.pytest.org/1523The Application24---------------16The :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.2026First, 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>`.2130So that we can import the module ``flaskr`` correctly, we need to run31``pip install -e .`` in the folder ``tutorial``.22Identifying Tests23-----------------2433The Testing Skeleton34--------------------25Tests 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``.2836We 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.29It 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.3341Next, we create a `pytest fixture`_ called42:func:`client` that configures43the application for testing and initializes a new database::3445 import os46 import tempfile35Fixtures36--------3748 import pytest38Pytest *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``.4350 from flaskr import create_app51 from flaskr.db import init_db44If 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 @pytest.fixture55 def client():56 db_fd, db_path = tempfile.mkstemp()57 app = create_app({'TESTING': True, 'DATABASE': db_path})54.. code-block:: python5559 with app.test_client() as client:60 with app.app_context():61 init_db()62 yield client56 import pytest57 from my_project import create_app5864 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 })6567This 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.66 # other setup can go here6771During 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.68 yield app6976Because 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.70 # clean up / reset resources here7183To delete the database after the test, the fixture closes the file and removes84it from the filesystem.7286If we now run the test suite, we should see the following output::73 @pytest.fixture()74 def client(app):75 return app.test_client()7688 $ pytest7790 ================ 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()8194 =========== no tests ran in 0.07 seconds ============8296Even 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.83Sending Requests with the Test Client84-------------------------------------85100.. _pytest fixture:101 https://docs.pytest.org/en/latest/fixture.html86The 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.90103The First Test104--------------91The ``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``, ``headers``, and ``data`` or ``json``.96106Now 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::97To 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)``.103111 def test_empty_db(client):112 """Start with a blank database."""104.. code-block:: python105114 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.data109117Notice that our test functions begin with the word `test`; this allows118`pytest`_ to automatically identify the function as a test to run.110120By 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.111Pass a dict ``query={"key": "value", ...}`` to set arguments in the112query string (after the ``?`` in the URL). Pass a dict ``headers={}``113to set request headers.114128Run it again and you should see one passing test::115To 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.118130 $ pytest -v119132 ================ test session starts ================133 rootdir: ./flask/examples/flaskr, inifile: setup.cfg134 collected 1 items120Form Data121~~~~~~~~~122136 tests/test_flaskr.py::test_empty_db PASSED123To 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.126138 ============= 1 passed in 0.10 seconds ==============127If 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.132140Logging In and Out141------------------133It can be useful to store files in a ``tests/resources`` folder, then134use ``pathlib.Path`` to get files relative to the current test file.135143The 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`.136.. code-block:: python137149Add the following two functions to your :file:`test_flaskr.py` file::138 from pathlib import Path139151 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"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 == 200150158 def logout(client):159 return client.get('/logout', follow_redirects=True)151161Now we can easily test that logging in and out works and that it fails with162invalid credentials. Add this new test function::152JSON Data153~~~~~~~~~154164 def test_login_logout(client):165 """Make sure login and logout works."""155To send JSON data, pass an object to ``json``. The ``Content-Type``156header will be set to ``application/json`` automatically.157167 username = flaskr.app.config["USERNAME"]168 password = flaskr.app.config["PASSWORD"]158Similarly, if the response contains JSON data, the ``response.json``159attribute will contain the deserialized object.160170 rv = login(client, username, password)171 assert b'You were logged in' in rv.data161.. code-block:: python162173 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"177176 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.data179Following Redirects180-------------------181182Test Adding Messages183--------------------182By 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.186185We should also test that adding messages works. Add a new test function186like this::187: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.191188 def test_messages(client):189 """Test that messages work."""192.. code-block:: python193191 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.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"200200Here we check that HTML is allowed in the text but not in the title,201which is the intended behavior.201203Running that should now give us three passing tests::202Accessing and Modifying the Session203-----------------------------------204205 $ pytest -v205To 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.209207 ================ test session starts ================208 rootdir: ./flask/examples/flaskr, inifile: setup.cfg209 collected 3 items210.. code-block:: python211211 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 session213215 ============= 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"] == 1219220 # session is no longer accessible221218Other Testing Tricks219--------------------222If 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.227221Besides 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::228.. code-block:: python229228 from flask import Flask, request230 from flask import session231230 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"] = 1236232 with app.test_request_context('/?name=Peter'):233 assert request.path == '/'234 assert request.args['name'] == 'Peter'237 # session is saved now238236All the other objects that are context bound can be used in the same237way.239 response = client.get("/users/me")240 assert response.json["username"] == "flask"241239If 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::243.. _testing-cli:244251 app = Flask(__name__)245Running Commands with the CLI Runner246------------------------------------247253 with app.test_request_context('/?name=Peter'):254 app.preprocess_request()255 ...248Flask 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.253257This can be necessary to open database connections or something similar258depending on how your application was designed.254Use 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.257260If 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::258.. code-block:: python259264 app = Flask(__name__)260 import click261266 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}!")266271This in general is less useful because at that point you can directly272start using the test client.267 def test_hello_command(runner):268 result = runner.invoke(["hello"])269 assert "World" in result.output270274.. _faking-resources:271 result = runner.invoke(["hello", "--name", "Flask"])272 assert "Flask" in result.output273276Faking Resources and Context277----------------------------274279.. versionadded:: 0.10275Tests that depend on an Active Context276--------------------------------------277281A 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::278You 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.284287 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 user285Use ``with app.app_context()`` to push an application context. For286example, database extensions usually require an active app context to287make queries.288294For 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::289.. code-block:: python290298 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)294301 @contextmanager302 def user_set(app, user):303 def handler(sender, **kwargs):304 g.user = user305 with appcontext_pushed.connected_to(handler, app):306 yield295Use ``with app.test_request_context()`` to push a request context. It296takes the same arguments as the test client's request methods.297308And then to use it::298.. code-block:: python299310 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()306312 @app.route('/users/me')313 def users_me():314 return jsonify(username=g.user.username)307 assert messages["name"][0] == "Name cannot be empty."308316 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.username309Creating 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:: python315323Keeping 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/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"
modified:CHANGES.rst+1 added-1 removed
45 unmodified lines
4647Version 2.0.348-------------4950Unreleased50Released 2022-02-145152- The test client's ``as_tuple`` parameter is deprecated and will be53 removed in Werkzeug 2.1. It is now also deprecated in Flask, to be54 removed in Flask 2.1, while remaining compatible with both in
1193 unmodified lines