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 fileTake it
Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1
lines 1–6why, one step back1# Testing Click Applications23```{eval-rst}4.. currentmodule:: click.testing5```6Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e
lines 7–8why, one step back7Click provides the {ref}`click.testing <testing>` module to help you invoke8command line applications and check their behavior.Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1
line 9why, one step back9Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 10–15why, one step back10```{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 back1617The 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 back28 - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output29 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 back3132```{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## Subcommands57Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e
lines 58–59why, one step back58A subcommand name must be specified in the `args` parameter59{meth}`CliRunner.invoke`:Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1
lines 60–91why, one step back6061```{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 Settings91Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e
lines 92–93why, one step back92Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to93construct the initial {class}`Context object <click.Context>`.Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1
lines 94–125why, one step back94For 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 Isolation125Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 126–130why, one step back126To test a command that reads or writes files, give each test its own127directory 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 back131132```{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 cat148Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 149–151why, one step back149def 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 back152Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 153–156why, one step back153 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 back157```158Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 159–161why, one step back159Because the directory is unique to the test and the command receives an160absolute 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 back162Merge main into stable (#3800)Rowlando13before adoption420c8fb
line 163why, one step back163### Running tests in parallelRewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1
line 164why, one step back164Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 165–166why, one step back165Isolating 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 back167Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 168–172why, one step back168{meth}`CliRunner.invoke` is different. While a command runs it swaps several169pieces 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 back173Merge main into stable (#3800)Rowlando13before adoption420c8fb
lines 174–189why, one step back174```{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 back190```191192## Input Streams193Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e
lines 194–195why, one step back194The test wrapper can provide input data for the input stream (stdin). This is195very useful for testing prompts.Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1
lines 196–223why, one step back196197```{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 back224Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
line 225why, one step back225## Capture modesExpose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae
line 226why, one step back226Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
lines 227–229why, one step back227{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 back230Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
line 231why, one step back231### `capture="sys"` (default)Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae
line 232why, one step back232Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
lines 233–234why, one step back233Captures 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 back235Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
lines 236–238why, one step back236Code that holds a reference to the original `sys.stdout` (like a library that237does `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 back239Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
lines 240–243why, one step back240In this mode `sys.stdout.fileno()` and `sys.stderr.fileno()` raise241{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 back244Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
line 245why, one step back245### `capture="fd"`Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae
line 246why, one step back246Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
lines 247–250why, one step back247Redirects OS file descriptors `1` and `2` to a temporary file via248{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 back251Add capture mode to `CliRunner` and revert default `fileno` exposure (#3391)Rowlando13before adoptiond959898
lines 252–282why, one step back252- 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 back283```