testing.md
This file
Path
docs/testing.md
246 lines · 6.1 KiB · Markdown
Last changed by
Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae
History of this fileTake it
Rewrite testing docs and move from rst to myst (#2857)Rowlando13before adoption854cfb1
lines 1–198why, one step back1# Testing Click Applications23```{eval-rst}4.. currentmodule:: click.testing5```67Click provides the {ref}`click.testing <testing>` module to help you invoke command line applications and check their behavior.89These tools should only be used for testing since they change10the entire interpreter state for simplicity. They are not thread-safe!1112The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.1314```{contents}15:depth: 116:local: true17```1819## Basic Example2021The key pieces are:22 - {class}`CliRunner` - used to invoke commands as command line scripts.23 - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output data, exit code, optional exception, and captures the output as bytes and binary data.2425```{code-block} python26:caption: hello.py2728import click2930@click.command()31@click.argument('name')32def hello(name):33 click.echo(f'Hello {name}!')34```3536```{code-block} python37:caption: test_hello.py3839from click.testing import CliRunner40from hello import hello4142def test_hello_world():43 runner = CliRunner()44 result = runner.invoke(hello, ['Peter'])45 assert result.exit_code == 046 assert result.output == 'Hello Peter!\n'47```4849## Subcommands5051A subcommand name must be specified in the `args` parameter {meth}`CliRunner.invoke`:5253```{code-block} python54:caption: sync.py5556import click5758@click.group()59@click.option('--debug/--no-debug', default=False)60def cli(debug):61 click.echo(f"Debug mode is {'on' if debug else 'off'}")6263@cli.command()64def sync():65 click.echo('Syncing')66```6768```{code-block} python69:caption: test_sync.py7071from click.testing import CliRunner72from sync import cli7374def test_sync():75 runner = CliRunner()76 result = runner.invoke(cli, ['--debug', 'sync'])77 assert result.exit_code == 078 assert 'Debug mode is on' in result.output79 assert 'Syncing' in result.output80```8182## Context Settings8384Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to construct the initial {class}`Context object <click.Context>`.85For example, setting a fixed terminal width equal to 60:8687```{code-block} python88:caption: sync.py8990import click9192@click.group()93def cli():94 pass9596@cli.command()97def sync():98 click.echo('Syncing')99```100101```{code-block} python102:caption: test_sync.py103104from click.testing import CliRunner105from sync import cli106107def test_sync():108 runner = CliRunner()109 result = runner.invoke(cli, ['sync'], terminal_width=60)110 assert result.exit_code == 0111 assert 'Debug mode is on' in result.output112 assert 'Syncing' in result.output113```114115## File System Isolation116117The {meth}`CliRunner.isolated_filesystem` context manager sets the current working directory to a new, empty folder.118119```{code-block} python120:caption: cat.py121122import click123124@click.command()125@click.argument('f', type=click.File())126def cat(f):127 click.echo(f.read())128```129130```{code-block} python131:caption: test_cat.py132133from click.testing import CliRunner134from cat import cat135136def test_cat():137 runner = CliRunner()138 with runner.isolated_filesystem():139 with open('hello.txt', 'w') as f:140 f.write('Hello World!')141142 result = runner.invoke(cat, ['hello.txt'])143 assert result.exit_code == 0144 assert result.output == 'Hello World!\n'145```146147Pass in a path to control where the temporary directory is created.148In this case, the directory will not be removed by Click. Its useful149to integrate with a framework like Pytest that manages temporary files.150151```{code-block} python152:caption: test_cat.py153154from click.testing import CliRunner155from cat import cat156157def test_cat_with_path_specified():158 runner = CliRunner()159 with runner.isolated_filesystem('~/test_folder'):160 with open('hello.txt', 'w') as f:161 f.write('Hello World!')162163 result = runner.invoke(cat, ['hello.txt'])164 assert result.exit_code == 0165 assert result.output == 'Hello World!\n'166```167168## Input Streams169170The test wrapper can provide input data for the input stream (stdin). This is very useful for testing prompts.171172```{code-block} python173:caption: prompt.py174175import click176177@click.command()178@click.option('--foo', prompt=True)179def prompt(foo):180 click.echo(f"foo={foo}")181```182183```{code-block} python184:caption: test_prompt.py185186from click.testing import CliRunner187from prompt import prompt188189def test_prompts():190 runner = CliRunner()191 result = runner.invoke(prompt, input='wau wau\n')192 assert not result.exception193 assert result.output == 'Foo: wau wau\nfoo=wau wau\n'194```195196Prompts will be emulated so they write the input data to197the output stream as well. If hidden input is expected then this198does not happen.Expose original file descriptor in `CliRunner` (#3244)Rowlando13before adoption89af4ae
lines 199–246why, one step back199200## File Descriptors and Low-Level I/O201202{class}`CliRunner` captures output by replacing203`sys.stdout` and `sys.stderr` with in-memory204{class}`~io.BytesIO`-backed wrappers. This is205Python-level redirection: calls to {func}`~click.echo`,206{func}`print`, or `sys.stdout.write()` are captured, but207the wrappers have no OS-level file descriptor.208209Code that calls `fileno()` on `sys.stdout` or210`sys.stderr`, like {mod}`faulthandler`,211{mod}`subprocess`, or C extensions, would normally crash212with {exc}`io.UnsupportedOperation` inside213{class}`CliRunner`.214215To avoid this, {class}`CliRunner` preserves the original216stream's file descriptor and exposes it via `fileno()` on217the replacement wrapper.218219This means:220- **Python-level writes** (`print()`, `click.echo()`,221 ...) are captured as usual.222- **fd-level writes** (C code writing directly to the223 file descriptor) go to the original terminal and are224 **not** captured.225226This is the same trade-off that227[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)228makes with its two capture modes:229230- `capsys`, which captures Python-level output, where231 `fileno()` raises `UnsupportedOperation` and fd-level232 writes are not captured.233- `capfd`, which captures fd-level output via234 `os.dup2()`, where `fileno()` works and fd-level235 writes *are* captured.236237Rather than implementing a full `capfd`-style mechanism,238{class}`CliRunner` takes the simpler path: expose the239original `fd` so that standard library helpers keep240working, while accepting that their output is not241captured.242243```{versionchanged} 8.3.3244`fileno()` on the redirected streams now returns the245original stream's file descriptor instead of raising.246```