Skip to content
Myr

testing.rst

This file

Path

docs/testing.rst

462 lines · 15.5 KiB

Last changed by

Merge pull request #2676 from davidism/tutorialDavid Lordbefore adoptionc3e2ff2

History of this file

Take it

The walk stopped after 200 commits: lines older than 84efebd point at it.

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 1–7why, one step back
1.. _testing:
23Testing Flask Applications4==========================56 **Something that is untested is broken.**7

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 8–9why, one step back
8The origin of this quote is unknown and while it is not entirely correct, it
9is also not far from the truth. Untested applications make it hard to

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 10–15why, one step back
10improve existing code and developers of untested applications tend to
11become 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.

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 16why, one step back
16You can then use that with your favourite testing solution.

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 17why, one step back
17

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 18–25why, one step back
18In this documentation we will use the `pytest`_ package as the base
19framework for our tests. You can install it with ``pip``, like so::2021 pip install pytest2223.. _pytest:24 https://pytest.org25

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 26–30why, one step back
26The Application
27---------------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 #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 32–35why, one step back
32
33The Testing Skeleton34--------------------35

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 36–39why, one step back
36We begin by adding a tests directory under the application root. Then
37create a Python file to store our tests (:file:`test_flaskr.py`). When we38format the filename like ``test_*.py``, it will be auto-discoverable by39pytest.

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 40why, one step back
40

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 41–44why, one step back
41Next, we create a `pytest fixture`_ called
42:func:`client` that configures43the application for testing and initializes a new database.::44

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 45–47why, one step back
45 import os
46 import tempfile47

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 48why, one step back
48 import pytest

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 49why, one step back
49

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 50why, one step back
50 from flaskr import flaskr

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 51–52why, one step back
51
52

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 53–57why, one step back
53 @pytest.fixture
54 def client():55 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 flaskr.app.config['TESTING'] = True57 client = flaskr.app.test_client()

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 58why, one step back
58

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 59–60why, one step back
59 with flaskr.app.app_context():
60 flaskr.init_db()

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 61why, one step back
61

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 62why, one step back
62 yield client

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 63why, one step back
63

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 64–76why, one step back
64 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.7576Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 77–82why, one step back
77to create a temporary database and initialize it. The
78: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.82

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 83–85why, one step back
83To delete the database after the test, the fixture closes the file and removes
84it from the filesystem.85

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 86–87why, one step back
86If we now run the test suite, we should see the following output::
87

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 88why, one step back
88 $ pytest

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 89why, one step back
89

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 90–92why, one step back
90 ================ test session starts ================
91 rootdir: ./flask/examples/flaskr, inifile: setup.cfg92 collected 0 items

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 93why, one step back
93

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 94why, one step back
94 =========== no tests ran in 0.07 seconds ============

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 95why, one step back
95

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 96why, one step back
96Even though it did not run any actual tests, we already know that our ``flaskr``

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 97–99why, one step back
97application is syntactically valid, otherwise the import would have died
98with an exception.99

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 100–102why, one step back
100.. _pytest fixture:
101 https://docs.pytest.org/en/latest/fixture.html102

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 103–107why, one step back
103The First Test
104--------------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 we

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 108–109why, one step back
108access the root of the application (``/``). To do this, we add a new
109test function to :file:`test_flaskr.py`, like this::

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 110why, one step back
110

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 111–112why, one step back
111 def test_empty_db(client):
112 """Start with a blank database."""

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 113why, one step back
113

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 114–115why, one step back
114 rv = client.get('/')
115 assert b'No entries here so far' in rv.data

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 116–117why, one step back
116
117Notice that our test functions begin with the word `test`; this allows

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 118why, one step back
118`pytest`_ to automatically identify the function as a test to run.

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 119why, one step back
119

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 120why, one step back
120By using ``client.get`` we can send an HTTP ``GET`` request to the application with

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 121–127why, one step back
121the given path. The return value will be a :class:`~flask.Flask.response_class` object.
122We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect123the return value (as string) from the application. In this case, we ensure that124``'No entries here so far'`` is part of the output.125126Run it again and you should see one passing test::127

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 128why, one step back
128 $ pytest -v

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 129why, one step back
129

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 130–132why, one step back
130 ================ test session starts ================
131 rootdir: ./flask/examples/flaskr, inifile: setup.cfg132 collected 1 items

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 133why, one step back
133

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 134–137why, one step back
134 tests/test_flaskr.py::test_empty_db PASSED
135136 ============= 1 passed in 0.10 seconds ==============137

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 138–146why, one step back
138Logging In and Out
139------------------140141The majority of the functionality of our application is only available for142the administrative user, so we need a way to log our test client in and out143of the application. To do this, we fire some requests to the login and logout144pages with the required form data (username and password). And because the145login and logout pages redirect, we tell the client to `follow_redirects`.146

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 147why, one step back
147Add the following two functions to your :file:`test_flaskr.py` file::

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 148why, one step back
148

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 149–153why, one step back
149 def login(client, username, password):
150 return client.post('/login', data=dict(151 username=username,152 password=password153 ), follow_redirects=True)

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 154–155why, one step back
154
155

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 156–158why, one step back
156 def logout(client):
157 return client.get('/logout', follow_redirects=True)158

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 159why, one step back
159Now we can easily test that logging in and out works and that it fails with

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 160why, one step back
160invalid credentials. Add this new test function::

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 161why, one step back
161

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 162–163why, one step back
162 def test_login_logout(client):
163 """Make sure login and logout works."""

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 164why, one step back
164

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 165–176why, one step back
165 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])
166 assert b'You were logged in' in rv.data167168 rv = logout(client)169 assert b'You were logged out' in rv.data170171 rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])172 assert b'Invalid username' in rv.data173174 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')175 assert b'Invalid password' in rv.data176

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 177–179why, one step back
177Test Adding Messages
178--------------------179

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 180why, one step back
180We should also test that adding messages works. Add a new test function

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 181–182why, one step back
181like this::
182

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 183–187why, one step back
183 def test_messages(client):
184 """Test that messages work."""185186 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])187 rv = client.post('/add', data=dict(

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 188–190why, one step back
188 title='<Hello>',
189 text='<strong>HTML</strong> allowed here'190 ), follow_redirects=True)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 191–193why, one step back
191 assert b'No entries here so far' not in rv.data
192 assert b'&lt;Hello&gt;' in rv.data193 assert b'<strong>HTML</strong> allowed here' in rv.data

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 194–199why, one step back
194
195Here we check that HTML is allowed in the text but not in the title,196which is the intended behavior.197198Running that should now give us three passing tests::199

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 200why, one step back
200 $ pytest -v

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 201why, one step back
201

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 202–204why, one step back
202 ================ test session starts ================
203 rootdir: ./flask/examples/flaskr, inifile: setup.cfg204 collected 3 items

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 205why, one step back
205

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 206–211why, one step back
206 tests/test_flaskr.py::test_empty_db PASSED
207 tests/test_flaskr.py::test_login_logout PASSED208 tests/test_flaskr.py::test_messages PASSED209210 ============= 3 passed in 0.23 seconds ==============211

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 212–216why, one step back
212For more complex tests with headers and status codes, check out the
213`MiniTwit Example`_ from the sources which contains a larger test214suite.215216.. _MiniTwit Example:

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 217why, one step back
217 https://github.com/pallets/flask/tree/master/examples/minitwit/

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 218–223why, one step back
218
219Other Testing Tricks220--------------------221222Besides using the test client as shown above, there is also the223:meth:`~flask.Flask.test_request_context` method that can be used

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 224why, one step back
224in combination with the ``with`` statement to activate a request context

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 225–228why, one step back
225temporarily. With this you can access the :class:`~flask.request`,
226:class:`~flask.g` and :class:`~flask.session` objects like in view227functions. Here is a full example that demonstrates this approach::228

Merge pull request #1380 from KWinston/masterMarkus Unterwaditzerbefore adoptionb57a076

line 229why, one step back
229 import flask

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 230why, one step back
230

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 231–244why, one step back
231 app = flask.Flask(__name__)
232233 with app.test_request_context('/?name=Peter'):234 assert flask.request.path == '/'235 assert flask.request.args['name'] == 'Peter'236237All the other objects that are context bound can be used in the same238way.239240If you want to test your application with different configurations and241there does not seem to be a good way to do that, consider switching to242application factories (see :ref:`app-factories`).243244Note however that if you are using a test request context, the

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 245–246why, one step back
245:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`
246functions are not called automatically. However

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

line 247why, one step back
247:meth:`~flask.Flask.teardown_request` functions are indeed executed when

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 248why, one step back
248the test request context leaves the ``with`` block. If you do want the

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 249–295why, one step back
249:meth:`~flask.Flask.before_request` functions to be called as well, you
250need to call :meth:`~flask.Flask.preprocess_request` yourself::251252 app = flask.Flask(__name__)253254 with app.test_request_context('/?name=Peter'):255 app.preprocess_request()256 ...257258This can be necessary to open database connections or something similar259depending on how your application was designed.260261If you want to call the :meth:`~flask.Flask.after_request` functions you262need to call into :meth:`~flask.Flask.process_response` which however263requires that you pass it a response object::264265 app = flask.Flask(__name__)266267 with app.test_request_context('/?name=Peter'):268 resp = Response('...')269 resp = app.process_response(resp)270 ...271272This in general is less useful because at that point you can directly273start using the test client.274275.. _faking-resources:276277Faking Resources and Context278----------------------------279280.. versionadded:: 0.10281282A very common pattern is to store user authorization information and283database connections on the application context or the :attr:`flask.g`284object. The general pattern for this is to put the object on there on285first usage and then to remove it on a teardown. Imagine for instance286this code to get the current user::287288 def get_user():289 user = getattr(g, 'user', None)290 if user is None:291 user = fetch_current_user_from_database()292 g.user = user293 return user294295For a test it would be nice to override this user from the outside without

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 296why, one step back
296having to change some code. This can be accomplished with

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 297–299why, one step back
297hooking the :data:`flask.appcontext_pushed` signal::
298299 from contextlib import contextmanager

Merge pull request #1313 from homeworkprod/patch-1Markus Unterwaditzerbefore adoptionb68dc78

line 300why, one step back
300 from flask import appcontext_pushed, g

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 301–331why, one step back
301
302 @contextmanager303 def user_set(app, user):304 def handler(sender, **kwargs):305 g.user = user306 with appcontext_pushed.connected_to(handler, app):307 yield308309And then to use it::310311 from flask import json, jsonify312313 @app.route('/users/me')314 def users_me():315 return jsonify(username=g.user.username)316317 with user_set(app, my_user):318 with app.test_client() as c:319 resp = c.get('/users/me')320 data = json.loads(resp.data)321 self.assert_equal(data['username'], my_user.username)322323324Keeping the Context Around325--------------------------326327.. versionadded:: 0.4328329Sometimes it is helpful to trigger a regular request but still keep the330context around for a little longer so that additional introspection can331happen. With Flask 0.4 this is possible by using the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 332why, one step back
332:meth:`~flask.Flask.test_client` with a ``with`` block::

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 333–340why, one step back
333
334 app = flask.Flask(__name__)335336 with app.test_client() as c:337 rv = c.get('/?tequila=42')338 assert request.args['tequila'] == '42'339340If you were to use just the :meth:`~flask.Flask.test_client` without

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 341why, one step back
341the ``with`` block, the ``assert`` would fail with an error because `request`

Merge pull request #1225 from s3rvac/typo-and-cosmetic-fixesMarkus Unterwaditzerbefore adoption84efebd

lines 342–374why, one step back
342is no longer available (because you are trying to use it outside 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 flask.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. This works364independently 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 stored371372Note that in this case you have to use the ``sess`` object instead of the373:data:`flask.session` proxy. The object however itself will provide the374same interface.

Merge pull request #2358 from davidism/json-mixinDavid Lordbefore adoption63129e8

lines 375–405why, one step back
375
376377Testing JSON APIs378-----------------379380.. versionadded:: 1.0381382Flask has great support for JSON, and is a popular choice for building JSON383APIs. Making requests with JSON data and examining JSON data in responses is384very convenient::385386 from flask import request, jsonify387388 @app.route('/api/auth')389 def auth():390 json_data = request.get_json()391 email = json_data['email']392 password = json_data['password']393 return jsonify(token=generate_token(email, password))394395 with app.test_client() as c:396 rv = c.post('/api/auth', json={397 'username': 'flask', 'password': 'secret'398 })399 json_data = rv.get_json()400 assert verify_token(email, json_data['token'])401402Passing the ``json`` argument in the test client methods sets the request data403to the JSON-serialized object and sets the content type to404``application/json``. You can get the JSON data from the request or response405with ``get_json``.

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

lines 406–412why, one step back
406
407408.. _testing-cli:409410Testing CLI Commands411--------------------412

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

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

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

line 416why, one step back
416

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

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

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

lines 422–430why, one step back
422
423 import click424425 @app.cli.command('hello')426 @click.option('--name', default='World')427 def hello_command(name)428 click.echo(f'Hello, {name}!')429430 def test_hello():

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

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

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

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

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

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

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

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

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

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

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

lines 447–462why, one step back
447
448 def upper(ctx, param, value):449 if value is not None:450 return value.upper()451452 @app.cli.command('hello')453 @click.option('--name', default='World', callback=upper)454 def hello_command(name)455 click.echo(f'Hello, {name}!')456457 def test_hello_params():458 context = hello_command.make_context('hello', ['--name', 'flask'])459 assert context.params['name'] == 'FLASK'460461.. _click: http://click.pocoo.org/462.. _utilities for testing: http://click.pocoo.org/testing