Skip to content
Myr

add test_cli_runner for testing app.cli commands

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 · parent 79f34f1 · Browse files · 6 files+140 added−12 removed
This commit

State

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

Diff stats

6 files+140 added−12 removed

  • tests:+47 added−2 removed
  • other:+93 added−10 removed

6 files+140 added−12 removed

modified:docs/api.rst+9 added
186 unmodified lines
187.. autoclass:: FlaskClient188 :members:189190191Test CLI Runner192---------------193194.. currentmodule:: flask.testing195196.. autoclass:: FlaskCliRunner197 :members:198199200Application Globals201-------------------202203.. currentmodule:: flask
634 unmodified lines
modified:docs/testing.rst+20 added-10 removed
411 unmodified lines
412413Testing CLI Commands414--------------------415416Click comes with `utilities for testing`_ your CLI commands.416Click comes with `utilities for testing`_ your CLI commands. A417:class:`~click.testing.CliRunner` runs commands in isolation and418captures the output in a :class:`~click.testing.Result` object.419418Use :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` to call419commands in the same way they would be called from the command line. The420:class:`~click.testing.CliRunner` runs the command in isolation and421captures the output in a :class:`~click.testing.Result` object. ::420Flask provides :meth:`~flask.Flask.test_cli_runner` to create a421:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the422CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`423method to call commands in the same way they would be called from the424command line. ::425426 import click424 from click.testing import CliRunner427428 @app.cli.command('hello')429 @click.option('--name', default='World')430 def hello_command(name)431 click.echo(f'Hello, {name}!')432433 def test_hello():432 runner = CliRunner()434 runner = app.test_cli_runner()435436 # invoke the command directly437 result = runner.invoke(hello_command, ['--name', 'Flask'])438 assert 'Hello, Flask' in result.output439440 # or by name441 result = runner.invoke(args=['hello'])442 assert 'World' in result.output443444In the example above, invoking the command by name is useful because it445verifies that the command was correctly registered with the app.446447If you want to test how your command parses parameters, without running437the command, use the command's :meth:`~click.BaseCommand.make_context`438method. This is useful for testing complex validation rules and custom439types. ::448the command, use its :meth:`~click.BaseCommand.make_context` method.449This is useful for testing complex validation rules and custom types. ::450451 def upper(ctx, param, value):452 if value is not None:453 return value.upper()
12 unmodified lines
modified:flask/app.py+25 added
309 unmodified lines
310 #:311 #: .. versionadded:: 0.7312 test_client_class = None313314 #: The :class:`~click.testing.CliRunner` subclass, by default315 #: :class:`~flask.testing.FlaskCliRunner` that is used by316 #: :meth:`test_cli_runner`. Its ``__init__`` method should take a317 #: Flask app object as the first argument.318 #:319 #: .. versionadded:: 1.0320 test_cli_runner_class = None321322 #: the session interface to use. By default an instance of323 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.324 #:325 #: .. versionadded:: 0.8
664 unmodified lines
990 if cls is None:991 from flask.testing import FlaskClient as cls992 return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)993994 def test_cli_runner(self, **kwargs):995 """Create a CLI runner for testing CLI commands.996 See :ref:`testing-cli`.997998 Returns an instance of :attr:`test_cli_runner_class`, by default999 :class:`~flask.testing.FlaskCliRunner`. The Flask app object is1000 passed as the first argument.10011002 .. versionadded:: 1.01003 """1004 cls = self.test_cli_runner_class10051006 if cls is None:1007 from flask.testing import FlaskCliRunner as cls10081009 return cls(self, **kwargs)10101011 def open_session(self, request):1012 """Creates or opens a new session. Default implementation stores all1013 session data in a signed cookie. This requires that the1014 :attr:`secret_key` is set. Instead of overriding this method
1225 unmodified lines
modified:flask/testing.py+36 added
10 unmodified lines
11"""1213import werkzeug14from contextlib import contextmanager1516from click.testing import CliRunner17from flask.cli import ScriptInfo18from werkzeug.test import Client, EnvironBuilder19from flask import _request_ctx_stack20from flask.json import dumps as json_dumps21from werkzeug.urls import url_parse
173 unmodified lines
195 # in. See RequestGlobals.push() for the general behavior.196 top = _request_ctx_stack.top197 if top is not None and top.preserved:198 top.pop()199200201class FlaskCliRunner(CliRunner):202 """A :class:`~click.testing.CliRunner` for testing a Flask app's203 CLI commands. Typically created using204 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.205 """206 def __init__(self, app, **kwargs):207 self.app = app208 super(FlaskCliRunner, self).__init__(**kwargs)209210 def invoke(self, cli=None, args=None, **kwargs):211 """Invokes a CLI command in an isolated environment. See212 :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for213 full method documentation. See :ref:`testing-cli` for examples.214215 If the ``obj`` argument is not given, passes an instance of216 :class:`~flask.cli.ScriptInfo` that knows how to load the Flask217 app being tested.218219 :param cli: Command object to invoke. Default is the app's220 :attr:`~flask.app.Flask.cli` group.221 :param args: List of strings to invoke the command with.222223 :return: a :class:`~click.testing.Result` object.224 """225 if cli is None:226 cli = self.app.cli227228 if 'obj' not in kwargs:229 kwargs['obj'] = ScriptInfo(create_app=lambda: self.app)230231 return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)
modified:tests/test_testing.py+47 added-2 removed
6 unmodified lines
78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1111import click12import pytest1314import flask15import werkzeug1617from flask._compat import text_type18from flask.cli import ScriptInfo19from flask.json import jsonify19from flask.testing import make_test_environ_builder20from flask.testing import make_test_environ_builder, FlaskCliRunner212223def test_environ_defaults_from_config(app, client):24 app.config['SERVER_NAME'] = 'example.com:1234'
310 unmodified lines
335 response = client.get(url)336337 assert 200 == response.status_code338 assert b'xxx' == response.data339340341def test_cli_runner_class(app):342 runner = app.test_cli_runner()343 assert isinstance(runner, FlaskCliRunner)344345 class SubRunner(FlaskCliRunner):346 pass347348 app.test_cli_runner_class = SubRunner349 runner = app.test_cli_runner()350 assert isinstance(runner, SubRunner)351352353def test_cli_invoke(app):354 @app.cli.command('hello')355 def hello_command():356 click.echo('Hello, World!')357358 runner = app.test_cli_runner()359 # invoke with command name360 result = runner.invoke(args=['hello'])361 assert 'Hello' in result.output362 # invoke with command object363 result = runner.invoke(hello_command)364 assert 'Hello' in result.output365366367def test_cli_custom_obj(app):368 class NS(object):369 called = False370371 def create_app():372 NS.called = True373 return app374375 @app.cli.command('hello')376 def hello_command():377 click.echo('Hello, World!')378379 script_info = ScriptInfo(create_app=create_app)380 runner = app.test_cli_runner()381 runner.invoke(hello_command, obj=script_info)382 assert NS.called
modified:CHANGES.rst+3 added
135 unmodified lines
136- Pass ``--cert`` and ``--key`` options to ``flask run`` to run the137 development server over HTTPS. (`#2606`_)138- Added :data:`SESSION_COOKIE_SAMESITE` to control the ``SameSite``139 attribute on the session cookie. (`#2607`_)140- Added :meth:`~flask.Flask.test_cli_runner` to create a Click runner141 that can invoke Flask CLI commands for testing. (`#2636`_)142143.. _pallets/meta#24: https://github.com/pallets/meta/issues/24144.. _#1421: https://github.com/pallets/flask/issues/1421145.. _#1489: https://github.com/pallets/flask/pull/1489
33 unmodified lines
179.. _#2586: https://github.com/pallets/flask/issues/2586180.. _#2581: https://github.com/pallets/flask/pull/2581181.. _#2606: https://github.com/pallets/flask/pull/2606182.. _#2607: https://github.com/pallets/flask/pull/2607183.. _#2636: https://github.com/pallets/flask/pull/2636184185186Version 0.12.2187--------------
618 unmodified lines