Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

460 lines · 15.4 KiB

Last changed by

Merge branch '1.0.x'David Lordbefore adoption05a4e15

History of this file

Take it

The walk stopped after 200 commits: lines older than 4c56477 point at it.

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 1–20why, one step back
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::20

Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6

line 21why, one step back
21 $ pip install pytest

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 22–30why, one step back
22
23.. _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 the

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

line 31why, one step back
31source code from :gh:`the examples <examples/tutorial>`.

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 32–42why, one step back
32
33The 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 configures

Merge pull request #2834 from greyli/remove-unnecessary-periodDavid Lordbefore adoption7627d9c

line 43why, one step back
43the application for testing and initializes a new database::

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 44–75why, one step back
44
45 import os46 import tempfile4748 import pytest4950 from flaskr import flaskr515253 @pytest.fixture54 def client():55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True57 client = flaskr.app.test_client()5859 with flaskr.app.app_context():60 flaskr.init_db()6162 yield client6364 os.close(db_fd)65 os.unlink(flaskr.app.config['DATABASE'])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.75

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

lines 76–78why, one step back
76Because SQLite3 is filesystem-based, we can easily use the
77:mod:`tempfile` module to create a temporary database and initialize it.78The :func:`~tempfile.mkstemp` function does two things for us: it returns a

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 79–95why, one step back
79low-level file handle and a random file name, the latter we use as
80database 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 ============95

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

lines 96–98why, one step back
96Even though it did not run any actual tests, we already know that our
97``flaskr`` application is syntactically valid, otherwise the import98would have died with an exception.

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 99–119why, one step back
99
100.. _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.119

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

lines 120–126why, one step back
120By using ``client.get`` we can send an HTTP ``GET`` request to the
121application with the given path. The return value will be a122:class:`~flask.Flask.response_class` object. We can now use the123:attr:`~werkzeug.wrappers.BaseResponse.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.

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 127–337why, one step back
127
128Run 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 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])168 assert b'You were logged in' in rv.data169170 rv = logout(client)171 assert b'You were logged out' in rv.data172173 rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])174 assert b'Invalid username' in rv.data175176 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')177 assert b'Invalid password' in rv.data178179Test Adding Messages180--------------------181182We should also test that adding messages works. Add a new test function183like this::184185 def test_messages(client):186 """Test that messages work."""187188 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])189 rv = client.post('/add', data=dict(190 title='<Hello>',191 text='<strong>HTML</strong> allowed here'192 ), follow_redirects=True)193 assert b'No entries here so far' not in rv.data194 assert b'&lt;Hello&gt;' in rv.data195 assert b'<strong>HTML</strong> allowed here' in rv.data196197Here we check that HTML is allowed in the text but not in the title,198which is the intended behavior.199200Running that should now give us three passing tests::201202 $ pytest -v203204 ================ test session starts ================205 rootdir: ./flask/examples/flaskr, inifile: setup.cfg206 collected 3 items207208 tests/test_flaskr.py::test_empty_db PASSED209 tests/test_flaskr.py::test_login_logout PASSED210 tests/test_flaskr.py::test_messages PASSED211212 ============= 3 passed in 0.23 seconds ==============213214215Other Testing Tricks216--------------------217218Besides using the test client as shown above, there is also the219:meth:`~flask.Flask.test_request_context` method that can be used220in combination with the ``with`` statement to activate a request context221temporarily. With this you can access the :class:`~flask.request`,222:class:`~flask.g` and :class:`~flask.session` objects like in view223functions. Here is a full example that demonstrates this approach::224225 import flask226227 app = flask.Flask(__name__)228229 with app.test_request_context('/?name=Peter'):230 assert flask.request.path == '/'231 assert flask.request.args['name'] == 'Peter'232233All the other objects that are context bound can be used in the same234way.235236If you want to test your application with different configurations and237there does not seem to be a good way to do that, consider switching to238application factories (see :ref:`app-factories`).239240Note however that if you are using a test request context, the241:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`242functions are not called automatically. However243:meth:`~flask.Flask.teardown_request` functions are indeed executed when244the test request context leaves the ``with`` block. If you do want the245:meth:`~flask.Flask.before_request` functions to be called as well, you246need to call :meth:`~flask.Flask.preprocess_request` yourself::247248 app = flask.Flask(__name__)249250 with app.test_request_context('/?name=Peter'):251 app.preprocess_request()252 ...253254This can be necessary to open database connections or something similar255depending on how your application was designed.256257If you want to call the :meth:`~flask.Flask.after_request` functions you258need to call into :meth:`~flask.Flask.process_response` which however259requires that you pass it a response object::260261 app = flask.Flask(__name__)262263 with app.test_request_context('/?name=Peter'):264 resp = Response('...')265 resp = app.process_response(resp)266 ...267268This in general is less useful because at that point you can directly269start using the test client.270271.. _faking-resources:272273Faking Resources and Context274----------------------------275276.. versionadded:: 0.10277278A very common pattern is to store user authorization information and279database connections on the application context or the :attr:`flask.g`280object. The general pattern for this is to put the object on there on281first usage and then to remove it on a teardown. Imagine for instance282this code to get the current user::283284 def get_user():285 user = getattr(g, 'user', None)286 if user is None:287 user = fetch_current_user_from_database()288 g.user = user289 return user290291For a test it would be nice to override this user from the outside without292having to change some code. This can be accomplished with293hooking the :data:`flask.appcontext_pushed` signal::294295 from contextlib import contextmanager296 from flask import appcontext_pushed, g297298 @contextmanager299 def user_set(app, user):300 def handler(sender, **kwargs):301 g.user = user302 with appcontext_pushed.connected_to(handler, app):303 yield304305And then to use it::306307 from flask import json, jsonify308309 @app.route('/users/me')310 def users_me():311 return jsonify(username=g.user.username)312313 with user_set(app, my_user):314 with app.test_client() as c:315 resp = c.get('/users/me')316 data = json.loads(resp.data)317 self.assert_equal(data['username'], my_user.username)318319320Keeping the Context Around321--------------------------322323.. versionadded:: 0.4324325Sometimes it is helpful to trigger a regular request but still keep the326context around for a little longer so that additional introspection can327happen. With Flask 0.4 this is possible by using the328:meth:`~flask.Flask.test_client` with a ``with`` block::329330 app = flask.Flask(__name__)331332 with app.test_client() as c:333 rv = c.get('/?tequila=42')334 assert request.args['tequila'] == '42'335336If you were to use just the :meth:`~flask.Flask.test_client` without337the ``with`` block, the ``assert`` would fail with an error because `request`

Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a

lines 338–339why, one step back
338is no longer available (because you are trying to use it
339outside of the actual request).

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 340–359why, one step back
340
341342Accessing and Modifying Sessions343--------------------------------344345.. versionadded:: 0.8346347Sometimes it can be very helpful to access or modify the sessions from the348test client. Generally there are two ways for this. If you just want to349ensure that a session has certain keys set to certain values you can just350keep the context around and access :data:`flask.session`::351352 with app.test_client() as c:353 rv = c.get('/')354 assert flask.session['foo'] == 42355356This however does not make it possible to also modify the session or to357access the session before a request was fired. Starting with Flask 0.8 we358provide a so called “session transaction” which simulates the appropriate359calls to open a session in the context of the test client and to modify

Merge branch '1.0.x'David Lordbefore adoption05a4e15

lines 360–361why, one step back
360it. At the end of the transaction the session is stored and ready to be
361used by the test client. This works independently of the session backend used::

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 362–366why, one step back
362
363 with app.test_client() as c:364 with c.session_transaction() as sess:365 sess['a_key'] = 'a value'366

Merge branch '1.0.x'David Lordbefore adoption05a4e15

lines 367–368why, one step back
367 # once this is reached the session was stored and ready to be used by the client
368 c.get(...)

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 369–394why, one step back
369
370Note that in this case you have to use the ``sess`` object instead of the371:data:`flask.session` proxy. The object however itself will provide the372same interface.373374375Testing JSON APIs376-----------------377378.. versionadded:: 1.0379380Flask has great support for JSON, and is a popular choice for building JSON381APIs. Making requests with JSON data and examining JSON data in responses is382very convenient::383384 from flask import request, jsonify385386 @app.route('/api/auth')387 def auth():388 json_data = request.get_json()389 email = json_data['email']390 password = json_data['password']391 return jsonify(token=generate_token(email, password))392393 with app.test_client() as c:394 rv = c.post('/api/auth', json={

Merge pull request #2976 from cykerway/masterDavid Lordbefore adoptiondcc02d6

line 395why, one step back
395 'email': 'flask@example.com', 'password': 'secret'

Merge pull request #2394 from davidism/remove-deprecatedDavid Lordbefore adoption4c56477

lines 396–403why, one step back
396 })
397 json_data = rv.get_json()398 assert verify_token(email, json_data['token'])399400Passing the ``json`` argument in the test client methods sets the request data401to the JSON-serialized object and sets the content type to402``application/json``. You can get the JSON data from the request or response403with ``get_json``.

Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802

lines 404–410why, one step back
404
405406.. _testing-cli:407408Testing CLI Commands409--------------------410

Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66

lines 411–413why, one step back
411Click comes with `utilities for testing`_ your CLI commands. A
412:class:`~click.testing.CliRunner` runs commands in isolation and413captures the output in a :class:`~click.testing.Result` object.

Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802

line 414why, one step back
414

Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66

lines 415–419why, one step back
415Flask provides :meth:`~flask.Flask.test_cli_runner` to create a
416:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the417CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`418method to call commands in the same way they would be called from the419command line. ::

Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802

lines 420–428why, one step back
420
421 import click422423 @app.cli.command('hello')424 @click.option('--name', default='World')425 def hello_command(name)426 click.echo(f'Hello, {name}!')427428 def test_hello():

Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66

lines 429–431why, one step back
429 runner = app.test_cli_runner()
430431 # invoke the command directly

Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802

lines 432–434why, one step back
432 result = runner.invoke(hello_command, ['--name', 'Flask'])
433 assert 'Hello, Flask' in result.output434

Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66

lines 435–441why, one step back
435 # or by name
436 result = runner.invoke(args=['hello'])437 assert 'World' in result.output438439In the example above, invoking the command by name is useful because it440verifies that the command was correctly registered with the app.441

Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802

line 442why, one step back
442If you want to test how your command parses parameters, without running

Merge pull request #2636 from pallets/test-cli-runnerDavid Lordbefore adoption4a7db66

lines 443–444why, one step back
443the command, use its :meth:`~click.BaseCommand.make_context` method.
444This is useful for testing complex validation rules and custom types. ::

Merge pull request #2611 from pallets/cli-test-docsDavid Lordbefore adoption8c2c802

lines 445–460why, one step back
445
446 def upper(ctx, param, value):447 if value is not None:448 return value.upper()449450 @app.cli.command('hello')451 @click.option('--name', default='World', callback=upper)452 def hello_command(name)453 click.echo(f'Hello, {name}!')454455 def test_hello_params():456 context = hello_command.make_context('hello', ['--name', 'flask'])457 assert context.params['name'] == 'FLASK'458459.. _click: http://click.pocoo.org/460.. _utilities for testing: http://click.pocoo.org/testing