|
| 1 | +"""CLI smoke and seam-contract tests. |
| 2 | +
|
| 3 | +Issue #999: `openadapt serve` and `openadapt train start` were broken |
| 4 | +for months while CI stayed green, because cli.py's imports of |
| 5 | +openadapt-ml only execute inside command bodies and the broad |
| 6 | +`except ImportError` handlers reported every failure as |
| 7 | +"openadapt-ml not installed". |
| 8 | +
|
| 9 | +Three layers of defense here: |
| 10 | +
|
| 11 | +1. test_every_command_help — walks the whole Click tree and renders |
| 12 | + --help for every command, so any module-level wiring error fails CI. |
| 13 | +2. Contract tests — monkeypatch the openadapt-ml entry points and |
| 14 | + assert cli.py calls them the way they're actually shaped today. |
| 15 | +3. test_cmd_serve_reads_only_provided_args — parses the installed |
| 16 | + openadapt-ml's cmd_serve and asserts every `args.<attr>` it reads is |
| 17 | + provided by cli.py's Namespace, so the seam can't drift silently in |
| 18 | + either direction. |
| 19 | +
|
| 20 | +The openadapt-ml-dependent tests skip when it isn't installed; CI |
| 21 | +installs it so they always run there. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import ast |
| 27 | +import sys |
| 28 | +from pathlib import Path |
| 29 | + |
| 30 | +import click |
| 31 | +import pytest |
| 32 | +from click.testing import CliRunner |
| 33 | + |
| 34 | +from openadapt.cli import main as cli_main |
| 35 | + |
| 36 | +# Namespace attributes cli.py's serve command provides to cmd_serve. |
| 37 | +# Keep in sync with openadapt/cli.py::serve. |
| 38 | +SERVE_NAMESPACE_ATTRS = { |
| 39 | + "port", |
| 40 | + "benchmark", |
| 41 | + "no_regenerate", |
| 42 | + "start_page", |
| 43 | + "quiet", |
| 44 | + "open", |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | +def _iter_commands(group, prefix=()): |
| 49 | + yield prefix, group |
| 50 | + if isinstance(group, click.Group): |
| 51 | + for name, cmd in group.commands.items(): |
| 52 | + yield from _iter_commands(cmd, prefix + (name,)) |
| 53 | + |
| 54 | + |
| 55 | +def test_every_command_help(): |
| 56 | + """Render --help for every command in the tree.""" |
| 57 | + runner = CliRunner() |
| 58 | + failures = [] |
| 59 | + for path, _cmd in _iter_commands(cli_main): |
| 60 | + args = list(path) + ["--help"] |
| 61 | + result = runner.invoke(cli_main, args) |
| 62 | + if result.exit_code != 0: |
| 63 | + failures.append(f"{' '.join(args)!r} exited {result.exit_code}") |
| 64 | + assert not failures, "Commands whose --help failed:\n " + "\n ".join(failures) |
| 65 | + |
| 66 | + |
| 67 | +def test_version_command(): |
| 68 | + runner = CliRunner() |
| 69 | + result = runner.invoke(cli_main, ["version"]) |
| 70 | + assert result.exit_code == 0 |
| 71 | + |
| 72 | + |
| 73 | +# --------------------------------------------------------------------------- |
| 74 | +# Seam contracts with openadapt-ml |
| 75 | +# --------------------------------------------------------------------------- |
| 76 | + |
| 77 | + |
| 78 | +def _require_openadapt_ml(): |
| 79 | + return pytest.importorskip("openadapt_ml", reason="openadapt-ml not installed") |
| 80 | + |
| 81 | + |
| 82 | +def test_train_start_calls_real_entry_point(monkeypatch, tmp_path): |
| 83 | + """`openadapt train start` must call scripts.train.main with kwargs |
| 84 | + that exist in its signature.""" |
| 85 | + _require_openadapt_ml() |
| 86 | + import inspect |
| 87 | + |
| 88 | + from openadapt_ml.scripts import train as train_module |
| 89 | + |
| 90 | + real_params = set(inspect.signature(train_module.main).parameters) |
| 91 | + calls = [] |
| 92 | + |
| 93 | + def fake_main(**kwargs): |
| 94 | + unknown = set(kwargs) - real_params |
| 95 | + assert not unknown, ( |
| 96 | + f"cli.py passes kwargs {sorted(unknown)} that " |
| 97 | + f"openadapt_ml.scripts.train.main does not accept " |
| 98 | + f"(it takes {sorted(real_params)})" |
| 99 | + ) |
| 100 | + calls.append(kwargs) |
| 101 | + |
| 102 | + monkeypatch.setattr(train_module, "main", fake_main) |
| 103 | + |
| 104 | + capture_dir = tmp_path / "my-capture" |
| 105 | + capture_dir.mkdir() |
| 106 | + config = tmp_path / "config.yaml" |
| 107 | + config.write_text("model:\n name: test\n") |
| 108 | + |
| 109 | + runner = CliRunner() |
| 110 | + result = runner.invoke( |
| 111 | + cli_main, |
| 112 | + [ |
| 113 | + "train", |
| 114 | + "start", |
| 115 | + "--capture", |
| 116 | + str(capture_dir), |
| 117 | + "--config", |
| 118 | + str(config), |
| 119 | + "--no-open", |
| 120 | + ], |
| 121 | + ) |
| 122 | + assert result.exit_code == 0, result.output |
| 123 | + assert len(calls) == 1 |
| 124 | + kwargs = calls[0] |
| 125 | + assert kwargs["config_path"] == str(config) |
| 126 | + assert kwargs["capture_path"] == str(capture_dir) |
| 127 | + assert kwargs["open_dashboard"] is False |
| 128 | + |
| 129 | + |
| 130 | +def test_serve_calls_cmd_serve_with_expected_namespace(monkeypatch): |
| 131 | + """`openadapt serve` must call cmd_serve with the agreed Namespace.""" |
| 132 | + _require_openadapt_ml() |
| 133 | + from openadapt_ml.cloud import local as oa_local |
| 134 | + |
| 135 | + received = [] |
| 136 | + |
| 137 | + def fake_cmd_serve(args): |
| 138 | + received.append(args) |
| 139 | + return 0 |
| 140 | + |
| 141 | + monkeypatch.setattr(oa_local, "cmd_serve", fake_cmd_serve) |
| 142 | + |
| 143 | + runner = CliRunner() |
| 144 | + result = runner.invoke(cli_main, ["serve", "--port", "8123", "--no-open"]) |
| 145 | + assert result.exit_code == 0, result.output |
| 146 | + assert len(received) == 1 |
| 147 | + ns = received[0] |
| 148 | + assert ns.port == 8123 |
| 149 | + assert ns.open is False # --no-open passes through to cmd_serve |
| 150 | + for attr in SERVE_NAMESPACE_ATTRS: |
| 151 | + assert hasattr(ns, attr), f"Namespace missing {attr}" |
| 152 | + |
| 153 | + |
| 154 | +def test_serve_honors_output_directory(monkeypatch, tmp_path): |
| 155 | + """--output must repoint openadapt-ml's TRAINING_OUTPUT.""" |
| 156 | + _require_openadapt_ml() |
| 157 | + from openadapt_ml.cloud import local as oa_local |
| 158 | + |
| 159 | + monkeypatch.setattr(oa_local, "cmd_serve", lambda args: 0) |
| 160 | + |
| 161 | + runner = CliRunner() |
| 162 | + out = tmp_path / "runs" |
| 163 | + result = runner.invoke(cli_main, ["serve", "--output", str(out), "--no-open"]) |
| 164 | + assert result.exit_code == 0, result.output |
| 165 | + assert Path(oa_local.TRAINING_OUTPUT) == out |
| 166 | + |
| 167 | + |
| 168 | +def test_cmd_serve_reads_only_provided_args(): |
| 169 | + """Every `args.<attr>` cmd_serve reads must be in cli.py's Namespace. |
| 170 | +
|
| 171 | + This is the direction the contract can silently drift: openadapt-ml |
| 172 | + adds a new required Namespace attribute and cli.py doesn't provide |
| 173 | + it. Parse the installed cmd_serve and check. |
| 174 | + """ |
| 175 | + ml = _require_openadapt_ml() |
| 176 | + local_path = Path(next(iter(ml.__path__))) / "cloud" / "local.py" |
| 177 | + tree = ast.parse(local_path.read_text(encoding="utf-8")) |
| 178 | + cmd_serve = next( |
| 179 | + ( |
| 180 | + node |
| 181 | + for node in tree.body |
| 182 | + if isinstance(node, ast.FunctionDef) and node.name == "cmd_serve" |
| 183 | + ), |
| 184 | + None, |
| 185 | + ) |
| 186 | + assert cmd_serve is not None, "cmd_serve not found in openadapt-ml" |
| 187 | + |
| 188 | + args_param = cmd_serve.args.args[0].arg |
| 189 | + read_attrs = { |
| 190 | + node.attr |
| 191 | + for node in ast.walk(cmd_serve) |
| 192 | + if isinstance(node, ast.Attribute) |
| 193 | + and isinstance(node.value, ast.Name) |
| 194 | + and node.value.id == args_param |
| 195 | + } |
| 196 | + missing = read_attrs - SERVE_NAMESPACE_ATTRS |
| 197 | + assert not missing, ( |
| 198 | + f"openadapt-ml's cmd_serve reads args attributes " |
| 199 | + f"{sorted(missing)} that openadapt's serve command does not " |
| 200 | + f"provide; update openadapt/cli.py (and SERVE_NAMESPACE_ATTRS)" |
| 201 | + ) |
| 202 | + |
| 203 | + |
| 204 | +def test_import_error_messages_not_masked(monkeypatch): |
| 205 | + """Internal ImportErrors must surface the real error, not claim |
| 206 | + openadapt-ml isn't installed.""" |
| 207 | + _require_openadapt_ml() |
| 208 | + |
| 209 | + import builtins |
| 210 | + |
| 211 | + real_import = builtins.__import__ |
| 212 | + |
| 213 | + def broken_import(name, *args, **kwargs): |
| 214 | + if name == "openadapt_ml.cloud" or name.startswith("openadapt_ml.cloud."): |
| 215 | + raise ImportError( |
| 216 | + "cannot import name 'definitely_phantom' from " |
| 217 | + "'openadapt_ml.cloud.local'" |
| 218 | + ) |
| 219 | + return real_import(name, *args, **kwargs) |
| 220 | + |
| 221 | + monkeypatch.setattr(builtins, "__import__", broken_import) |
| 222 | + monkeypatch.delitem(sys.modules, "openadapt_ml.cloud.local", raising=False) |
| 223 | + monkeypatch.delitem(sys.modules, "openadapt_ml.cloud", raising=False) |
| 224 | + |
| 225 | + runner = CliRunner() |
| 226 | + result = runner.invoke(cli_main, ["serve", "--no-open"]) |
| 227 | + assert result.exit_code != 0 |
| 228 | + assert "definitely_phantom" in result.output, ( |
| 229 | + "The underlying ImportError must appear in the CLI output; " |
| 230 | + f"got: {result.output}" |
| 231 | + ) |
0 commit comments