Skip to content
Myr

testing.md

This file

Path

docs/testing.md

198 lines · 4.5 KiB · Markdown

Last changed by

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

History of this file

Take it

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

lines 1–198why, one step back
1# Testing Click Applications
23```{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.