Merge pull request #2636 from pallets/test-cli-runner
Before adoption: this commit came in with the history the project adopted, so no landing records it.
add test_cli_runner for testing app.cli commands
authored by David Lord · committed by GitHub · parents 79f34f1, cf5525f · 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
Provenance
- Commit
4a7db66- Tree
ac4564a- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
79f34f1- Parent 2
cf5525f
6 files changed+140 added−12 removed
modified:docs/api.rst+9 added
186 unmodified lines187 .. autoclass:: FlaskClient188 :members:189 190 191+Test CLI Runner192+---------------193+194+.. currentmodule:: flask.testing195+196+.. autoclass:: FlaskCliRunner197+ :members:198+199+200 Application Globals201 -------------------202 203 .. currentmodule:: flask634 unmodified linesmodified:docs/testing.rst+20 added-10 removed
411 unmodified lines412 413 Testing CLI Commands414 --------------------415 416-Click comes with `utilities for testing`_ your CLI commands.416+Click comes with `utilities for testing`_ your CLI commands. A417+:class:`~click.testing.CliRunner` runs commands in isolation and418+captures the output in a :class:`~click.testing.Result` object.419 418-Use :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` to call419-commands in the same way they would be called from the command line. The420-:class:`~click.testing.CliRunner` runs the command in isolation and421-captures the output in a :class:`~click.testing.Result` object. ::420+Flask provides :meth:`~flask.Flask.test_cli_runner` to create a421+:class:`~flask.testing.FlaskCliRunner` that passes the Flask app to the422+CLI automatically. Use its :meth:`~flask.testing.FlaskCliRunner.invoke`423+method to call commands in the same way they would be called from the424+command line. ::425 426 import click424- from click.testing import CliRunner427 428 @app.cli.command('hello')429 @click.option('--name', default='World')430 def hello_command(name)431 click.echo(f'Hello, {name}!')432 433 def test_hello():432- runner = CliRunner()434+ runner = app.test_cli_runner()435+436+ # invoke the command directly437 result = runner.invoke(hello_command, ['--name', 'Flask'])438 assert 'Hello, Flask' in result.output439 440+ # or by name441+ result = runner.invoke(args=['hello'])442+ assert 'World' in result.output443+444+In the example above, invoking the command by name is useful because it445+verifies that the command was correctly registered with the app.446+447 If you want to test how your command parses parameters, without running437-the command, use the command's :meth:`~click.BaseCommand.make_context`438-method. This is useful for testing complex validation rules and custom439-types. ::448+the command, use its :meth:`~click.BaseCommand.make_context` method.449+This is useful for testing complex validation rules and custom types. ::450 451 def upper(ctx, param, value):452 if value is not None:453 return value.upper()12 unmodified linesmodified:flask/app.py+25 added
309 unmodified lines310 #:311 #: .. versionadded:: 0.7312 test_client_class = None313 314+ #: 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 = None321+322 #: the session interface to use. By default an instance of323 #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.324 #:325 #: .. versionadded:: 0.8664 unmodified lines990 if cls is None:991 from flask.testing import FlaskClient as cls992 return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)993 994+ def test_cli_runner(self, **kwargs):995+ """Create a CLI runner for testing CLI commands.996+ See :ref:`testing-cli`.997+998+ 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.1001+1002+ .. versionadded:: 1.01003+ """1004+ cls = self.test_cli_runner_class1005+1006+ if cls is None:1007+ from flask.testing import FlaskCliRunner as cls1008+1009+ return cls(self, **kwargs)1010+1011 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 method1225 unmodified linesmodified:flask/testing.py+36 added
10 unmodified lines11 """12 13 import werkzeug14 from contextlib import contextmanager15+16+from click.testing import CliRunner17+from flask.cli import ScriptInfo18 from werkzeug.test import Client, EnvironBuilder19 from flask import _request_ctx_stack20 from flask.json import dumps as json_dumps21 from werkzeug.urls import url_parse173 unmodified lines195 # 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()199+200+201+class 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)209+210+ 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.214+215+ 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.218+219+ :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.222+223+ :return: a :class:`~click.testing.Result` object.224+ """225+ if cli is None:226+ cli = self.app.cli227+228+ if 'obj' not in kwargs:229+ kwargs['obj'] = ScriptInfo(create_app=lambda: self.app)230+231+ return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)modified:tests/test_testing.py+47 added-2 removed
6 unmodified lines7 8 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10 """11-11+import click12 import pytest13 14 import flask15 import werkzeug16 17 from flask._compat import text_type18+from flask.cli import ScriptInfo19 from flask.json import jsonify19-from flask.testing import make_test_environ_builder20+from flask.testing import make_test_environ_builder, FlaskCliRunner21 22 23 def test_environ_defaults_from_config(app, client):24 app.config['SERVER_NAME'] = 'example.com:1234'310 unmodified lines335 response = client.get(url)336 337 assert 200 == response.status_code338 assert b'xxx' == response.data339+340+341+def test_cli_runner_class(app):342+ runner = app.test_cli_runner()343+ assert isinstance(runner, FlaskCliRunner)344+345+ class SubRunner(FlaskCliRunner):346+ pass347+348+ app.test_cli_runner_class = SubRunner349+ runner = app.test_cli_runner()350+ assert isinstance(runner, SubRunner)351+352+353+def test_cli_invoke(app):354+ @app.cli.command('hello')355+ def hello_command():356+ click.echo('Hello, World!')357+358+ 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.output365+366+367+def test_cli_custom_obj(app):368+ class NS(object):369+ called = False370+371+ def create_app():372+ NS.called = True373+ return app374+375+ @app.cli.command('hello')376+ def hello_command():377+ click.echo('Hello, World!')378+379+ script_info = ScriptInfo(create_app=create_app)380+ runner = app.test_cli_runner()381+ runner.invoke(hello_command, obj=script_info)382+ assert NS.calledmodified:CHANGES.rst+3 added
135 unmodified lines136 - 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`_)142 143 .. _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/148933 unmodified lines179 .. _#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/2636184 185 186 Version 0.12.2187 --------------618 unmodified lines