click_extra.testing module¶

        classDiagram
  AssertionError <|-- RegexLineMismatch
  CliRunner <|-- CliRunner
  Result <|-- Result
    

CLI testing and simulation of their execution.

click_extra.testing.OUTPUT_LABEL = '<output>'¶

Label for the merged stream, where stdout and stderr are interleaved.

click_extra.testing.STDOUT_LABEL = '<stdout>'¶

Label for the standard output stream.

click_extra.testing.STDERR_LABEL = '<stderr>'¶

Label for the standard error stream.

click_extra.testing.EXIT_CODE_LABEL = '<exit_code>'¶

Label for the process exit code.

click_extra.testing.REGEX_NEWLINE = '\\n'¶

Newline token used to split a multi-line regex pattern for line-by-line matching.

click_extra.testing.INVOKE_ARGS = {'args', 'catch_exceptions', 'cli', 'color', 'env', 'input', 'self'}¶

Parameter names of click.testing.CliRunner.invoke().

An extra keyword of CliRunner.invoke() named like one of them collides with Click’s own parameter, and reaches Context through a patched Command.main() call instead (pallets/click#2110).

Todo

pallets/click#3896 adds a context_settings parameter to click.testing.CliRunner.invoke(). It sets the context color without the Command.main() patch in invoke().

On a Click release that carries it, this constant also catches context_settings, and the patch sends it to Context, which rejects it. On such a release, keep context_settings out of the collision set and pass force_color through it. Drop this constant and the patch once the Click floor of this package reaches that release.

click_extra.testing.STREAM_FIELDS = {'output_': ('<output>', 'output'), 'stderr_': ('<stderr>', 'stderr'), 'stdout_': ('<stdout>', 'stdout')}¶

Maps a test-case field prefix to its stream label and StreamView attribute.

output_* directives target the merged stream; stdout_* and stderr_* target the separate streams. Both render_cli_run() and click_extra.test_suite.CLITestCase.run_cli_test() read this single table so the rendered trace and the assertion loop agree on labels and stream selection.

class click_extra.testing.StreamView(stdout='', stderr='', output='', exit_code=None)[source]¶

Bases: object

Normalized view of a CLI run’s captured streams and exit code.

Both runners produce one of these so the renderer and the assertion loop read a single shape, regardless of whether the run was driven in-process (Click’s click.testing.Result) or as a black-box subprocess (subprocess.CompletedProcess).

A run captures either the merged stream (output) or the separate stdout and stderr streams, never both: the unused fields stay empty.

stdout: str = ''¶

Captured standard output, or empty when the merged stream was captured.

stderr: str = ''¶

Captured standard error, or empty when the merged stream was captured.

output: str = ''¶

Captured merged stream (stdout and stderr interleaved), or empty when the separate streams were captured.

exit_code: int | None = None¶

Process exit code, or None when unavailable.

classmethod from_result(result)[source]¶

Build a view from an in-process click.testing.Result.

Click always exposes stdout, stderr and the interleaved output together, so all three are carried over verbatim.

Return type:

StreamView

classmethod from_completed_process(result)[source]¶

Build a view from a black-box subprocess.CompletedProcess.

A subprocess run with stderr merged into stdout (stderr=STDOUT) reports result.stderr as None: that case is rendered as the interleaved output stream. Otherwise the two streams are kept separate.

Return type:

StreamView

click_extra.testing.render_cli_run(args, result, env=None)[source]¶

Render the full simulation of a CLI execution, output included.

CliRunner.invoke() prints it after every run, so a failing test shows the session that produced it.

Return type:

str

class click_extra.testing.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]¶

Bases: Result

A Result subclass with automatic traceback formatting.

Enhances __repr__ so that pytest assertion failures show the full traceback instead of just the exception type.

property formatted_exception: str | None[source]¶

Full formatted traceback, or None if no exception occurred.

click_extra.testing.isolated_filesystem(temp_dir=None)[source]¶

Create a temporary directory and change the working directory to it.

Replaces click.testing.CliRunner.isolated_filesystem(), which Click deprecates and removes in 9.0. Click points at tempfile.TemporaryDirectory and pytest’s tmp_path fixture, and neither replaces it: what isolates a CLI here is the working directory, which a command reads through relative paths and configuration-file globs. The runner pytest fixture and the click:run Sphinx directive both call this on every test and every documented example, where Click’s version would raise a deprecation warning each time.

Warning

The isolation is process-global, because it calls os.chdir(). Parallelize with processes, never with threads.

Parameters:

temp_dir (str | PathLike[str] | None) – create the temporary directory inside this one. When given, the directory is left in place on exit.

Return type:

Generator[str, None, None]

Returns:

path of the directory the working directory was changed to.

class click_extra.testing.CliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True, capture='sys')[source]¶

Bases: CliRunner

Augment click.testing.CliRunner with extra features and bug fixes.

force_color: bool = False¶

Default of the force_color argument of invoke(), for every run.

A call passing color=False still gets uncolored output.

invoke(cli, *args, input=None, env=None, catch_exceptions=None, color=None, force_color=None, **extra)[source]¶

Same as click.testing.CliRunner.invoke() with extra features.

  • The first positional parameter is the CLI to invoke. The remaining positional parameters of the function are the CLI arguments. All other parameters are required to be named.

  • The CLI arguments can be nested iterables of arbitrary depth. This is useful for argument composition of test cases with @pytest.mark.parametrize.

  • Adds force_color, which keeps colored output while initializing Context.color = True. click.testing.CliRunner.invoke() cannot express it, its color parameter colliding with the Context one (pallets/click#2110). The force_color class attribute sets it for every run.

  • Strips all ANSI codes from results if color was explicitly set to False.

  • Always prints a simulation of the CLI execution as the user would see it in its terminal. Including colors.

  • Pretty-prints a formatted exception traceback if the command fails.

Parameters:
  • cli (Command) – CLI to invoke.

  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – can be nested iterables composed of str, pathlib.Path objects and None values. The nested structure will be flattened and None values will be filtered out. Then all elements will be cast to str. See args_cleanup() for details.

  • input (str | bytes | IO | None) – same as click.testing.CliRunner.invoke().

  • env (Mapping[str, str | None] | None) – same as click.testing.CliRunner.invoke().

  • catch_exceptions (bool | None) – same as click.testing.CliRunner.invoke(): None (the default) follows the runner’s own catch_exceptions.

  • color (bool | None) – whether the captured streams keep ANSI codes, passed to click.testing.CliRunner.isolation(). False also scrubs the result bytes.

  • force_color (bool | None) – keep the ANSI codes and initialize the invoked CLI’s Context.color to True, so it takes its colored branch. None (the default) follows the force_color class attribute.

  • extra (Any) – same as click.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.

Raises:

ValueError – if force_color=True is passed with color=False.

Return type:

Result

isolated_filesystem(temp_dir=None)[source]¶

Same as isolated_filesystem(), minus Click’s deprecation warning.

Overrides click.testing.CliRunner.isolated_filesystem() so a runner keeps the helper once Click 9.0 removes it.

Return type:

Generator[str, None, None]

click_extra.testing.unescape_regex(text)[source]¶

De-obfuscate a regex for better readability.

This is like the reverse of re.escape().

Return type:

str

exception click_extra.testing.RegexLineMismatch(regex_line, content_line, line_number)[source]¶

Bases: AssertionError

Raised when a regex line does not match the corresponding content line.

click_extra.testing.regex_fullmatch_line_by_line(regex, content)[source]¶

Check that the content matches the given regex.

If the regex does not fully match the content, raise an AssertionError, with a message showing the first mismatching line.

This is useful when comparing large walls of text, such as CLI output.

Return type:

None