Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(cli): support standalone and vendored Click in Typer (#2013)

Nurkhan Esenbekd95dfef60986
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2ab43982..4f17996b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -668,6 +668,8 @@ jobs:
pytest -o addopts= -q
tests/test_core_dependency_floors.py
tests/test_cli_dependency_floors.py
+ tests/test_typer_click_compat.py
+ tests/test_cli_runner.py
tests/test_click_argument_help.py
tests/test_cli_startup_is_light.py
tests/test_cli.py
@@ -772,6 +774,61 @@ jobs:
tests/test_cli_dependency_floors.py
tests/test_click_argument_help.py
tests/test_cli_startup_is_light.py
+ tests/test_typer_click_compat.py
+ tests/test_cli_help_completeness.py
+ tests/test_cli_help_markup.py
+ tests/test_gen_reference_docs.py
+ tests/test_cli_runner.py
+
+ typer-vendored:
+ needs: plan
+ if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
+ # Keep the pinned vendored probe off PR/release runs to preserve CI capacity.
+ # Exercise these identities nightly/manually without upgrading either floor.
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - name: Install pinned vendored Typer compatibility lane
+ run: python -m pip install -e . "pytest>=7,<9" "typer==0.27.3" "click==8.4.2"
+ - name: Verify pinned vendored identities and compatibility scenarios
+ env:
+ PYTEST_DISABLE_PLUGIN_AUTOLOAD: "1"
+ HF_HUB_OFFLINE: "1"
+ TRANSFORMERS_OFFLINE: "1"
+ run: |
+ python - <<'PY'
+ import json
+ from importlib.metadata import version
+ import click
+ from typer._click.core import Command, Context, ParameterSource
+ from typer._click.exceptions import MissingParameter, UsageError
+ from typer.core import TyperGroup
+ from typer.main import get_command
+ from soup_cli.cli import app
+ from soup_cli.utils import typer_compat
+
+ installed = {name: version(name) for name in ("typer", "click")}
+ assert installed == {"typer": "0.27.3", "click": "8.4.2"}, installed
+ assert TyperGroup.__bases__[0] is Command
+ root = get_command(app)
+ assert isinstance(root, Command) and not isinstance(root, click.Command)
+ assert typer_compat.UsageError is UsageError and UsageError is not click.UsageError
+ assert typer_compat.MissingParameter is MissingParameter
+ assert MissingParameter is not click.MissingParameter
+ assert typer_compat.ParameterSource is ParameterSource
+ assert ParameterSource is not click.core.ParameterSource
+ with root.commands["ship"].make_context("ship", []) as context:
+ assert isinstance(context, Context)
+ assert context.get_parameter_source("forgetting_threshold") is ParameterSource.DEFAULT
+ print(json.dumps({**installed, "command_base": Command.__module__,
+ "usage_error": UsageError.__module__,
+ "parameter_source": ParameterSource.__module__}, sort_keys=True))
+ PY
+ python -m pytest -o addopts= tests/test_typer_click_compat.py -q
test:
needs: plan
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e0396120..5133c5f7 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -508,6 +508,27 @@ Contributions are accepted under the Apache License, Version 2.0, the project's
## Architecture & Design Decisions
+### Typer and Click compatibility
+
+The supported Typer range spans releases using standalone Click and releases
+vendoring it. Resolve exception and parameter-source identities through
+`soup_cli.utils.typer_compat`; importing those objects from standalone `click`
+can silently stop matching the live command tree. Inspect command and parameter
+capabilities when traversing help or reference pages. Keep standalone Click
+declared while the minimum supported Typer requires it.
+
+The core and training floor jobs exercise Typer 0.15.4. The separate `typer-vendored`
+job installs a core-only environment pinned to Typer 0.27.3 / Click 8.4.2,
+records those versions, asserts the real command/exception/parameter-source
+identities use Typer's vendored Click, and runs the unchanged 20-case
+`tests/test_typer_click_compat.py`. This explicit lane runs only on `schedule`
+and `workflow_dispatch`, keeping it off pull-request and release-push runs;
+it does not replace the minimum-version environment.
+Typer is not pinned in the ordinary CI stack, so its test matrix resolves the
+newest release admitted by `pyproject.toml`. The compatibility regressions
+exercise gate exit codes, noninteractive missing options, configured defaults,
+explicit tokens, legacy bench routing and complete command-tree traversal.
+
### Lazy Imports for Speed
Heavy ML imports (torch, transformers, trl) are imported inside command handlers so the CLI stays fast. Users can run `soup version` or `soup --help` instantly without waiting for PyTorch to load.
diff --git a/changelog.d/0.76.0/2013.changed.md b/changelog.d/0.76.0/2013.changed.md
new file mode 100644
index 00000000..7fc26345
--- /dev/null
+++ b/changelog.d/0.76.0/2013.changed.md
@@ -0,0 +1 @@
+- Support Typer's standalone and vendored Click implementations while preserving CLI usage exit codes, option precedence, filesystem isolation and complete help/reference traversal; admit Typer through 0.27.x while retaining the standalone Click dependency for older supported releases. (#1803 by @kok-o in #2013)
diff --git a/pyproject.toml b/pyproject.toml
index 964c18c1..7fe802af 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -47,12 +47,15 @@ dependencies = [
# job installs exactly this Typer floor and the Click floor below
# (.github/constraints/transformers-floor.txt) and starts the CLI on them. Move a
# floor and its pin together; that test file refuses one without the other.
- "typer>=0.15.4,<0.21.0",
+ # Both standalone-Click and vendored-Click Typer are exercised by the floor
+ # job and the main test matrix (#1803). 0.27.3 is the validated newest release;
+ # the next minor is a fresh compatibility boundary.
+ "typer>=0.15.4,<0.28",
# click 8.5.0 drops every positional-argument description from `--help`
- # (its Argument.__init__ overwrites the help typer sets). Imported directly at
- # run time by commands/autopilot.py, commands/push.py, commands/ship.py and
- # utils/exit_codes.py (utils/argv_redaction.py names click for type checking
- # only), so declared here. `tests/test_click_argument_help.py` pins the bound.
+ # (its Argument.__init__ overwrites the help typer sets).
+ # Older supported Typer releases require standalone Click; newer ones vendor
+ # it. Keep the declaration and help bound while the floor uses standalone
+ # Click. `tests/test_click_argument_help.py` pins the bound.
"click>=8.0.0,<8.5",
"rich>=13.0.0",
"pydantic>=2.0.0",
diff --git a/scripts/gen_reference_docs.py b/scripts/gen_reference_docs.py
index 12ab7ac0..8e799dd8 100644
--- a/scripts/gen_reference_docs.py
+++ b/scripts/gen_reference_docs.py
@@ -679,7 +679,7 @@ def iter_commands(root: click.Command) -> list[CommandEntry]:
def walk(command: click.Command, path: tuple[str, ...]) -> None:
if path:
entries.append(CommandEntry(path, command))
- if isinstance(command, click.Group):
+ if _is_group(command):
for name in sorted(command.commands):
sub = command.commands[name]
if not getattr(sub, "hidden", False):
@@ -705,26 +705,37 @@ def _range_words(param_type: Any) -> str:
return ", ".join(parts)
+def _is_group(command: object) -> bool:
+ return isinstance(getattr(command, "commands", None), collections.abc.Mapping)
+
+
+def _is_option(parameter: object) -> bool:
+ return getattr(parameter, "param_type_name", None) == "option"
+
+
+def _is_argument(parameter: object) -> bool:
+ return getattr(parameter, "param_type_name", None) == "argument"
+
+
def _click_type_name(param_type: click.ParamType) -> str:
- if isinstance(param_type, click.Choice):
+ # These are parameter capabilities, shared by Click and Typer's own types.
+ # The script also accepts plain Click trees without importing Soup's CLI.
+ if hasattr(param_type, "choices"):
values = [str(getattr(choice, "value", choice)) for choice in param_type.choices]
return "one of " + ", ".join(_code(value) for value in values)
- if isinstance(param_type, (click.IntRange, click.FloatRange)):
- name = "integer" if isinstance(param_type, click.IntRange) else "float"
- return ", ".join(part for part in (name, _range_words(param_type)) if part)
- if isinstance(param_type, click.types.IntParamType):
- return "integer"
- if isinstance(param_type, click.types.FloatParamType):
- return "float"
- if isinstance(param_type, click.types.BoolParamType):
- return "boolean"
- if isinstance(param_type, click.Path):
- return "path"
- if isinstance(param_type, click.File):
- return "file"
- if isinstance(param_type, click.DateTime):
- return "datetime"
- return "text"
+ name = getattr(param_type, "name", "")
+ if name in ("integer range", "int range", "float range"):
+ kind = "float" if name == "float range" else "integer"
+ return ", ".join(part for part in (kind, _range_words(param_type)) if part)
+ return {
+ "integer": "integer",
+ "int": "integer",
+ "float": "float",
+ "boolean": "boolean",
+ "path": "path",
+ "filename": "file",
+ "datetime": "datetime",
+ }.get(name, "text")
def format_click_type(param: click.Parameter) -> str:
@@ -766,7 +777,7 @@ def format_click_default(param: click.Parameter) -> str:
def _param_name(param: click.Parameter) -> str:
- if isinstance(param, click.Option):
+ if _is_option(param):
names = ", ".join(_code(opt) for opt in param.opts)
if param.secondary_opts:
names += " / " + ", ".join(_code(opt) for opt in param.secondary_opts)
@@ -839,21 +850,21 @@ def _param_rows(command: click.Command) -> list[str]:
def _usage(path: tuple[str, ...], command: click.Command) -> str:
params = _visible_params(command)
parts = ["soup", *path]
- if any(isinstance(param, click.Option) for param in params):
+ if any(_is_option(param) for param in params):
parts.append("[OPTIONS]")
- if isinstance(command, click.Group):
+ if _is_group(command):
# `<command>`, not Click's `COMMAND`: the docs guard that resolves every
# documented invocation (#1465) reads a bare capitalised word as a subcommand.
optional = bool(path) and command.invoke_without_command
parts.append("[<command>] [ARGS]..." if optional else "<command> [ARGS]...")
for param in params:
- if isinstance(param, click.Argument):
+ if _is_argument(param):
name = _argument_name(param)
name = name if param.required else f"[{name}]"
parts.append(f"{name}..." if param.nargs == -1 else name)
passes_extra = (command.context_settings or {}).get("allow_extra_args")
- variadic = any(isinstance(param, click.Argument) and param.nargs == -1 for param in params)
- if passes_extra and not variadic and not isinstance(command, click.Group):
+ variadic = any(_is_argument(param) and param.nargs == -1 for param in params)
+ if passes_extra and not variadic and not _is_group(command):
parts.append("[ARGS]...")
return " ".join(parts)
@@ -870,7 +881,7 @@ def _command_section(entry: CommandEntry, anchors: dict[tuple[str, ...], str]) -
if summary:
blocks.append([summary])
blocks.append([f"Usage: {_code(_usage(entry.path, command))}"])
- if isinstance(command, click.Group):
+ if _is_group(command):
subs = [
f"- [{_code(name)}](#{anchors[(*entry.path, name)]})"
for name in sorted(command.commands)
@@ -881,7 +892,7 @@ def _command_section(entry: CommandEntry, anchors: dict[tuple[str, ...], str]) -
rows = _param_rows(command)
if rows:
blocks.append([*_table_head("Name", "Type", "Default", "Required", "Help"), *rows])
- elif not isinstance(command, click.Group):
+ elif not _is_group(command):
blocks.append(["Takes no options or arguments."])
return [line for block in blocks for line in ("", *block)]
diff --git a/src/soup_cli/commands/autopilot.py b/src/soup_cli/commands/autopilot.py
index 63591548..56e24c04 100644
--- a/src/soup_cli/commands/autopilot.py
+++ b/src/soup_cli/commands/autopilot.py
@@ -7,7 +7,6 @@ import sys
from pathlib import Path
from typing import Optional
-import click
import typer
from rich.console import Console
from rich.panel import Panel
@@ -26,6 +25,7 @@ from soup_cli.autopilot.decisions import (
from soup_cli.autopilot.generate_config import build_soup_config, write_yaml
from soup_cli.config.schema import SFT_KERNEL_AWARE_TASKS
from soup_cli.utils.terminal import for_terminal
+from soup_cli.utils.typer_compat import MissingParameter
console = Console()
@@ -70,7 +70,7 @@ def _stdin_isatty() -> bool:
return sys.stdin.isatty()
-def _param_by_name(ctx: typer.Context, name: str) -> click.Parameter | None:
+def _param_by_name(ctx: typer.Context, name: str) -> object | None:
"""Find a Click Parameter on the command by its argument name."""
for param in ctx.command.params:
if param.name == name:
@@ -111,11 +111,11 @@ def autopilot_cmd(
"""Autopilot: give model+data+goal, Soup picks optimal hyperparameters."""
if not _stdin_isatty():
if model is None:
- raise click.MissingParameter(ctx=ctx, param=_param_by_name(ctx, "model"))
+ raise MissingParameter(ctx=ctx, param=_param_by_name(ctx, "model"))
if data is None:
- raise click.MissingParameter(ctx=ctx, param=_param_by_name(ctx, "data"))
+ raise MissingParameter(ctx=ctx, param=_param_by_name(ctx, "data"))
if goal is None:
- raise click.MissingParameter(ctx=ctx, param=_param_by_name(ctx, "goal"))
+ raise MissingParameter(ctx=ctx, param=_param_by_name(ctx, "goal"))
if model is None:
model = Prompt.ask("Base model (HF model id)")
diff --git a/src/soup_cli/commands/push.py b/src/soup_cli/commands/push.py
index 97833765..2540fdd4 100644
--- a/src/soup_cli/commands/push.py
+++ b/src/soup_cli/commands/push.py
@@ -145,13 +145,12 @@ def push(
hf_token: Optional[str] = None
hf_endpoint: Optional[str] = None
if hub_canonical != "hf":
- import click
-
from soup_cli.utils.hubs import hub_token_env_var, resolve_hub_token
+ from soup_cli.utils.typer_compat import ParameterSource
# --token also reads HF_TOKEN via envvar; only a value typed on the
# command line is meant for this hub.
- typed = ctx.get_parameter_source("token") == click.core.ParameterSource.COMMANDLINE
+ typed = ctx.get_parameter_source("token") == ParameterSource.COMMANDLINE
hub_token = resolve_hub_token(hub_canonical, token if typed else None)
if not hub_token:
env_var = hub_token_env_var(hub_canonical)
diff --git a/src/soup_cli/commands/ship.py b/src/soup_cli/commands/ship.py
index 4b3adbc8..9a196b4c 100644
--- a/src/soup_cli/commands/ship.py
+++ b/src/soup_cli/commands/ship.py
@@ -455,7 +455,7 @@ def _flag_is_default(ctx: typer.Context, name: str) -> bool:
make a flag config-overridable.
"""
try:
- from click.core import ParameterSource
+ from soup_cli.utils.typer_compat import ParameterSource
source = ctx.get_parameter_source(name)
except (ImportError, AttributeError): # pragma: no cover — defensive
diff --git a/src/soup_cli/utils/exit_codes.py b/src/soup_cli/utils/exit_codes.py
index bd0d2bc6..5e4b02fc 100644
--- a/src/soup_cli/utils/exit_codes.py
+++ b/src/soup_cli/utils/exit_codes.py
@@ -11,15 +11,16 @@ Taxonomy (project-wide standard):
from __future__ import annotations
-import click.exceptions
import typer.core
+from soup_cli.utils.typer_compat import UsageError
+
EXIT_OK: int = 0
EXIT_RUNTIME_ERROR: int = 1
EXIT_GATE_FAILED: int = 2
EXIT_USAGE_ERROR: int = 3
-_USAGE_ERRORS: tuple[type[Exception], ...] = (click.exceptions.UsageError,)
+_USAGE_ERRORS: tuple[type[Exception], ...] = (UsageError,)
class _GateUsageErrorMixin:
diff --git a/src/soup_cli/utils/typer_compat.py b/src/soup_cli/utils/typer_compat.py
new file mode 100644
index 00000000..69f6c1a2
--- /dev/null
+++ b/src/soup_cli/utils/typer_compat.py
@@ -0,0 +1,36 @@
+"""The Click capabilities used by the installed Typer, without version checks.
+
+Typer may use standalone Click or its own copy. Their exceptions and enum
+members have different identities even when both packages are installed.
+Resolve the implementation from Typer's real command base, rather than
+assuming that ``import click`` describes the objects in our command tree.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from importlib import import_module
+
+from typer.core import TyperGroup
+
+_core = import_module(TyperGroup.__bases__[0].__module__)
+_exceptions = import_module(f"{_core.__package__}.exceptions")
+
+UsageError = _exceptions.UsageError
+MissingParameter = _exceptions.MissingParameter
+ParameterSource = _core.ParameterSource
+
+
+def is_group(command: object) -> bool:
+ """Whether a command exposes a subcommand mapping (Click or Typer)."""
+ return isinstance(getattr(command, "commands", None), Mapping)
+
+
+def is_option(parameter: object) -> bool:
+ """Whether a real CLI parameter declares itself an option."""
+ return getattr(parameter, "param_type_name", None) == "option"
+
+
+def is_argument(parameter: object) -> bool:
+ """Whether a real CLI parameter declares itself a positional argument."""
+ return getattr(parameter, "param_type_name", None) == "argument"
diff --git a/tests/cli_runner.py b/tests/cli_runner.py
new file mode 100644
index 00000000..3a0a8c91
--- /dev/null
+++ b/tests/cli_runner.py
@@ -0,0 +1,10 @@
+"""Typer's runner with Click's filesystem isolation across supported releases."""
+
+from click.testing import CliRunner as ClickCliRunner
+from typer.testing import CliRunner as TyperCliRunner
+
+
+class CliRunner(TyperCliRunner):
+ """Keep Typer's invocation; reuse Click's independent filesystem helper."""
+
+ isolated_filesystem = ClickCliRunner.isolated_filesystem
diff --git a/tests/test_audit_log_option_masking.py b/tests/test_audit_log_option_masking.py
index 427a1070..fb9d3d70 100644
--- a/tests/test_audit_log_option_masking.py
+++ b/tests/test_audit_log_option_masking.py
@@ -4,10 +4,11 @@ from __future__ import annotations
import json
-import click
import pytest
import typer
+from soup_cli.utils.typer_compat import is_group, is_option
+
@pytest.fixture
def audit_path(tmp_path, monkeypatch):
@@ -91,7 +92,7 @@ def test_mask_secret_args_forms():
def _all_commands(cmd, path=()):
yield path, cmd
- if isinstance(cmd, click.Group):
+ if is_group(cmd):
for name, sub in cmd.commands.items():
yield from _all_commands(sub, path + (name,))
@@ -105,7 +106,7 @@ def test_every_secret_looking_option_is_masked(audit_path):
checked = 0
for path, cmd in _all_commands(root):
for param in getattr(cmd, "params", []):
- if not isinstance(param, click.Option) or param.is_flag:
+ if not is_option(param) or param.is_flag:
continue
longs = [o for o in param.opts if o.startswith("--")]
if not any(SECRET_NAME_RE.search(o[2:]) for o in longs):
@@ -129,7 +130,7 @@ def test_not_secret_list_only_names_real_options():
o
for _path, cmd in _all_commands(root)
for p in getattr(cmd, "params", [])
- if isinstance(p, click.Option)
+ if is_option(p)
for o in p.opts
}
assert NOT_SECRET_OPTIONS <= names, NOT_SECRET_OPTIONS - names
diff --git a/tests/test_awq_gptq_export.py b/tests/test_awq_gptq_export.py
index bf3bd126..ad7f4016 100644
--- a/tests/test_awq_gptq_export.py
+++ b/tests/test_awq_gptq_export.py
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
import pytest
-from click.exceptions import Exit as ClickExit
+from typer import Exit as ClickExit
from soup_cli.commands.export import SUPPORTED_FORMATS
diff --git a/tests/test_ci_full_matrix_on_approval.py b/tests/test_ci_full_matrix_on_approval.py
index 65b9f5e0..7efe67d9 100644
--- a/tests/test_ci_full_matrix_on_approval.py
+++ b/tests/test_ci_full_matrix_on_approval.py
@@ -79,6 +79,7 @@ GATED_JOBS = (
"transformers-floor",
"core-floor",
)
+NIGHTLY_JOBS = ("typer-vendored",)
#: The two gated jobs that are not required checks and never fail the build: they run in the
#: nightly, manual and release runs but not on a pull request, approval run included
#: (2026-10-19: 206 pull-request runs in 7 days, 480 job-minutes, for a signal that is not a
@@ -694,8 +695,19 @@ class TestGatedJobs:
assert "needs" not in lint
def test_every_job_is_classified(self):
- """A new job must be declared quick or full here, or it lands on every PR push."""
- assert sorted(_jobs()) == sorted(["plan", "lint", "test", *GATED_JOBS])
+ """Classify quick, approval and nightly jobs so none lands on every PR push."""
+ assert sorted(_jobs()) == sorted(["plan", "lint", "test", *GATED_JOBS, *NIGHTLY_JOBS])
+
+ @pytest.mark.parametrize(("context", "kind"), EVENTS)
+ def test_vendored_lane_runs_only_on_nightly_and_manual(self, context, kind):
+ job = _jobs()["typer-vendored"]
+ assert "plan" in _needs(job)
+ context = {
+ **context,
+ "needs": {"plan": {"outputs": {"full": "false" if kind == "QUICK" else "true"}}},
+ }
+ # FULL is schedule/dispatch; APPROVAL and RELEASE must not add this job.
+ assert _runs("typer-vendored", context) == (kind == "FULL")
class TestMatrix:
@@ -1093,7 +1105,7 @@ class TestPinnedUpstream:
"""A new job that installs `.[dev]` on its own resolves the newest release on
every pull request, which is the failure this switch removed."""
installing = {name for name, job in _jobs().items() if _project_installs(job)}
- assert installing == {*SWITCHED_JOBS, FLOOR_JOB, "core-floor"}
+ assert installing == {*SWITCHED_JOBS, FLOOR_JOB, "core-floor", "typer-vendored"}
def test_no_environment_variable_constrains_a_job_behind_its_command_line(self):
"""`PIP_CONSTRAINT` in an `env:` applies to every pip of that job on every run,
@@ -1152,6 +1164,8 @@ UNPINNED_ON_PURPOSE = {
# CORE: the project with no extra, so no torch and no transformers to pin.
# Its separate core-floor constraints are checked by test_core_dependency_floors.py.
(CI.name, "core-floor"): CORE,
+ # Dedicated core-only lane with exact Typer/Click pins, asserted at runtime.
+ (CI.name, "typer-vendored"): CORE,
("codspeed.yml", "benchmark"): CORE,
# NEWEST: started by a schedule or by hand, never by a pull request or a push, and
# there to meet the newest release.
diff --git a/tests/test_cli_dependency_floors.py b/tests/test_cli_dependency_floors.py
index c379bec6..88733ae8 100644
--- a/tests/test_cli_dependency_floors.py
+++ b/tests/test_cli_dependency_floors.py
@@ -92,6 +92,7 @@ CLI_TESTS = (
"tests/test_cli_dependency_floors.py",
"tests/test_click_argument_help.py",
"tests/test_cli_startup_is_light.py",
+ "tests/test_typer_click_compat.py",
)
@@ -192,9 +193,9 @@ def _command_paths(root: click.Command) -> list[list[str]]:
for name in command.list_commands(ctx):
child = command.get_command(ctx, name)
assert child is not None, f"`{' '.join([*path, name])}` is listed but missing"
- visit(child, click.Context(child, info_name=name, parent=ctx), [*path, name])
+ visit(child, child.context_class(child, info_name=name, parent=ctx), [*path, name])
- visit(root, click.Context(root, info_name="soup"), [])
+ visit(root, root.context_class(root, info_name="soup"), [])
return paths
diff --git a/tests/test_cli_help_completeness.py b/tests/test_cli_help_completeness.py
index 2ac1bb86..df699d4d 100644
--- a/tests/test_cli_help_completeness.py
+++ b/tests/test_cli_help_completeness.py
@@ -7,6 +7,7 @@ import click
import typer
from soup_cli.cli import app
+from soup_cli.utils.typer_compat import is_argument, is_group
def _visible_commands(
@@ -16,7 +17,7 @@ def _visible_commands(
if getattr(command, "hidden", False):
return
yield path, command
- if isinstance(command, click.Group):
+ if is_group(command):
for name, child in command.commands.items():
yield from _visible_commands(child, path + (name,))
@@ -25,7 +26,7 @@ def _parameter_help(command: click.Command, parameter: click.Parameter) -> str |
"""Return help from Click or the Typer declaration behind an argument."""
if parameter.help:
return parameter.help
- if not isinstance(parameter, click.Argument) or command.callback is None:
+ if not is_argument(parameter) or command.callback is None:
return parameter.help
callback_parameter = inspect.signature(command.callback).parameters.get(
diff --git a/tests/test_cli_help_markup.py b/tests/test_cli_help_markup.py
index 5409061f..6186870e 100644
--- a/tests/test_cli_help_markup.py
+++ b/tests/test_cli_help_markup.py
@@ -24,6 +24,7 @@ from rich.text import Text
from typer.testing import CliRunner
from soup_cli.cli import app
+from soup_cli.utils.typer_compat import is_group
_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
_BOX_RE = re.compile(r"[─-╿│╭╮╰╯]")
@@ -93,7 +94,7 @@ def _iter_cli_help_strings(
except (ValueError, TypeError):
pass
- if isinstance(cmd, click.Group):
+ if is_group(cmd):
for sub_name, sub_cmd in cmd.commands.items():
yield from _iter_cli_help_strings(sub_cmd, f"{path} {sub_name}")
diff --git a/tests/test_cli_runner.py b/tests/test_cli_runner.py
new file mode 100644
index 00000000..e74e55fa
--- /dev/null
+++ b/tests/test_cli_runner.py
@@ -0,0 +1,73 @@
+"""Keep Typer invocation and Click's filesystem lifecycle in the shared runner."""
+
+from __future__ import annotations
+
+import os
+import tempfile
+from contextlib import nullcontext
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner as TyperCliRunner
+
+from soup_cli import __version__
+from soup_cli.cli import app
+from tests.cli_runner import CliRunner
+from tests.conftest import strip_ansi
+
+
[email protected]("force_color", [False, True])
+def test_invoke_is_the_installed_typer_implementation(force_color: bool) -> None:
+ assert CliRunner.invoke is TyperCliRunner.invoke
+ result = CliRunner().invoke(
+ app, ["version"], color=force_color, env={"FORCE_COLOR": "1" if force_color else "0"},
+ )
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert __version__ in strip_ansi(result.output)
+
+
[email protected]("preserve", [False, True])
[email protected]("fail", [False, True])
+def test_filesystem_restores_cwd_and_respects_directory_lifecycle(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, preserve: bool, fail: bool,
+) -> None:
+ _assert_filesystem_lifecycle(tmp_path, monkeypatch, preserve, fail)
+
+
[email protected]("preserve", [False, True])
[email protected]("fail", [False, True])
+def test_filesystem_with_symlinked_temporary_root(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, preserve: bool, fail: bool,
+) -> None:
+ target = tmp_path / "temporary-root"
+ target.mkdir()
+ alias = tmp_path / "temporary-alias"
+ alias.symlink_to(target, target_is_directory=True)
+ monkeypatch.setattr(tempfile, "tempdir", str(alias))
+ _assert_filesystem_lifecycle(tmp_path, monkeypatch, preserve, fail)
+
+
+def _assert_filesystem_lifecycle(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, preserve: bool, fail: bool,
+) -> None:
+ monkeypatch.chdir(tmp_path)
+ expectation = pytest.raises(RuntimeError, match="inside isolation") if fail else nullcontext()
+ directory: Path | None = None
+
+ with expectation:
+ with CliRunner().isolated_filesystem(temp_dir=tmp_path if preserve else None) as fs:
+ assert isinstance(fs, str)
+ directory = Path(fs)
+ assert os.path.realpath(Path.cwd()) == os.path.realpath(directory)
+ if preserve:
+ assert os.path.realpath(directory.parent) == os.path.realpath(tmp_path)
+ Path("artifact.txt").write_text("kept artifact", encoding="utf-8")
+ if fail:
+ raise RuntimeError("inside isolation")
+
+ assert os.path.realpath(Path.cwd()) == os.path.realpath(tmp_path)
+ assert directory is not None
+ assert directory.exists() is preserve
+ if preserve:
+ assert (directory / "artifact.txt").read_text(encoding="utf-8") == "kept artifact"
diff --git a/tests/test_config_loader_limits.py b/tests/test_config_loader_limits.py
index ed248625..8b778a91 100644
--- a/tests/test_config_loader_limits.py
+++ b/tests/test_config_loader_limits.py
@@ -498,21 +498,21 @@ class TestCallerWithItsOwnSizeLimit:
assert f"Config file soup.yaml {_SIZE_MESSAGE}" in _plain(result.output)
def test_ship_refuses_a_config_over_its_own_limit(self, in_tmp):
- import click
+ import typer
from soup_cli.commands import ship
(in_tmp / "soup.yaml").write_bytes(b"#" + b"x" * ship._MAX_CONFIG_BYTES)
- with pytest.raises(click.exceptions.Exit):
+ with pytest.raises(typer.Exit):
ship._parse_ship_config("soup.yaml")
def test_recipes_verify_reads_no_further_than_the_limit(self, in_tmp, capsys):
- import click
+ import typer
from soup_cli.commands.recipes import _configs_to_verify
(in_tmp / "soup.yaml").write_bytes(_config_of_size(MAX_CONFIG_BYTES + 1).encode())
- with pytest.raises(click.exceptions.Exit):
+ with pytest.raises(typer.Exit):
_configs_to_verify("soup.yaml", False)
captured = capsys.readouterr()
assert f"Config file soup.yaml {_SIZE_MESSAGE}" in _plain(captured.out + captured.err)
diff --git a/tests/test_deepspeed.py b/tests/test_deepspeed.py
index d06cc772..1bbfaee2 100644
--- a/tests/test_deepspeed.py
+++ b/tests/test_deepspeed.py
@@ -228,7 +228,7 @@ class TestResolveDeepSpeed:
def test_resolve_invalid_name(self):
"""Should raise exit for invalid name."""
- from click.exceptions import Exit
+ from typer import Exit
from soup_cli.commands.train import _resolve_deepspeed
diff --git a/tests/test_deploy_ollama.py b/tests/test_deploy_ollama.py
index ccd198ab..e261506a 100644
--- a/tests/test_deploy_ollama.py
+++ b/tests/test_deploy_ollama.py
@@ -4,8 +4,8 @@ import subprocess
from pathlib import Path
from unittest.mock import MagicMock, patch
-import click
import pytest
+import typer
from typer.testing import CliRunner
from soup_cli.cli import app
@@ -746,7 +746,7 @@ def test_export_deploy_unsupported_target():
"""_auto_deploy_ollama rejects non-ollama targets."""
from soup_cli.commands.export import _auto_deploy_ollama
- with pytest.raises((SystemExit, click.exceptions.Exit)):
+ with pytest.raises((SystemExit, typer.Exit)):
_auto_deploy_ollama(Path("m.gguf"), "model", "kubernetes", None)
@@ -755,7 +755,7 @@ def test_export_deploy_ollama_not_found(mock_detect):
"""_auto_deploy_ollama exits if Ollama not installed."""
from soup_cli.commands.export import _auto_deploy_ollama
- with pytest.raises((SystemExit, click.exceptions.Exit)):
+ with pytest.raises((SystemExit, typer.Exit)):
_auto_deploy_ollama(Path("m.gguf"), "model", "ollama", None)
@@ -775,7 +775,7 @@ def test_export_deploy_ollama_create_fails(mock_detect_fn, mock_deploy_fn):
"""_auto_deploy_ollama exits on deploy failure."""
from soup_cli.commands.export import _auto_deploy_ollama
- with pytest.raises((SystemExit, click.exceptions.Exit)):
+ with pytest.raises((SystemExit, typer.Exit)):
_auto_deploy_ollama(Path("m.gguf"), "model", "ollama", "soup-model")
@@ -783,5 +783,5 @@ def test_export_deploy_invalid_name():
"""_auto_deploy_ollama rejects invalid model name."""
from soup_cli.commands.export import _auto_deploy_ollama
- with pytest.raises((SystemExit, click.exceptions.Exit)):
+ with pytest.raises((SystemExit, typer.Exit)):
_auto_deploy_ollama(Path("m.gguf"), "model", "ollama", "bad/name")
diff --git a/tests/test_gen_reference_docs.py b/tests/test_gen_reference_docs.py
index b35ad4f1..e00f53a9 100644
--- a/tests/test_gen_reference_docs.py
+++ b/tests/test_gen_reference_docs.py
@@ -47,6 +47,7 @@ import typer
from pydantic import BaseModel, Field, create_model
from scripts import gen_reference_docs as gen
+from soup_cli.utils.typer_compat import is_argument, is_group, is_option
_ROOT = Path(__file__).resolve().parents[1]
_HEAVY = ("torch", "transformers", "accelerate", "peft", "trl", "datasets", "bitsandbytes")
@@ -228,7 +229,7 @@ def test_check_fails_when_a_command_gains_an_option(
title, command = next(
(title, cmd)
for title, cmd in _command_tree(root).items()
- if not isinstance(cmd, click.Group) and _visible(cmd)
+ if not is_group(cmd) and _visible(cmd)
)
command.params.append(
click.Option(["--brand-new-flag"], is_flag=True, default=False, help="Not yet.")
@@ -501,7 +502,7 @@ def _command_tree(cmd: click.Command, path: tuple[str, ...] = ()) -> dict[str, c
found: dict[str, click.Command] = {}
if path:
found["soup " + " ".join(path)] = cmd
- if isinstance(cmd, click.Group):
+ if is_group(cmd):
for name in cmd.list_commands(None) or []:
sub = cmd.get_command(None, name)
if sub is not None and not sub.hidden:
@@ -531,7 +532,7 @@ def _row_names(row: list[str]) -> set[str]:
def test_every_registered_command_has_exactly_one_section(cli_page: str) -> None:
tree = _command_tree(_live_root())
- leaves = [title for title, cmd in tree.items() if not isinstance(cmd, click.Group)]
+ leaves = [title for title, cmd in tree.items() if not is_group(cmd)]
assert len(leaves) >= 200, len(leaves)
sections = _cli_sections(cli_page)
@@ -551,7 +552,7 @@ def test_every_visible_option_and_argument_is_one_row_of_its_command(cli_page: s
params = _visible(cmd)
assert len(rows) == len(params), (title, len(rows), len(params))
for param, row in zip(params, rows):
- if isinstance(param, click.Option):
+ if is_option(param):
options += 1
assert _row_names(row) == {*param.opts, *param.secondary_opts}, (title, row[0])
else:
@@ -801,7 +802,7 @@ def test_argument_help_reads_the_same_whether_or_not_click_kept_it() -> None:
kept, reset = _toy_root(), _toy_root()
for root, value in ((kept, declared), (reset, {})):
for param in root.commands["bake"].params:
- if isinstance(param, click.Argument):
+ if is_argument(param):
param.help = value.get(param.name)
assert gen.render_cli_reference(kept) == gen.render_cli_reference(reset)
diff --git a/tests/test_infer.py b/tests/test_infer.py
index a9bdcf66..3e073e7b 100644
--- a/tests/test_infer.py
+++ b/tests/test_infer.py
@@ -555,7 +555,7 @@ class TestLoadModel:
adapter_config = tmp_path / "adapter_config.json"
adapter_config.write_text(json.dumps({"peft_type": "LORA"}))
- from click.exceptions import Exit
+ from typer import Exit
with pytest.raises(Exit):
_load_model(str(tmp_path), None, "cpu")
@@ -567,7 +567,7 @@ class TestLoadModel:
adapter_config = tmp_path / "adapter_config.json"
adapter_config.write_text("not valid json {{{")
- from click.exceptions import Exit
+ from typer import Exit
with pytest.raises(Exit):
_load_model(str(tmp_path), None, "cpu")
diff --git a/tests/test_issue1116_attach_preflight.py b/tests/test_issue1116_attach_preflight.py
index 45358f5a..252fc4fd 100644
--- a/tests/test_issue1116_attach_preflight.py
+++ b/tests/test_issue1116_attach_preflight.py
@@ -1220,12 +1220,13 @@ class TestTheAdvisoryGoesToStderr:
"training:\n lora:\n r: 8\n target_modules: auto\n",
encoding="utf-8",
)
- # Click < 8.2 mixes stderr into stdout unless told not to; 8.2 removed the
- # parameter and always keeps them apart (cf. test_issue762's note).
- import importlib.metadata as _md
+ # Ask this runner: Typer may use a vendored implementation whose API
+ # is independent of the installed standalone Click version.
+ import inspect
- click_version = tuple(int(x) for x in _md.version("click").split(".")[:2])
- runner = CliRunner(mix_stderr=False) if click_version < (8, 2) else CliRunner()
+ supports_separate_stderr = "mix_stderr" in inspect.signature(CliRunner).parameters
+ kwargs = {"mix_stderr": False} if supports_separate_stderr else {}
+ runner = CliRunner(**kwargs)
result = runner.invoke(app, ["recipes", "verify", "--config", str(path), "--json"])
rows = _json.loads(result.stdout)
@@ -1336,7 +1337,7 @@ class TestTheLoadersWarningsLeaveJsonStdoutAlone:
def test_json_stdout_parses_when_the_loader_warns(self, tmp_path, monkeypatch):
"""The config loader prints a deprecated value (#759) or a staged field (#808)
as a warning on stdout. Under --json that line came before the document."""
- import importlib.metadata as _md
+ import inspect
import json as _json
from transformers import LlamaConfig
@@ -1358,8 +1359,9 @@ class TestTheLoadersWarningsLeaveJsonStdoutAlone:
"training:\n lora:\n r: 8\n target_modules: [q_proj, v_proj]\n",
encoding="utf-8",
)
- click_version = tuple(int(x) for x in _md.version("click").split(".")[:2])
- runner = CliRunner(mix_stderr=False) if click_version < (8, 2) else CliRunner()
+ supports_separate_stderr = "mix_stderr" in inspect.signature(CliRunner).parameters
+ kwargs = {"mix_stderr": False} if supports_separate_stderr else {}
+ runner = CliRunner(**kwargs)
result = runner.invoke(app, ["recipes", "verify", "--config", str(path), "--json"])
assert result.exit_code == 0, (result.output, result.exception)
diff --git a/tests/test_issue1465_documented_invocations_exist.py b/tests/test_issue1465_documented_invocations_exist.py
index b1dbe277..68df13bb 100644
--- a/tests/test_issue1465_documented_invocations_exist.py
+++ b/tests/test_issue1465_documented_invocations_exist.py
@@ -35,6 +35,7 @@ import typer
from soup_cli.cli import app
from soup_cli.recipes.catalog import RECIPES
+from soup_cli.utils.typer_compat import is_group, is_option
_ROOT = Path(__file__).resolve().parents[1]
_DOC_FILES = sorted((_ROOT / "docs").glob("*.md")) + [_ROOT / "README.md"]
@@ -65,7 +66,7 @@ def _cli() -> click.Group:
def _options(cmd: click.Command) -> set[str]:
opts: set[str] = {"--help"}
for param in cmd.params:
- if isinstance(param, click.Option):
+ if is_option(param):
opts.update(o for o in param.opts if o.startswith("--"))
opts.update(o for o in param.secondary_opts if o.startswith("--"))
return opts
@@ -74,7 +75,7 @@ def _options(cmd: click.Command) -> set[str]:
def _all_options(cmd: click.Command) -> set[str]:
"""Every --option anywhere in the tree (for recipe descriptions)."""
found = _options(cmd)
- if isinstance(cmd, click.Group):
+ if is_group(cmd):
for sub in cmd.commands.values():
found |= _all_options(sub)
return found
@@ -138,7 +139,7 @@ def check_invocation(invocation: str, root: click.Group) -> str | None:
tokens = _QUOTED.sub('""', _PREFIX.sub("", invocation.strip())).split()
if not tokens or tokens[0] != "soup":
return None
- root_params = {o: p for p in root.params if isinstance(p, click.Option) for o in p.opts}
+ root_params = {o: p for p in root.params if is_option(p) for o in p.opts}
i = 1
# global options, only before the command; a valued one consumes its value
while i < len(tokens) and tokens[i].startswith("-"):
@@ -150,7 +151,7 @@ def check_invocation(invocation: str, root: click.Group) -> str | None:
if not param.is_flag and "=" not in tokens[i - 1]:
i += 1
cmd: click.Command = root
- while isinstance(cmd, click.Group) and i < len(tokens):
+ while is_group(cmd) and i < len(tokens):
name = tokens[i]
if _NOTATION.search(name):
if cmd is not root and _routes_a_default_subcommand(cmd):
@@ -164,7 +165,7 @@ def check_invocation(invocation: str, root: click.Group) -> str | None:
i += 1
rest = tokens[i:]
flags = [m.group(0) for t in rest for m in [_FLAG.match(t.strip("[]"))] if m]
- if isinstance(cmd, click.Group):
+ if is_group(cmd):
if cmd is root:
return f"no command {rest[0]!r}" if rest else None
if not rest:
@@ -211,7 +212,7 @@ def check_invocation(invocation: str, root: click.Group) -> str | None:
def _first_bare_token(rest: list[str], cmd: click.Command) -> str | None:
"""The first token of ``rest`` that is neither one of ``cmd``'s options nor the
value a valued option consumes (bracketed ``[--output v.json]`` included)."""
- params = {o: p for p in cmd.params if isinstance(p, click.Option) for o in p.opts}
+ params = {o: p for p in cmd.params if is_option(p) for o in p.opts}
i = 0
while i < len(rest):
token = rest[i].strip("[]")
diff --git a/tests/test_issue367_live_eval_quantization.py b/tests/test_issue367_live_eval_quantization.py
index 6c58f3e3..dee3cfb3 100644
--- a/tests/test_issue367_live_eval_quantization.py
+++ b/tests/test_issue367_live_eval_quantization.py
@@ -458,14 +458,13 @@ class TestShipDerivesQuantizationFromConfig:
this file's sibling tests (test_v07139.py) already cover."""
from pathlib import Path
- from typer.testing import CliRunner
-
from soup_cli.commands import ship as ship_cmd
from soup_cli.utils.ship_verdict import (
build_task_win,
compute_benchmark_deltas,
decide_ship,
)
+ from tests.cli_runner import CliRunner
captured = {}
@@ -488,14 +487,13 @@ class TestShipDerivesQuantizationFromConfig:
assert captured["quantization"] == "4bit"
def test_ship_cli_without_config_passes_none(self, monkeypatch):
- from typer.testing import CliRunner
-
from soup_cli.commands import ship as ship_cmd
from soup_cli.utils.ship_verdict import (
build_task_win,
compute_benchmark_deltas,
decide_ship,
)
+ from tests.cli_runner import CliRunner
captured = {}
@@ -522,9 +520,8 @@ class TestShipDerivesQuantizationFromConfig:
import json
from pathlib import Path
- from typer.testing import CliRunner
-
from soup_cli.commands import ship as ship_cmd
+ from tests.cli_runner import CliRunner
captured = {}
diff --git a/tests/test_issue367_ship_numerics.py b/tests/test_issue367_ship_numerics.py
index 72bd6927..48dcdb7b 100644
--- a/tests/test_issue367_ship_numerics.py
+++ b/tests/test_issue367_ship_numerics.py
@@ -20,7 +20,6 @@ from dataclasses import replace
from pathlib import Path
import pytest
-from typer.testing import CliRunner
from soup_cli.utils.ship_verdict import (
NUMERICS_FAMILY_FULL,
@@ -35,6 +34,7 @@ from soup_cli.utils.ship_verdict import (
verdict_to_dict,
verdict_to_evidence,
)
+from tests.cli_runner import CliRunner
runner = CliRunner()
diff --git a/tests/test_issue404_baseline_scorer_stamp.py b/tests/test_issue404_baseline_scorer_stamp.py
index 855ae199..7841af25 100644
--- a/tests/test_issue404_baseline_scorer_stamp.py
+++ b/tests/test_issue404_baseline_scorer_stamp.py
@@ -7,9 +7,9 @@ import json
import pytest
import yaml
-from typer.testing import CliRunner
from soup_cli.cli import app
+from tests.cli_runner import CliRunner
runner = CliRunner()
diff --git a/tests/test_issue818_edit_diff_validation.py b/tests/test_issue818_edit_diff_validation.py
index 7468a318..6a055eeb 100644
--- a/tests/test_issue818_edit_diff_validation.py
+++ b/tests/test_issue818_edit_diff_validation.py
@@ -5,10 +5,9 @@ from __future__ import annotations
import json
from pathlib import Path
-from typer.testing import CliRunner
-
from soup_cli.cli import app
from soup_cli.utils import live_eval
+from tests.cli_runner import CliRunner
from .conftest import strip_ansi
diff --git a/tests/test_issue880_edit_diff_models_without_probes.py b/tests/test_issue880_edit_diff_models_without_probes.py
index 4e5203b9..2d610187 100644
--- a/tests/test_issue880_edit_diff_models_without_probes.py
+++ b/tests/test_issue880_edit_diff_models_without_probes.py
@@ -22,9 +22,8 @@ from __future__ import annotations
import json
from pathlib import Path
-from typer.testing import CliRunner
-
from soup_cli.cli import app
+from tests.cli_runner import CliRunner
from .conftest import strip_ansi
diff --git a/tests/test_outbound_endpoint_ip_literals.py b/tests/test_outbound_endpoint_ip_literals.py
index 1cacbce9..26fec618 100644
--- a/tests/test_outbound_endpoint_ip_literals.py
+++ b/tests/test_outbound_endpoint_ip_literals.py
@@ -359,11 +359,11 @@ class TestShipJudgeModelFlag:
@pytest.mark.parametrize("host", _NON_PUBLIC_HOSTS)
def test_refused_as_a_usage_error(self, host, out):
- import click
+ import typer
from soup_cli.commands.ship import _validate_judge_model_url
- with pytest.raises(click.exceptions.Exit) as info:
+ with pytest.raises(typer.Exit) as info:
_validate_judge_model_url(f"https://{host}/m")
assert info.value.exit_code == 3
assert f"--judge-model: {_REFUSED}" in out.getvalue()
diff --git a/tests/test_runs_clean_keep_weights.py b/tests/test_runs_clean_keep_weights.py
index fc462c95..2be65e4b 100644
--- a/tests/test_runs_clean_keep_weights.py
+++ b/tests/test_runs_clean_keep_weights.py
@@ -19,6 +19,7 @@ from typer.testing import CliRunner
from soup_cli.cli import app
from soup_cli.experiment.tracker import ExperimentTracker
+from soup_cli.utils.typer_compat import is_group, is_option
runner = CliRunner()
@@ -32,10 +33,10 @@ def _plain(text: str) -> str:
def _clean_command() -> click.Command:
root = typer.main.get_command(app)
- root_ctx = click.Context(root)
+ root_ctx = root.context_class(root)
runs_group = root.get_command(root_ctx, "runs")
assert runs_group is not None
- clean = runs_group.get_command(click.Context(runs_group), "clean")
+ clean = runs_group.get_command(runs_group.context_class(runs_group), "clean")
assert clean is not None
return clean
@@ -151,8 +152,8 @@ class TestBehaviour:
def _walk(command: click.Command, path: tuple):
yield path, command
- if isinstance(command, click.Group):
- ctx = click.Context(command)
+ if is_group(command):
+ ctx = command.context_class(command)
for name in command.list_commands(ctx):
sub = command.get_command(ctx, name)
if sub is not None:
@@ -168,7 +169,7 @@ class TestNoTrueDefaultFlagWithoutNegative:
for path, command in _walk(root, ("soup",)):
for param in command.params:
if (
- isinstance(param, click.Option)
+ is_option(param)
and param.is_flag
and param.default is True
and not param.secondary_opts
diff --git a/tests/test_typer_click_compat.py b/tests/test_typer_click_compat.py
new file mode 100644
index 00000000..7fd8cff7
--- /dev/null
+++ b/tests/test_typer_click_compat.py
@@ -0,0 +1,128 @@
+"""Exercise Soup's Click-sensitive behavior on the installed, real Typer tree."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import typer
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.commands import autopilot, ship
+from soup_cli.utils.argv_redaction import all_secret_option_strings, iter_commands
+from tests.conftest import strip_ansi
+
+
[email protected]("command", [["ship"], ["expect"], ["lock", "check"]])
+def test_gate_bad_flags_keep_exit_three(command: list[str]) -> None:
+ result = CliRunner().invoke(app, [*command, "--no-such-flag"])
+ assert result.exit_code == 3, (result.output, result.exception)
+ assert "No such option" in result.output
+
+
+def test_ordinary_bad_flags_keep_exit_two() -> None:
+ result = CliRunner().invoke(app, ["version", "--no-such-flag"])
+ assert result.exit_code == 2, (result.output, result.exception)
+ assert "No such option" in result.output
+
+
+ ("arguments", "missing"),
+ [
+ ([], "--model"),
+ (["--model", "model"], "--data"),
+ (["--model", "model", "--data", "data.jsonl"], "--goal"),
+ ],
+)
[email protected]("color", [False, True], ids=["plain", "ansi"])
+def test_noninteractive_autopilot_reports_the_missing_option(
+ monkeypatch: pytest.MonkeyPatch, arguments: list[str], missing: str, color: bool,
+) -> None:
+ monkeypatch.setattr(autopilot, "_stdin_isatty", lambda: False)
+ result = CliRunner().invoke(
+ app, ["autopilot", *arguments], color=color,
+ env={"FORCE_COLOR": "1" if color else "0"},
+ )
+ assert result.exit_code == 2, (result.output, result.exception)
+ output = " ".join(strip_ansi(result.output).split())
+ assert "Missing option" in output and missing in output
+
+
[email protected]("explicit", [False, True])
+def test_ship_uses_config_defaults_but_preserves_explicit_flags(
+ monkeypatch: pytest.MonkeyPatch, explicit: bool,
+) -> None:
+ configured = SimpleNamespace(
+ task_eval=None, task_mode="metric", general_suite=None, judge_model=None,
+ baseline=None, forgetting_threshold=0.42, noise_floor=None,
+ )
+ monkeypatch.setattr(ship, "_parse_ship_config", lambda path: (None, configured))
+ observed = []
+
+ def stop_after_threshold(value: float) -> None:
+ observed.append(value)
+ raise typer.Exit(0)
+
+ monkeypatch.setattr(ship, "_validate_threshold_flag", stop_after_threshold)
+ arguments = ["ship", "--config", "soup.yaml"]
+ if explicit:
+ arguments.extend(["--forgetting-threshold", "0.17"])
+ result = CliRunner().invoke(app, arguments)
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert observed == [0.17 if explicit else 0.42]
+
+
+def test_ship_unknown_parameter_cannot_be_overridden() -> None:
+ command = typer.main.get_command(app).commands["ship"]
+ with command.make_context("ship", []) as context:
+ assert not ship._flag_is_default(context, "unknown_parameter")
+
+
[email protected]("explicit", [False, True])
+def test_push_keeps_hf_env_token_out_of_other_hubs(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, explicit: bool,
+) -> None:
+ from soup_cli.utils import hubs
+
+ monkeypatch.chdir(tmp_path)
+ model = tmp_path / "model"
+ model.mkdir()
+ (model / "config.json").write_text(json.dumps({"model_type": "llama"}), encoding="utf-8")
+ monkeypatch.setenv("HF_TOKEN", "hf-token-for-hf-only")
+ monkeypatch.setenv("MODELSCOPE_API_TOKEN", "modelscope-env-token")
+ uploads = []
+ monkeypatch.setattr(hubs, "upload_repo", lambda *args, **kwargs: uploads.append(kwargs))
+ arguments = ["push", "--model", "model", "--repo", "user/model", "--hub", "modelscope"]
+ if explicit:
+ arguments.extend(["--token", "typed-modelscope-token"])
+ result = CliRunner().invoke(app, arguments)
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert len(uploads) == 1
+ assert uploads[0]["token"] == (
+ "typed-modelscope-token" if explicit else "modelscope-env-token"
+ )
+
+
+ "arguments",
+ [["bench", "model", "--help"], ["bench", "--p50", "model", "--help"]],
+)
[email protected]("color", [False, True], ids=["plain", "ansi"])
+def test_bench_legacy_routing_reaches_infer_help(arguments: list[str], color: bool) -> None:
+ result = CliRunner().invoke(
+ app, arguments, color=color, env={"COLUMNS": "200", "FORCE_COLOR": "1" if color else "0"},
+ )
+ assert result.exit_code == 0, (result.output, result.exception)
+ output = " ".join(strip_ansi(result.output).split())
+ assert "Path to model" in output and "--max-tokens" in output
+
+
+def test_redaction_walks_the_real_tree_and_finds_nested_credentials() -> None:
+ root = typer.main.get_command(app)
+ commands = list(iter_commands(root))
+ assert len(commands) > 200
+ assert root.commands["push"] in commands
+ assert {"--token", "-t", "--api-key", "--tool-auth-token"} <= all_secret_option_strings(root)
diff --git a/tests/test_v0430_part_d.py b/tests/test_v0430_part_d.py
index 654be15f..3f2867b4 100644
--- a/tests/test_v0430_part_d.py
+++ b/tests/test_v0430_part_d.py
@@ -6,7 +6,6 @@ import os
from pathlib import Path
import pytest
-from typer.testing import CliRunner
from soup_cli.commands.data import app as data_app
from soup_cli.utils.demo_bundles import (
@@ -16,6 +15,7 @@ from soup_cli.utils.demo_bundles import (
get_bundle,
list_bundles,
)
+from tests.cli_runner import CliRunner
class TestDemoBundleRegistry:
diff --git a/tests/test_v0610_part_b.py b/tests/test_v0610_part_b.py
index d6315d6f..46ac0291 100644
--- a/tests/test_v0610_part_b.py
+++ b/tests/test_v0610_part_b.py
@@ -17,9 +17,9 @@ import os
from pathlib import Path
import pytest
-from typer.testing import CliRunner
from soup_cli.cli import app
+from tests.cli_runner import CliRunner
# ---------- Module surface ----------
diff --git a/tests/test_v0610_part_e.py b/tests/test_v0610_part_e.py
index e01a2fef..310be3bc 100644
--- a/tests/test_v0610_part_e.py
+++ b/tests/test_v0610_part_e.py
@@ -16,9 +16,9 @@ import os
from pathlib import Path
import pytest
-from typer.testing import CliRunner
from soup_cli.cli import app
+from tests.cli_runner import CliRunner
class TestDataclasses:
diff --git a/tests/test_v07110.py b/tests/test_v07110.py
index 73818d74..99312075 100644
--- a/tests/test_v07110.py
+++ b/tests/test_v07110.py
@@ -508,7 +508,7 @@ class TestPerStyleExtractors:
class TestEvalCitationCli:
def _runner(self):
- from typer.testing import CliRunner
+ from tests.cli_runner import CliRunner
return CliRunner()
@@ -920,7 +920,7 @@ class TestInstallSteeringHook:
class TestServeSteerCli:
def _runner(self):
- from typer.testing import CliRunner
+ from tests.cli_runner import CliRunner
return CliRunner()
@@ -960,9 +960,9 @@ class TestSteerCommandPlumbing:
import numpy as np
from safetensors.numpy import save_file
- from typer.testing import CliRunner
from soup_cli.commands.steer import app
+ from tests.cli_runner import CliRunner
monkeypatch.chdir(tmp_path)
d = "steering/safety-v1"
@@ -982,9 +982,8 @@ class TestSteerCommandPlumbing:
assert "Vector loaded" in result.output
def test_steer_train_help_has_output(self):
- from typer.testing import CliRunner
-
from soup_cli.commands.steer import app
+ from tests.cli_runner import CliRunner
result = CliRunner().invoke(app, ["train", "--help"])
assert result.exit_code == 0
@@ -1263,7 +1262,7 @@ class TestTrainAutolinkHook:
class TestRaDitCli:
def _runner(self):
- from typer.testing import CliRunner
+ from tests.cli_runner import CliRunner
return CliRunner()
@@ -1910,9 +1909,8 @@ class TestV07110ReviewFixRegressions:
assert "validate_steering_strength" in src
def test_serve_bad_steer_name_message(self):
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
result = CliRunner().invoke(
app, ["serve", "-m", "model", "--steer", "bad/name"]
diff --git a/tests/test_v07123.py b/tests/test_v07123.py
index 08203f84..92c48780 100644
--- a/tests/test_v07123.py
+++ b/tests/test_v07123.py
@@ -26,7 +26,8 @@ from pathlib import Path
import numpy as np
import pytest
-from typer.testing import CliRunner
+
+from tests.cli_runner import CliRunner
_SRC = Path(__file__).resolve().parent.parent / "src" / "soup_cli"
diff --git a/tests/test_v07125.py b/tests/test_v07125.py
index e054c4bc..4a930e82 100644
--- a/tests/test_v07125.py
+++ b/tests/test_v07125.py
@@ -24,7 +24,6 @@ from pathlib import Path
import pytest
from rich.console import Console
-from typer.testing import CliRunner
from soup_cli import __version__
from soup_cli.utils.ship_verdict import (
@@ -44,6 +43,7 @@ from soup_cli.utils.ship_verdict import (
render_ship_panel,
verdict_to_dict,
)
+from tests.cli_runner import CliRunner
_SRC = Path(__file__).resolve().parent.parent / "src" / "soup_cli"
diff --git a/tests/test_v07138.py b/tests/test_v07138.py
index 1cf47fa3..72466dba 100644
--- a/tests/test_v07138.py
+++ b/tests/test_v07138.py
@@ -494,10 +494,9 @@ class TestShipLiveHeadline:
def _run(self, monkeypatch, base_gen, tuned_gen, extra_args=None, want_verdict=False):
import json as _json
- from typer.testing import CliRunner
-
from soup_cli.cli import app
from soup_cli.commands import ship as ship_cmd
+ from tests.cli_runner import CliRunner
# Inject deterministic generators (no model load).
monkeypatch.setattr(
@@ -604,9 +603,8 @@ class TestExitCodeTaxonomy:
can tell a config typo from a caught regression."""
def _invoke(self, args):
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
return CliRunner().invoke(app, ["ship", *args])
diff --git a/tests/test_v07139.py b/tests/test_v07139.py
index 9ab31757..a45a75ca 100644
--- a/tests/test_v07139.py
+++ b/tests/test_v07139.py
@@ -21,7 +21,6 @@ import json
from pathlib import Path
import pytest
-from typer.testing import CliRunner
from soup_cli.utils.ship_verdict import (
TASK_MODES,
@@ -30,6 +29,7 @@ from soup_cli.utils.ship_verdict import (
decide_ship,
verdict_to_evidence,
)
+from tests.cli_runner import CliRunner
_SRC = Path(__file__).resolve().parent.parent / "src" / "soup_cli"
diff --git a/tests/test_v07302.py b/tests/test_v07302.py
index a6fab779..d50f084b 100644
--- a/tests/test_v07302.py
+++ b/tests/test_v07302.py
@@ -873,9 +873,8 @@ class TestAHostileEvidenceFloorIsBoundedAndLoud:
"""The actual mitigation: the evidence reader must be exactly as loud
as the live measurement path. The quieter of two readers is the one an
attacker picks."""
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
monkeypatch.chdir(tmp_path)
(tmp_path / "ev.json").write_text(
@@ -902,9 +901,8 @@ class TestAHostileEvidenceFloorIsBoundedAndLoud:
):
"""CONTROL. Warning on every evidence file trains the operator to
ignore the warning."""
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
monkeypatch.chdir(tmp_path)
(tmp_path / "ev.json").write_text(
@@ -1343,10 +1341,9 @@ def _run_ship_cli(monkeypatch, base_gen, tuned_gen, extra_args=None):
"""
import os as _os
- from typer.testing import CliRunner
-
from soup_cli.cli import app
from soup_cli.commands import ship as ship_cmd
+ from tests.cli_runner import CliRunner
monkeypatch.setattr(
ship_cmd, "_resolve_generators", lambda *a, **k: (base_gen, tuned_gen)
@@ -1751,14 +1748,13 @@ class TestBareFunctionShapeGuard:
class TestNoiseFloorCliFlag:
def _runner(self):
- from typer.testing import CliRunner
+ from tests.cli_runner import CliRunner
return CliRunner()
def test_the_flag_exists_and_is_documented(self):
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
result = CliRunner().invoke(app, ["ship", "--help"])
assert result.exit_code == 0, (result.output, repr(result.exception))
@@ -1770,9 +1766,8 @@ class TestNoiseFloorCliFlag:
@pytest.mark.parametrize("bad", ["1", "0", "-3", "11"])
def test_out_of_range_is_a_usage_error(self, bad, tmp_path):
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
tasks = tmp_path / "t.jsonl"
tasks.write_text('{"prompt": "hi", "expected": "hi"}\n', encoding="utf-8")
@@ -1789,9 +1784,8 @@ class TestNoiseFloorCliFlag:
def test_an_offline_verdict_refuses_to_measure_a_floor(self, tmp_path, monkeypatch):
"""``--evidence`` loads no model, so there is nothing to repeat.
Refusing beats silently ignoring the flag the operator asked for."""
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
monkeypatch.chdir(tmp_path)
ev = tmp_path / "ev.json"
@@ -1811,9 +1805,8 @@ class TestNoiseFloorCliFlag:
def test_an_offline_verdict_without_the_flag_still_works(self, tmp_path, monkeypatch):
"""CONTROL. The refusal must be about the FLAG, not about --evidence."""
- from typer.testing import CliRunner
-
from soup_cli.cli import app
+ from tests.cli_runner import CliRunner
monkeypatch.chdir(tmp_path)
ev = tmp_path / "ev.json"