Skip to content
Myr

Merge pull request #2611 from pallets/cli-test-docs

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

document testing cli commands

authored by David Lord · committed by GitHub · parents 94aaa24, ae30fe7 · Browse files · 2 files+50 added−0 removed
This commit

State

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

Diff stats

2 files+50 added−0 removed

  • other:+50 added−0 removed

2 files+50 added−0 removed

modified:docs/cli.rst+3 added
245 unmodified lines
246::247248 flask user create demo249250See :ref:`testing-cli` for an overview of how to test your custom251commands.252253254Application Context255~~~~~~~~~~~~~~~~~~~256257Commands added using the Flask app's :attr:`~Flask.cli`
167 unmodified lines
modified:docs/testing.rst+47 added
404 unmodified lines
405Passing the ``json`` argument in the test client methods sets the request data406to the JSON-serialized object and sets the content type to407``application/json``. You can get the JSON data from the request or response408with ``get_json``.409410411.. _testing-cli:412413Testing CLI Commands414--------------------415416Click comes with `utilities for testing`_ your CLI commands.417418Use :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. ::422423 import click424 from click.testing import CliRunner425426 @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 = CliRunner()433 result = runner.invoke(hello_command, ['--name', 'Flask'])434 assert 'Hello, Flask' in result.output435436If 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. ::440441 def upper(ctx, param, value):442 if value is not None:443 return value.upper()444445 @app.cli.command('hello')446 @click.option('--name', default='World', callback=upper)447 def hello_command(name)448 click.echo(f'Hello, {name}!')449450 def test_hello_params():451 context = hello_command.make_context('hello', ['--name', 'flask'])452 assert context.params['name'] == 'FLASK'453454.. _click: http://click.pocoo.org/455.. _utilities for testing: http://click.pocoo.org/testing