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 matchingclick-extra[…]extra. TOML has no bare top-level array, so a TOML suite lists its cases under a[[cases]]array of tables (seeparse_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 anImportErrorpointing at its extra at parse time.
- exception click_extra.test_suite.SkippedTest[source]¶
Bases:
ExceptionRaised 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:
objectA single CLI test case: how to invoke the command and what to expect.
Each case runs the command-under-test once with
cli_parametersappended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plusexit_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:
shlexon POSIX,CommandLineToArgvWon 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_parametersflag, a variable cannot. Values must be strings, so a number or a boolean is quoted ("1", not1): an environment holds strings only, and coercing would have to pick betweenTrueandtrueon the author’s behalf.Applied to that one child process, never to the suite runner’s own environment, so cases stay independent under
--jobs. Seeunset_envto take a variable away instead.
- unset_env: tuple[str, ...] | str¶
Environment variables removed from the inherited environment.
The half
envcannot express. Assigning the empty string leaves a variable set, and a flag read by bare presence (likeACCESSIBLEorDO_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
nullvalue inenvbecause 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_platformsidentifiers such aslinux,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
--timeoutdefault, then to no limit.
- 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 thestdout_*/stderr_*ones: a single subprocess run captures either the merged stream or the separate ones, not both.
- output_regex_matches: tuple[Pattern | str, ...] | str¶
Regexes that must each match somewhere in the combined output (searched,
re.DOTALL). Seeoutput_containsfor 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_containsfor 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_*orstderr_*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
commandcan 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
envandunset_envdirectives are layered over the inherited environment for this child process only.work_directoryis the directory the command runs in, defaulting to the one the runner itself is in.commandis 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:
- click_extra.test_suite.cases_from_data(data)[source]¶
Build
CLITestCaseinstances from already-parsed suite data.The in-memory counterpart to
parse_test_suite()(which parses a string) andload_test_suite()(which reads a file): feed it a suite that is already a Python object, such as the nativecasesmappings declared in a[tool.<cli>.test-suite]config section.A suite is a list of case mappings, each keyed by
CLITestCasedirective names. Formats with no bare top-level array (TOML) carry that list under a top-levelcaseskey, 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:
- click_extra.test_suite.parse_test_suite(suite_string, fmt=ConfigFormat.YAML)[source]¶
Parse a serialized test suite string into
CLITestCaseinstances.fmtselects the serialization format, one ofSUITE_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,
fmtcannot express a suite, a mapping suite omitscases, 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:
- 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-capableSUITE_FORMATS(sosuite.tomlparses as TOML,suite.yamlas YAML). Reading and format detection are delegated toclick_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:
- 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(seeclick_extra.jobs.run_jobs()): at one worker they run sequentially and lazily, soexit_on_errorcan 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 aclick_extra.spinner.Spinnerreports progress unlessshow_progressis 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;1runs 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, andcommandis 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:
- Returns:
A
collections.Counterwithtotal,skipped, andfailedkeys. A non-zerofailedcount signals the caller to exit with an error.