Flask Test CLI Runner API
FlaskCliRunner is based on Click's CliRunner, used for testing Flask CLI commands.
Throughapp.test_cli_runner()Create instance.
Creation Method
| Method | Description |
|---|---|
| app.test_cli_runner(**kwargs) | Create a CLI test runner. kwargs are passed to the CliRunner constructor |
Core Methods
| Methods | Description |
|---|---|
| invoke(cli=None, args=None, **kwargs) | Invoke the CLI command. By default, use app.cli. Returns a click.testing.Result object. |
Result object attributes
| Property | Description |
|---|---|
| exit_code | Command exit code. 0 indicates success |
| output | Command's standard output content (str) |
| exception | If the command throws an exception, this contains the exception object. |
Code Examples
Example
from app import create_app
app = create_app()
runner = app.test_cli_runner()
# Test built-in commands
result = runner.invoke(args=["routes"])
assert result.exit_code == 0
assert "/api/posts" in result.output
# Test custom commands
result = runner.invoke(args=["init-db"])
assert result.exit_code == 0
# Test commands with arguments
result = runner.invoke(args=["greet", "--name", "EXAMPLE"])
assert "EXAMPLE" in result.output
# Directly use invoke to test the application CLI group
result = runner.invoke(app.cli, ["run", "--help"])
assert result.exit_code == 0
app = create_app()
runner = app.test_cli_runner()
# Test built-in commands
result = runner.invoke(args=["routes"])
assert result.exit_code == 0
assert "/api/posts" in result.output
# Test custom commands
result = runner.invoke(args=["init-db"])
assert result.exit_code == 0
# Test commands with arguments
result = runner.invoke(args=["greet", "--name", "EXAMPLE"])
assert "EXAMPLE" in result.output
# Directly use invoke to test the application CLI group
result = runner.invoke(app.cli, ["run", "--help"])
assert result.exit_code == 0