click_extra.test_suite module¶

        classDiagram
  Exception <|-- SkippedTest
    

Declarative, black-box CLI test suites.

A test suite is a list of CLITestCase invocations: each runs a target command (a name, a command line, or a path to a binary) once with extra parameters, then checks its exit code and stdout/stderr against literal, substring, or regex expectations. Cases carry their own platform skip/only rules, so one suite runs across operating systems unchanged.

Suites are written in any list-capable configuration format and loaded with load_test_suite() (which picks the format from the file extension) or parse_test_suite() (which parses a serialized string). TOML, JSON and JSONC are built in; YAML and the other SUITE_FORMATS need their matching click-extra[…] extra. run_test_suite() drives a list of cases against a target, parallelized per the resolved --jobs count (see click_extra.jobs.run_jobs()) and reporting live progress through a click_extra.spinner.Spinner.

This is the black-box, subprocess-level complement to click_extra.testing.CliRunner, which drives a CLI in-process.

Todo

Import NestedReferences from the root of extra_platforms, in place of the private extra_platforms._types._TNestedReferences, once extra-platforms 15.0.0 ships on PyPI and the floor of that dependency moves to >=15. extra-platforms 16.0.0 removes the private alias.

click_extra.test_suite.SUITE_FORMATS: tuple[ConfigFormat, ...] = (ConfigFormat.TOML, ConfigFormat.JSON, ConfigFormat.JSONC, ConfigFormat.YAML, ConfigFormat.JSON5, ConfigFormat.HJSON)¶

Configuration formats a test suite can be serialized in, built-in ones first.

These are the formats able to represent a top-level list of case mappings, matched against a file’s extension by load_test_suite(). TOML, JSON and JSONC parse with no extra dependency; the others each need their matching click-extra[…] extra. TOML has no bare top-level array, so a TOML suite lists its cases under a [[cases]] array of tables (see parse_test_suite()); the others use a bare list. INI (no nesting) and XML (no natural list representation) are excluded.

Per-format availability is resolved by ConfigFormat, so a format whose parser is not installed raises an ImportError pointing at its extra at parse time.

exception click_extra.test_suite.SkippedTest[source]¶

Bases: Exception

Raised when a test case should be skipped.

class click_extra.test_suite.CLITestCase(cli_parameters=tuple(), env=dict(), unset_env=tuple(), skip_platforms=tuple(), only_platforms=tuple(), timeout=None, exit_code=None, strip_ansi=False, output_contains=tuple(), stdout_contains=tuple(), stderr_contains=tuple(), output_regex_matches=tuple(), stdout_regex_matches=tuple(), stderr_regex_matches=tuple(), output_regex_fullmatch=None, stdout_regex_fullmatch=None, stderr_regex_fullmatch=None)[source]¶

Bases: object

A single CLI test case: how to invoke the command and what to expect.

Each case runs the command-under-test once with cli_parameters appended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plus exit_code, if set).

cli_parameters: tuple[str, ...] | str¶

Arguments and options appended to the command-under-test.

A plain string is split into arguments the way the platform’s own parser does, quoted runs kept whole: shlex on POSIX, CommandLineToArgvW on Windows. A list or tuple is used as-is.

env: dict[str, str]¶

Environment variables set on the command, over the inherited environment.

The second input surface of a CLI, and the only way to reach a variable-only feature from a suite: an option can be typed as a cli_parameters flag, a variable cannot. Values must be strings, so a number or a boolean is quoted ("1", not 1): an environment holds strings only, and coercing would have to pick between True and true on the author’s behalf.

Applied to that one child process, never to the suite runner’s own environment, so cases stay independent under --jobs. See unset_env to take a variable away instead.

unset_env: tuple[str, ...] | str¶

Environment variables removed from the inherited environment.

The half env cannot express. Assigning the empty string leaves a variable set, and a flag read by bare presence (like ACCESSIBLE or DO_NOT_TRACK) counts that as activation, so hiding one from the command means removing it. This is what keeps a case from answering to whatever the shell running the suite happens to export.

A separate directive rather than a null value in env because TOML has no null literal, and a suite is as likely to be written in TOML as in YAML. Removing a variable that is not set is a no-op.

skip_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶

Platforms (or platform-group IDs) on which to skip this case.

Accepts extra_platforms identifiers such as linux, macos, windows, in any case, mixed freely with group IDs.

only_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]¶

Restrict this case to these platforms; skip it everywhere else.

The mirror image of skip_platforms, using the same identifiers.

timeout: float | str | None = None¶

Seconds before the command is killed and the case fails as a timeout.

Falls back to the command’s --timeout default, then to no limit.

exit_code: int | str | None = None¶

Expected process exit code; the case fails on any other code.

strip_ansi: bool = False¶

Strip ANSI escape sequences from the captured output before matching.

output_contains: tuple[str, ...] | str¶

Substrings that must all be present in the combined output.

The combined output interleaves stdout and stderr in the order the command wrote them, matching what a user sees in a terminal. The output_* directives are mutually exclusive with the stdout_* / stderr_* ones: a single subprocess run captures either the merged stream or the separate ones, not both.

stdout_contains: tuple[str, ...] | str¶

Substrings that must all be present in stdout.

stderr_contains: tuple[str, ...] | str¶

Substrings that must all be present in stderr.

output_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in the combined output (searched, re.DOTALL). See output_contains for the merged-stream semantics.

stdout_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in stdout (searched, re.DOTALL).

stderr_regex_matches: tuple[Pattern | str, ...] | str¶

Regexes that must each match somewhere in stderr (searched, re.DOTALL).

output_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match the combined output, line by line. See output_contains for the merged-stream semantics.

stdout_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match stdout, line by line.

stderr_regex_fullmatch: Pattern | str | None = None¶

Regex that must fully match stderr, line by line.

execution_trace: str | None = None¶

Rendering of the command execution and its output.

Populated after the case runs, for inspection on failure. Not a directive: a suite cannot set it, and two cases compare the same whether they ran or not.

property has_merged_output_directives: bool¶

Whether any output_* directive (merged stream) is set.

property has_separate_stream_directives: bool¶

Whether any stdout_* or stderr_* directive (separate streams) is set.

run_cli_test(command, additional_skip_platforms, default_timeout, work_directory=None)[source]¶

Run a CLI command and check its output against the test case.

The provided command can be either:

  • a path to a binary or script to execute;

  • a command name to be searched in the PATH,

  • a command line with arguments to be parsed and executed by the shell.

The case’s env and unset_env directives are layered over the inherited environment for this child process only.

work_directory is the directory the command runs in, defaulting to the one the runner itself is in. command is resolved to an absolute path before it takes effect, so moving the target elsewhere never changes which binary is executed, only what a relative path inside the command resolves against.

Return type:

None

click_extra.test_suite.cases_from_data(data)[source]¶

Build CLITestCase instances from already-parsed suite data.

The in-memory counterpart to parse_test_suite() (which parses a string) and load_test_suite() (which reads a file): feed it a suite that is already a Python object, such as the native cases mappings declared in a [tool.<cli>.test-suite] config section.

A suite is a list of case mappings, each keyed by CLITestCase directive names. Formats with no bare top-level array (TOML) carry that list under a top-level cases key, so a mapping is unwrapped here.

Raises:
  • ValueError – the suite is empty, a mapping suite omits cases, or a case uses unknown directives.

  • TypeError – the suite is not a list, or a case is not a mapping.

Return type:

Generator[CLITestCase, None, None]

click_extra.test_suite.parse_test_suite(suite_string, fmt=ConfigFormat.YAML)[source]¶

Parse a serialized test suite string into CLITestCase instances.

fmt selects the serialization format, one of SUITE_FORMATS; it defaults to YAML for string sources with no extension to key on, such as an environment variable. load_test_suite() is the file-based counterpart.

Raises:
  • ValueError – the suite is empty, fmt cannot express a suite, a mapping suite omits cases, or a case uses unknown directives.

  • TypeError – the suite is not a list, or a case is not a mapping.

  • ImportError – the format’s optional parser is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.test_suite.load_test_suite(path)[source]¶

Read a test suite file and parse it by the format of its extension.

The format is resolved from path’s name over the list-capable SUITE_FORMATS (so suite.toml parses as TOML, suite.yaml as YAML). Reading and format detection are delegated to click_extra.config.formats.read_file().

Raises:
  • ValueError – the file extension matches no suite format.

  • ImportError – the matched format’s optional parser is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.test_suite.run_test_suite(command, cases, *, jobs=1, select_test=None, skip_platform=None, timeout=None, work_directory=None, exit_on_error=False, show_trace_on_error=True, stats=True, show_progress=True)[source]¶

Run a list of test cases against a target command and tally the results.

Cases are parallelized per jobs (see click_extra.jobs.run_jobs()): at one worker they run sequentially and lazily, so exit_on_error can stop before the rest start; otherwise they run in a thread pool and every case runs to completion. Either way outcomes are tallied in submission order. On an interactive terminal a click_extra.spinner.Spinner reports progress unless show_progress is false.

Parameters:
  • command (Path | str) – The target to test: a command name, a command line, or a path to a binary or script.

  • cases (Sequence[CLITestCase]) – The test cases to run.

  • jobs (int) – Number of parallel workers; 1 runs sequentially.

  • select_test (Sequence[int] | None) – 1-based case numbers to run; others are skipped.

  • skip_platform (Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]]]) – Extra platforms (or group IDs) to skip every case on.

  • timeout (float | None) – Default per-case timeout in seconds when a case sets none.

  • work_directory (Path | str | None) – Directory every case runs its command in, defaulting to the runner’s own. It moves the target, never the runner: the suite file is read before any case starts, and command is resolved to an absolute path first, so neither is looked up relative to it.

  • exit_on_error (bool) – Stop at the first failure (sequential runs only).

  • show_trace_on_error (bool) – Echo the execution trace of each failed case.

  • stats (bool) – Echo a one-line worker summary up front and a result tally.

  • show_progress (bool) – Allow the progress spinner on an interactive terminal.

Return type:

Counter

Returns:

A collections.Counter with total, skipped, and failed keys. A non-zero failed count signals the caller to exit with an error.