Skip to content
Myr

testing.md

This file

Path

docs/testing.md

265 lines · 6.7 KiB · Markdown

Last changed by

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

History of this file

Take it

Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1

lines 1–6why, one step back
1# Testing Click Applications
23```{eval-rst}4.. currentmodule:: click.testing5```6

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 7–8why, one step back
7Click provides the {ref}`click.testing <testing>` module to help you invoke
8command line applications and check their behavior.

Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1

lines 9–23why, one step back
9
10These tools should only be used for testing since they change11the entire interpreter state for simplicity. They are not thread-safe!1213The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.1415```{contents}16:depth: 117:local: true18```1920## Basic Example2122The key pieces are:23 - {class}`CliRunner` - used to invoke commands as command line scripts.

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 24–26why, one step back
24 - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output
25 data, exit code, optional exception, and captures the output as bytes and26 binary data.

Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1

lines 27–53why, one step back
27
28```{code-block} python29:caption: hello.py3031import click3233@click.command()34@click.argument('name')35def hello(name):36 click.echo(f'Hello {name}!')37```3839```{code-block} python40:caption: test_hello.py4142from click.testing import CliRunner43from hello import hello4445def test_hello_world():46 runner = CliRunner()47 result = runner.invoke(hello, ['Peter'])48 assert result.exit_code == 049 assert result.output == 'Hello Peter!\n'50```5152## Subcommands53

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 54–55why, one step back
54A subcommand name must be specified in the `args` parameter
55{meth}`CliRunner.invoke`:

Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1

lines 56–87why, one step back
56
57```{code-block} python58:caption: sync.py5960import click6162@click.group()63@click.option('--debug/--no-debug', default=False)64def cli(debug):65 click.echo(f"Debug mode is {'on' if debug else 'off'}")6667@cli.command()68def sync():69 click.echo('Syncing')70```7172```{code-block} python73:caption: test_sync.py7475from click.testing import CliRunner76from sync import cli7778def test_sync():79 runner = CliRunner()80 result = runner.invoke(cli, ['--debug', 'sync'])81 assert result.exit_code == 082 assert 'Debug mode is on' in result.output83 assert 'Syncing' in result.output84```8586## Context Settings87

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 88–89why, one step back
88Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to
89construct the initial {class}`Context object <click.Context>`.

Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1

lines 90–121why, one step back
90For example, setting a fixed terminal width equal to 60:
9192```{code-block} python93:caption: sync.py9495import click9697@click.group()98def cli():99 pass100101@cli.command()102def sync():103 click.echo('Syncing')104```105106```{code-block} python107:caption: test_sync.py108109from click.testing import CliRunner110from sync import cli111112def test_sync():113 runner = CliRunner()114 result = runner.invoke(cli, ['sync'], terminal_width=60)115 assert result.exit_code == 0116 assert 'Debug mode is on' in result.output117 assert 'Syncing' in result.output118```119120## File System Isolation121

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 122–123why, one step back
122The {meth}`CliRunner.isolated_filesystem` context manager sets the current
123working directory to a new, empty folder.

Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1

lines 124–175why, one step back
124
125```{code-block} python126:caption: cat.py127128import click129130@click.command()131@click.argument('f', type=click.File())132def cat(f):133 click.echo(f.read())134```135136```{code-block} python137:caption: test_cat.py138139from click.testing import CliRunner140from cat import cat141142def test_cat():143 runner = CliRunner()144 with runner.isolated_filesystem():145 with open('hello.txt', 'w') as f:146 f.write('Hello World!')147148 result = runner.invoke(cat, ['hello.txt'])149 assert result.exit_code == 0150 assert result.output == 'Hello World!\n'151```152153Pass in a path to control where the temporary directory is created.154In this case, the directory will not be removed by Click. Its useful155to integrate with a framework like Pytest that manages temporary files.156157```{code-block} python158:caption: test_cat.py159160from click.testing import CliRunner161from cat import cat162163def 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!')168169 result = runner.invoke(cat, ['hello.txt'])170 assert result.exit_code == 0171 assert result.output == 'Hello World!\n'172```173174## Input Streams175

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 176–177why, one step back
176The test wrapper can provide input data for the input stream (stdin). This is
177very useful for testing prompts.

Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1

lines 178–205why, one step back
178
179```{code-block} python180:caption: prompt.py181182import click183184@click.command()185@click.option('--foo', prompt=True)186def prompt(foo):187 click.echo(f"foo={foo}")188```189190```{code-block} python191:caption: test_prompt.py192193from click.testing import CliRunner194from prompt import prompt195196def test_prompts():197 runner = CliRunner()198 result = runner.invoke(prompt, input='wau wau\n')199 assert not result.exception200 assert result.output == 'Foo: wau wau\nfoo=wau wau\n'201```202203Prompts will be emulated so they write the input data to204the output stream as well. If hidden input is expected then this205does not happen.

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 206why, one step back
206

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

line 207why, one step back
207## Capture modes

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 208why, one step back
208

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 209–211why, one step back
209{class}`CliRunner` captures output by replacing `sys.stdout` and `sys.stderr`
210with in-memory wrappers. The `capture` parameter controls which strategy is211used.

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 212why, one step back
212

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

line 213why, one step back
213### `capture="sys"` (default)

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 214why, one step back
214

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 215–216why, one step back
215Captures Python-level writes (`print()`, `click.echo()`, `sys.stdout.write()`).
216It is fast and sufficient for most Click applications.

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 217why, one step back
217

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 218–220why, one step back
218Code that holds a reference to the original `sys.stdout` (like a library that
219does `from sys import stdout` at import time) bypasses the capture and its220output is lost.

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 221why, one step back
221

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 222–225why, one step back
222In this mode `sys.stdout.fileno()` and `sys.stderr.fileno()` raise
223{exc}`io.UnsupportedOperation`, matching the pre-`8.3.3` behavior. C-level224consumers ({mod}`faulthandler`, {mod}`subprocess`, C extensions) that expect a225real file descriptor must opt into the `capture="fd"` mode.

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 226why, one step back
226

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

line 227why, one step back
227### `capture="fd"`

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 228why, one step back
228

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 229–232why, one step back
229Redirects OS file descriptors `1` and `2` to a temporary file via
230{func}`os.dup2`, inspired by [Pytest's231`capfd`](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html).232This catches output that bypasses `sys.stdout`, including:

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 233why, one step back
233

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 234–264why, one step back
234- Stale references to the original `sys.stdout` and `sys.stderr`.
235- Logging frameworks that cache the original stream (like `structlog` or the236 stdlib's `logging` module).237- C extensions and subprocesses that write directly to `fd 1` or `fd 2`.238239```python240from click.testing import CliRunner241from myapp import cli242243244def test_captures_everything():245 runner = CliRunner(capture="fd")246 result = runner.invoke(cli)247 # result.stdout contains both Python-level and fd-level output248 assert "expected output" in result.stdout249```250251In this mode `sys.stdout.fileno()` returns the saved (pre-redirection) `fd`, so252{mod}`faulthandler` and similar consumers keep working. Writes to `fd 1` and253`fd 2` land in the capture tmpfile, so `os.dup2()` calls inside the CLI no254longer leak into the host runner's stdout.255256```{note}257`capture="fd"` is not available on Windows.258```259260```{versionchanged} 8.4.0261Added the `capture` parameter. The default `sys` mode no longer exposes the262original `fd` through `fileno()`, reverting the change introduced in `8.3.3`263that broke Pytest's `fd`-level capture teardown. Use `capture="fd"` to restore264that behavior with proper isolation.

Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae

line 265why, one step back
265```