Skip to content
Myr

testing.md

This file

Path

docs/testing.md

283 lines · 7.7 KiB · Markdown

Last changed by

Merge main into stable (#3800)Rowlando13before adoption420c8fb

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

line 9why, one step back
9

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 10–15why, one step back
10```{warning}
11These tools should only be used for testing since they change the entire12interpreter state for simplicity. They are not thread-safe: see13[Running tests in parallel](#running-tests-in-parallel) for the supported14way to run CLI tests concurrently.15```

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

lines 16–27why, one step back
16
17The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.1819```{contents}20:depth: 121:local: true22```2324## Basic Example2526The key pieces are:27 - {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 28–30why, one step back
28 - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output
29 data, exit code, optional exception, and captures the output as bytes and30 binary data.

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

lines 31–57why, one step back
31
32```{code-block} python33:caption: hello.py3435import click3637@click.command()38@click.argument('name')39def hello(name):40 click.echo(f'Hello {name}!')41```4243```{code-block} python44:caption: test_hello.py4546from click.testing import CliRunner47from hello import hello4849def test_hello_world():50 runner = CliRunner()51 result = runner.invoke(hello, ['Peter'])52 assert result.exit_code == 053 assert result.output == 'Hello Peter!\n'54```5556## Subcommands57

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

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

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

lines 60–91why, one step back
60
61```{code-block} python62:caption: sync.py6364import click6566@click.group()67@click.option('--debug/--no-debug', default=False)68def cli(debug):69 click.echo(f"Debug mode is {'on' if debug else 'off'}")7071@cli.command()72def sync():73 click.echo('Syncing')74```7576```{code-block} python77:caption: test_sync.py7879from click.testing import CliRunner80from sync import cli8182def test_sync():83 runner = CliRunner()84 result = runner.invoke(cli, ['--debug', 'sync'])85 assert result.exit_code == 086 assert 'Debug mode is on' in result.output87 assert 'Syncing' in result.output88```8990## Context Settings91

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

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

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

lines 94–125why, one step back
94For example, setting a fixed terminal width equal to 60:
9596```{code-block} python97:caption: sync.py9899import click100101@click.group()102def cli():103 pass104105@cli.command()106def sync():107 click.echo('Syncing')108```109110```{code-block} python111:caption: test_sync.py112113from click.testing import CliRunner114from sync import cli115116def test_sync():117 runner = CliRunner()118 result = runner.invoke(cli, ['sync'], terminal_width=60)119 assert result.exit_code == 0120 assert 'Debug mode is on' in result.output121 assert 'Syncing' in result.output122```123124## File System Isolation125

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 126–130why, one step back
126To test a command that reads or writes files, give each test its own
127directory and pass absolute paths to the command. Pytest's128[`tmp_path`](https://docs.pytest.org/en/stable/how-to/tmp_path.html) fixture129provides a fresh directory per test; {class}`tempfile.TemporaryDirectory`130works without pytest.

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

lines 131–148why, one step back
131
132```{code-block} python133:caption: cat.py134135import click136137@click.command()138@click.argument('f', type=click.File())139def cat(f):140 click.echo(f.read())141```142143```{code-block} python144:caption: test_cat.py145146from click.testing import CliRunner147from cat import cat148

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 149–151why, one step back
149def test_cat(tmp_path):
150 hello = tmp_path / 'hello.txt'151 hello.write_text('Hello World!')

Revert "Deprecate `isolated_filesystem` and document its limits"Kevin Deldyckebefore adoption8ee83dd

line 152why, one step back
152

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 153–156why, one step back
153 runner = CliRunner()
154 result = runner.invoke(cat, [str(hello)])155 assert result.exit_code == 0156 assert result.output == 'Hello World!\n'

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

lines 157–158why, one step back
157```
158

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 159–161why, one step back
159Because the directory is unique to the test and the command receives an
160absolute path, nothing leaks between tests and the working directory is never161changed.

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

line 162why, one step back
162

Merge main into stable (#3800)Rowlando13before adoption420c8fb

line 163why, one step back
163### Running tests in parallel

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

line 164why, one step back
164

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 165–166why, one step back
165Isolating the file system with pytest is thread-safe: each test, or each thread,
166works in its own directory through absolute paths, with no shared state.

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

line 167why, one step back
167

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 168–172why, one step back
168{meth}`CliRunner.invoke` is different. While a command runs it swaps several
169pieces of process-global state into place (like `sys.stdout`, `sys.stderr`,170`sys.stdin`, etc). Two invocations active at the same time in one interpreter171overwrite each other's state, so the runner cannot be driven from several172threads at once.

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

line 173why, one step back
173

Merge main into stable (#3800)Rowlando13before adoption420c8fb

lines 174–189why, one step back
174```{warning}
175Do not parallelize CLI tests with threads. Use process-based isolation176instead, where each worker has its own interpreter and its own copy of those177globals. [pytest-xdist](https://pytest-xdist.readthedocs.io/) does this with178`pytest --numprocesses=auto`.179```180181Click's own test suite uses exactly this setup: the `tests-random` dependency182group and the `random` tox environment in183[`pyproject.toml`](https://github.com/pallets/click/blob/main/pyproject.toml)184run the suite under `pytest-randomly` and `pytest-xdist` to surface ordering185bugs and races.186187```{deprecated} 8.5.0188{meth}`CliRunner.isolated_filesystem` is deprecated and will be removed in189Click 9.0. Use a temporary directory with absolute paths, as shown above.

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

lines 190–193why, one step back
190```
191192## Input Streams193

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

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

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

lines 196–223why, one step back
196
197```{code-block} python198:caption: prompt.py199200import click201202@click.command()203@click.option('--foo', prompt=True)204def prompt(foo):205 click.echo(f"foo={foo}")206```207208```{code-block} python209:caption: test_prompt.py210211from click.testing import CliRunner212from prompt import prompt213214def test_prompts():215 runner = CliRunner()216 result = runner.invoke(prompt, input='wau wau\n')217 assert not result.exception218 assert result.output == 'Foo: wau wau\nfoo=wau wau\n'219```220221Prompts will be emulated so they write the input data to222the output stream as well. If hidden input is expected then this223does not happen.

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

line 224why, one step back
224

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 226why, one step back
226

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 230why, one step back
230

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 232why, one step back
232

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 235why, one step back
235

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 239why, one step back
239

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 244why, one step back
244

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 246why, one step back
246

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

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

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

line 251why, one step back
251

Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898

lines 252–282why, one step back
252- Stale references to the original `sys.stdout` and `sys.stderr`.
253- Logging frameworks that cache the original stream (like `structlog` or the254 stdlib's `logging` module).255- C extensions and subprocesses that write directly to `fd 1` or `fd 2`.256257```python258from click.testing import CliRunner259from myapp import cli260261262def test_captures_everything():263 runner = CliRunner(capture="fd")264 result = runner.invoke(cli)265 # result.stdout contains both Python-level and fd-level output266 assert "expected output" in result.stdout267```268269In this mode `sys.stdout.fileno()` returns the saved (pre-redirection) `fd`, so270{mod}`faulthandler` and similar consumers keep working. Writes to `fd 1` and271`fd 2` land in the capture tmpfile, so `os.dup2()` calls inside the CLI no272longer leak into the host runner's stdout.273274```{note}275`capture="fd"` is not available on Windows.276```277278```{versionchanged} 8.4.0279Added the `capture` parameter. The default `sys` mode no longer exposes the280original `fd` through `fileno()`, reverting the change introduced in `8.3.3`281that broke Pytest's `fd`-level capture teardown. Use `capture="fd"` to restore282that behavior with proper isolation.

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

line 283why, one step back
283```