| 1 |
# Testing Click Applications |
| 2 |
|
| 3 |
```{eval-rst} |
| 4 |
.. currentmodule:: click.testing |
| 5 |
``` |
| 6 |
|
| 7 |
Click provides the {ref}`click.testing <testing>` module to help you invoke |
| 8 |
command line applications and check their behavior. |
| 9 |
|
| 10 |
These tools should only be used for testing since they change |
| 11 |
the entire interpreter state for simplicity. They are not thread-safe! |
| 12 |
|
| 13 |
The examples use [pytest](https://docs.pytest.org/en/stable/) style tests. |
| 14 |
|
| 15 |
```{contents} |
| 16 |
:depth: 1 |
| 17 |
:local: true |
| 18 |
``` |
| 19 |
|
| 20 |
## Basic Example |
| 21 |
|
| 22 |
The key pieces are: |
| 23 |
- {class}`CliRunner` - used to invoke commands as command line scripts. |
| 24 |
- {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output |
| 25 |
data, exit code, optional exception, and captures the output as bytes and |
| 26 |
binary data. |
| 27 |
|
| 28 |
```{code-block} python |
| 29 |
:caption: hello.py |
| 30 |
|
| 31 |
import click |
| 32 |
|
| 33 |
@click.command() |
| 34 |
@click.argument('name') |
| 35 |
def hello(name): |
| 36 |
click.echo(f'Hello {name}!') |
| 37 |
``` |
| 38 |
|
| 39 |
```{code-block} python |
| 40 |
:caption: test_hello.py |
| 41 |
|
| 42 |
from click.testing import CliRunner |
| 43 |
from hello import hello |
| 44 |
|
| 45 |
def test_hello_world(): |
| 46 |
runner = CliRunner() |
| 47 |
result = runner.invoke(hello, ['Peter']) |
| 48 |
assert result.exit_code == 0 |
| 49 |
assert result.output == 'Hello Peter!\n' |
| 50 |
``` |
| 51 |
|
| 52 |
## Subcommands |
| 53 |
|
| 54 |
A subcommand name must be specified in the `args` parameter |
| 55 |
{meth}`CliRunner.invoke`: |
| 56 |
|
| 57 |
```{code-block} python |
| 58 |
:caption: sync.py |
| 59 |
|
| 60 |
import click |
| 61 |
|
| 62 |
@click.group() |
| 63 |
@click.option('--debug/--no-debug', default=False) |
| 64 |
def cli(debug): |
| 65 |
click.echo(f"Debug mode is {'on' if debug else 'off'}") |
| 66 |
|
| 67 |
@cli.command() |
| 68 |
def sync(): |
| 69 |
click.echo('Syncing') |
| 70 |
``` |
| 71 |
|
| 72 |
```{code-block} python |
| 73 |
:caption: test_sync.py |
| 74 |
|
| 75 |
from click.testing import CliRunner |
| 76 |
from sync import cli |
| 77 |
|
| 78 |
def test_sync(): |
| 79 |
runner = CliRunner() |
| 80 |
result = runner.invoke(cli, ['--debug', 'sync']) |
| 81 |
assert result.exit_code == 0 |
| 82 |
assert 'Debug mode is on' in result.output |
| 83 |
assert 'Syncing' in result.output |
| 84 |
``` |
| 85 |
|
| 86 |
## Context Settings |
| 87 |
|
| 88 |
Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to |
| 89 |
construct the initial {class}`Context object <click.Context>`. |
| 90 |
For example, setting a fixed terminal width equal to 60: |
| 91 |
|
| 92 |
```{code-block} python |
| 93 |
:caption: sync.py |
| 94 |
|
| 95 |
import click |
| 96 |
|
| 97 |
@click.group() |
| 98 |
def cli(): |
| 99 |
pass |
| 100 |
|
| 101 |
@cli.command() |
| 102 |
def sync(): |
| 103 |
click.echo('Syncing') |
| 104 |
``` |
| 105 |
|
| 106 |
```{code-block} python |
| 107 |
:caption: test_sync.py |
| 108 |
|
| 109 |
from click.testing import CliRunner |
| 110 |
from sync import cli |
| 111 |
|
| 112 |
def test_sync(): |
| 113 |
runner = CliRunner() |
| 114 |
result = runner.invoke(cli, ['sync'], terminal_width=60) |
| 115 |
assert result.exit_code == 0 |
| 116 |
assert 'Debug mode is on' in result.output |
| 117 |
assert 'Syncing' in result.output |
| 118 |
``` |
| 119 |
|
| 120 |
## File System Isolation |
| 121 |
|
| 122 |
The {meth}`CliRunner.isolated_filesystem` context manager sets the current |
| 123 |
working directory to a new, empty folder. |
| 124 |
|
| 125 |
```{code-block} python |
| 126 |
:caption: cat.py |
| 127 |
|
| 128 |
import click |
| 129 |
|
| 130 |
@click.command() |
| 131 |
@click.argument('f', type=click.File()) |
| 132 |
def cat(f): |
| 133 |
click.echo(f.read()) |
| 134 |
``` |
| 135 |
|
| 136 |
```{code-block} python |
| 137 |
:caption: test_cat.py |
| 138 |
|
| 139 |
from click.testing import CliRunner |
| 140 |
from cat import cat |
| 141 |
|
| 142 |
def test_cat(): |
| 143 |
runner = CliRunner() |
| 144 |
with runner.isolated_filesystem(): |
| 145 |
with open('hello.txt', 'w') as f: |
| 146 |
f.write('Hello World!') |
| 147 |
|
| 148 |
result = runner.invoke(cat, ['hello.txt']) |
| 149 |
assert result.exit_code == 0 |
| 150 |
assert result.output == 'Hello World!\n' |
| 151 |
``` |
| 152 |
|
| 153 |
Pass in a path to control where the temporary directory is created. |
| 154 |
In this case, the directory will not be removed by Click. Its useful |
| 155 |
to integrate with a framework like Pytest that manages temporary files. |
| 156 |
|
| 157 |
```{code-block} python |
| 158 |
:caption: test_cat.py |
| 159 |
|
| 160 |
from click.testing import CliRunner |
| 161 |
from cat import cat |
| 162 |
|
| 163 |
def test_cat_with_path_specified(): |
| 164 |
runner = CliRunner() |
| 165 |
with runner.isolated_filesystem('~/test_folder'): |
| 166 |
with open('hello.txt', 'w') as f: |
| 167 |
f.write('Hello World!') |
| 168 |
|
| 169 |
result = runner.invoke(cat, ['hello.txt']) |
| 170 |
assert result.exit_code == 0 |
| 171 |
assert result.output == 'Hello World!\n' |
| 172 |
``` |
| 173 |
|
| 174 |
## Input Streams |
| 175 |
|
| 176 |
The test wrapper can provide input data for the input stream (stdin). This is |
| 177 |
very useful for testing prompts. |
| 178 |
|
| 179 |
```{code-block} python |
| 180 |
:caption: prompt.py |
| 181 |
|
| 182 |
import click |
| 183 |
|
| 184 |
@click.command() |
| 185 |
@click.option('--foo', prompt=True) |
| 186 |
def prompt(foo): |
| 187 |
click.echo(f"foo={foo}") |
| 188 |
``` |
| 189 |
|
| 190 |
```{code-block} python |
| 191 |
:caption: test_prompt.py |
| 192 |
|
| 193 |
from click.testing import CliRunner |
| 194 |
from prompt import prompt |
| 195 |
|
| 196 |
def test_prompts(): |
| 197 |
runner = CliRunner() |
| 198 |
result = runner.invoke(prompt, input='wau wau\n') |
| 199 |
assert not result.exception |
| 200 |
assert result.output == 'Foo: wau wau\nfoo=wau wau\n' |
| 201 |
``` |
| 202 |
|
| 203 |
Prompts will be emulated so they write the input data to |
| 204 |
the output stream as well. If hidden input is expected then this |
| 205 |
does not happen. |
| 206 |
|
| 207 |
## File Descriptors and Low-Level I/O |
| 208 |
|
| 209 |
{class}`CliRunner` captures output by replacing |
| 210 |
`sys.stdout` and `sys.stderr` with in-memory |
| 211 |
{class}`~io.BytesIO`-backed wrappers. This is |
| 212 |
Python-level redirection: calls to {func}`~click.echo`, |
| 213 |
{func}`print`, or `sys.stdout.write()` are captured, but |
| 214 |
the wrappers have no OS-level file descriptor. |
| 215 |
|
| 216 |
Code that calls `fileno()` on `sys.stdout` or |
| 217 |
`sys.stderr`, like {mod}`faulthandler`, |
| 218 |
{mod}`subprocess`, or C extensions, would normally crash |
| 219 |
with {exc}`io.UnsupportedOperation` inside |
| 220 |
{class}`CliRunner`. |
| 221 |
|
| 222 |
To avoid this, {class}`CliRunner` preserves the original |
| 223 |
stream's file descriptor and exposes it via `fileno()` on |
| 224 |
the replacement wrapper. |
| 225 |
|
| 226 |
This means: |
| 227 |
- **Python-level writes** (`print()`, `click.echo()`, |
| 228 |
...) are captured as usual. |
| 229 |
- **fd-level writes** (C code writing directly to the |
| 230 |
file descriptor) go to the original terminal and are |
| 231 |
**not** captured. |
| 232 |
|
| 233 |
This is the same trade-off that |
| 234 |
[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html) |
| 235 |
makes with its two capture modes: |
| 236 |
|
| 237 |
- `capsys`, which captures Python-level output, where |
| 238 |
`fileno()` raises `UnsupportedOperation` and fd-level |
| 239 |
writes are not captured. |
| 240 |
- `capfd`, which captures fd-level output via |
| 241 |
`os.dup2()`, where `fileno()` works and fd-level |
| 242 |
writes *are* captured. |
| 243 |
|
| 244 |
Rather than implementing a full `capfd`-style mechanism, |
| 245 |
{class}`CliRunner` takes the simpler path: expose the |
| 246 |
original `fd` so that standard library helpers keep |
| 247 |
working, while accepting that their output is not |
| 248 |
captured. |
| 249 |
|
| 250 |
```{versionchanged} 8.3.3 |
| 251 |
`fileno()` on the redirected streams now returns the |
| 252 |
original stream's file descriptor instead of raising. |
| 253 |
``` |