Skip to content
Myr

testing.md

This file

Path

docs/testing.md

253 lines · 6.1 KiB · Markdown

Last changed by

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

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

lines 206–253why, one step back
206
207## File Descriptors and Low-Level I/O208209{class}`CliRunner` captures output by replacing210`sys.stdout` and `sys.stderr` with in-memory211{class}`~io.BytesIO`-backed wrappers. This is212Python-level redirection: calls to {func}`~click.echo`,213{func}`print`, or `sys.stdout.write()` are captured, but214the wrappers have no OS-level file descriptor.215216Code that calls `fileno()` on `sys.stdout` or217`sys.stderr`, like {mod}`faulthandler`,218{mod}`subprocess`, or C extensions, would normally crash219with {exc}`io.UnsupportedOperation` inside220{class}`CliRunner`.221222To avoid this, {class}`CliRunner` preserves the original223stream's file descriptor and exposes it via `fileno()` on224the replacement wrapper.225226This means:227- **Python-level writes** (`print()`, `click.echo()`,228 ...) are captured as usual.229- **fd-level writes** (C code writing directly to the230 file descriptor) go to the original terminal and are231 **not** captured.232233This is the same trade-off that234[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)235makes with its two capture modes:236237- `capsys`, which captures Python-level output, where238 `fileno()` raises `UnsupportedOperation` and fd-level239 writes are not captured.240- `capfd`, which captures fd-level output via241 `os.dup2()`, where `fileno()` works and fd-level242 writes *are* captured.243244Rather than implementing a full `capfd`-style mechanism,245{class}`CliRunner` takes the simpler path: expose the246original `fd` so that standard library helpers keep247working, while accepting that their output is not248captured.249250```{versionchanged} 8.3.3251`fileno()` on the redirected streams now returns the252original stream's file descriptor instead of raising.253```