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 reachesContextthrough a patchedCommand.main()call instead (pallets/click#2110).Todo
pallets/click#3896 adds a
context_settingsparameter toclick.testing.CliRunner.invoke(). It sets the context color without theCommand.main()patch ininvoke().On a Click release that carries it, this constant also catches
context_settings, and the patch sends it toContext, which rejects it. On such a release, keepcontext_settingsout of the collision set and passforce_colorthrough 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
StreamViewattribute.output_*directives target the merged stream;stdout_*andstderr_*target the separate streams. Bothrender_cli_run()andclick_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:
objectNormalized 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 separatestdoutandstderrstreams, never both: the unused fields stay empty.- output: str = ''¶
Captured merged stream (stdout and stderr interleaved), or empty when the separate streams were captured.
- classmethod from_result(result)[source]¶
Build a view from an in-process
click.testing.Result.Click always exposes
stdout,stderrand the interleavedoutputtogether, so all three are carried over verbatim.- Return type:
- 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) reportsresult.stderrasNone: that case is rendered as the interleavedoutputstream. Otherwise the two streams are kept separate.- Return type:
- 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:
- class click_extra.testing.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]¶
Bases:
ResultA
Resultsubclass with automatic traceback formatting.Enhances
__repr__so that pytest assertion failures show the full traceback instead of just the exception type.
- 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 in9.0. Click points attempfile.TemporaryDirectoryand pytest’stmp_pathfixture, and neither replaces it: what isolates a CLI here is the working directory, which a command reads through relative paths and configuration-file globs. Therunnerpytest fixture and theclick:runSphinx 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.
- class click_extra.testing.CliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True, capture='sys')[source]¶
Bases:
CliRunnerAugment
click.testing.CliRunnerwith extra features and bug fixes.- force_color: bool = False¶
Default of the
force_colorargument ofinvoke(), for every run.A call passing
color=Falsestill 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 initializingContext.color = True.click.testing.CliRunner.invoke()cannot express it, itscolorparameter colliding with theContextone (pallets/click#2110). Theforce_colorclass attribute sets it for every run.Strips all ANSI codes from results if
colorwas explicitly set toFalse.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 ofstr,pathlib.Pathobjects andNonevalues. The nested structure will be flattened andNonevalues will be filtered out. Then all elements will be cast tostr. Seeargs_cleanup()for details.input (
str|bytes|IO|None) – same asclick.testing.CliRunner.invoke().env (
Mapping[str,str|None] |None) – same asclick.testing.CliRunner.invoke().catch_exceptions (
bool|None) – same asclick.testing.CliRunner.invoke():None(the default) follows the runner’s owncatch_exceptions.color (
bool|None) – whether the captured streams keep ANSI codes, passed toclick.testing.CliRunner.isolation().Falsealso scrubs the result bytes.force_color (
bool|None) – keep the ANSI codes and initialize the invoked CLI’sContext.colortoTrue, so it takes its colored branch.None(the default) follows theforce_colorclass attribute.extra (
Any) – same asclick.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.
- Raises:
ValueError – if
force_color=Trueis passed withcolor=False.- Return type:
- 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 Click9.0removes it.
- click_extra.testing.unescape_regex(text)[source]¶
De-obfuscate a regex for better readability.
This is like the reverse of
re.escape().- Return type:
- exception click_extra.testing.RegexLineMismatch(regex_line, content_line, line_number)[source]¶
Bases:
AssertionErrorRaised 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
contentmatches the givenregex.If the
regexdoes not fully match thecontent, raise anAssertionError, with a message showing the first mismatching line.This is useful when comparing large walls of text, such as CLI output.
- Return type: