| 1 | """Tests for the remote API path (LAST30DAYS_API_KEY + LAST30DAYS_API_BASE). |
| 2 | |
| 3 | Fixtures mirror the remote API contract exactly: |
| 4 | POST {base}/search {"query","depth"} -> {"search_id","status"} | clarify payload |
| 5 | GET {base}/search?id=<uuid> -> pending|running|complete|error rows |
| 6 | 401 {"error"} / 402 {"error","requires_credits","balance","needed"} / 429 {"error"} |
| 7 | The endpoint is driven entirely through LAST30DAYS_API_BASE; there is no |
| 8 | built-in default. All keys/hosts in tests are obvious dummy values (see |
| 9 | AGENTS.md security hygiene). |
| 10 | """ |
| 11 | |
| 12 | import io |
| 13 | import json |
| 14 | import sys |
| 15 | from contextlib import redirect_stderr, redirect_stdout |
| 16 | from datetime import datetime, timedelta, timezone |
| 17 | from unittest import mock |
| 18 | |
| 19 | import pytest |
| 20 | |
| 21 | import last30days as cli |
| 22 | from lib import hosted, http, schema |
| 23 | |
| 24 | TEST_KEY = "sk_live_DUMMY_TEST_KEY_00000" |
| 25 | # Neutral placeholder endpoint - no product host. Ends in /api/v1 to mirror the |
| 26 | # API-version-root convention the billing-link derivation relies on. |
| 27 | TEST_BASE = "https://api.example.test/api/v1" |
| 28 | SEARCH_ID = "3f6c1c2e-9f6a-4a55-8f8a-2d1a9b8c7d6e" |
| 29 | |
| 30 | SUBMIT_OK = {"search_id": SEARCH_ID, "status": "running"} |
| 31 | POLL_RUNNING = { |
| 32 | "id": SEARCH_ID, |
| 33 | "status": "running", |
| 34 | "stderr": ( |
| 35 | "[narrate] step=planning queries\n" |
| 36 | "[Reddit] fetched 12 threads\n" |
| 37 | "[narrate] step=searching sources\n" |
| 38 | ), |
| 39 | "eta_ms": 45000, |
| 40 | } |
| 41 | POLL_COMPLETE = { |
| 42 | "id": SEARCH_ID, |
| 43 | "status": "complete", |
| 44 | "synthesis_text": "## What happened\nSynthesized report body.", |
| 45 | "raw_markdown": "# Raw markdown\nFull dump.", |
| 46 | } |
| 47 | CLARIFY_RESPONSE = { |
| 48 | "needs_clarification": True, |
| 49 | "clarify_class": "ambiguous_entity", |
| 50 | "question": "Which 'mercury' do you mean?", |
| 51 | "options": ["Mercury the planet", "Mercury the element", "Mercury the band"], |
| 52 | "original_query": "mercury", |
| 53 | } |
| 54 | |
| 55 | DIAG = { |
| 56 | "available_sources": ["grounding"], |
| 57 | "providers": {"google": True, "openai": False, "xai": False}, |
| 58 | "x_backend": None, |
| 59 | "bird_installed": False, |
| 60 | "bird_authenticated": False, |
| 61 | "bird_username": None, |
| 62 | "native_web_backend": "brave", |
| 63 | } |
| 64 | |
| 65 | |
| 66 | def make_report(topic: str = "test topic") -> schema.Report: |
| 67 | return schema.Report( |
| 68 | topic=topic, |
| 69 | range_from="2026-06-03", |
| 70 | range_to="2026-07-03", |
| 71 | generated_at="2026-07-03T00:00:00+00:00", |
| 72 | provider_runtime=schema.ProviderRuntime( |
| 73 | reasoning_provider="gemini", |
| 74 | planner_model="gemini-3.1-flash-lite", |
| 75 | rerank_model="gemini-3.1-flash-lite", |
| 76 | ), |
| 77 | query_plan=schema.QueryPlan( |
| 78 | intent="overview", |
| 79 | freshness_mode="balanced_recent", |
| 80 | cluster_mode="themes", |
| 81 | raw_topic=topic, |
| 82 | subqueries=[ |
| 83 | schema.SubQuery( |
| 84 | label="primary", |
| 85 | search_query=topic.lower(), |
| 86 | ranking_query=f"What happened with {topic}?", |
| 87 | sources=["grounding"], |
| 88 | ) |
| 89 | ], |
| 90 | source_weights={"grounding": 1.0}, |
| 91 | ), |
| 92 | clusters=[], |
| 93 | ranked_candidates=[], |
| 94 | items_by_source={"grounding": []}, |
| 95 | errors_by_source={}, |
| 96 | ) |
| 97 | |
| 98 | |
| 99 | def run_main(argv): |
| 100 | stdout, stderr = io.StringIO(), io.StringIO() |
| 101 | with mock.patch.object(sys, "argv", ["last30days.py", *argv]): |
| 102 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 103 | rc = cli.main() |
| 104 | return rc, stdout.getvalue(), stderr.getvalue() |
| 105 | |
| 106 | |
| 107 | @pytest.fixture(autouse=True) |
| 108 | def _clean_env(monkeypatch): |
| 109 | monkeypatch.delenv("LAST30DAYS_API_KEY", raising=False) |
| 110 | monkeypatch.delenv("LAST30DAYS_API_BASE", raising=False) |
| 111 | monkeypatch.delenv("LAST30DAYS_API_MODE", raising=False) |
| 112 | monkeypatch.delenv("LAST30DAYS_MEMORY_DIR", raising=False) |
| 113 | |
| 114 | |
| 115 | # --------------------------------------------------------------------------- |
| 116 | # Mode selection in the CLI entrypoint |
| 117 | # --------------------------------------------------------------------------- |
| 118 | |
| 119 | |
| 120 | def test_env_unset_runs_local_path_with_no_gateway_http(monkeypatch): |
| 121 | """Without LAST30DAYS_API_KEY the local engine runs; the remote client and |
| 122 | the API are never touched.""" |
| 123 | |
| 124 | def no_hosted(*args, **kwargs): # pragma: no cover - failure path |
| 125 | raise AssertionError("remote path must not run when env is unset") |
| 126 | |
| 127 | def no_http(*args, **kwargs): # pragma: no cover - failure path |
| 128 | raise AssertionError(f"unexpected HTTP call in local test: {args}") |
| 129 | |
| 130 | monkeypatch.setattr(hosted, "run_hosted", no_hosted) |
| 131 | monkeypatch.setattr(http, "request", no_http) |
| 132 | |
| 133 | fake_progress = mock.Mock() |
| 134 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 135 | mock.patch.object(cli.pipeline, "diagnose", return_value=DIAG), \ |
| 136 | mock.patch.object(cli.pipeline, "run", return_value=make_report()) as pipeline_run, \ |
| 137 | mock.patch.object(cli.ui, "ProgressDisplay", return_value=fake_progress), \ |
| 138 | mock.patch.object(cli, "emit_output", return_value="# local rendered"): |
| 139 | rc, out, _err = run_main(["test", "topic"]) |
| 140 | |
| 141 | assert rc == 0 |
| 142 | pipeline_run.assert_called_once() |
| 143 | assert "# local rendered" in out |
| 144 | |
| 145 | |
| 146 | def test_env_set_routes_to_remote_path(monkeypatch): |
| 147 | # Both vars set -> remote path (KTD-2: key alone no longer activates it). |
| 148 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 149 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 150 | calls = [] |
| 151 | |
| 152 | def fake_run_hosted(topic, depth, *, emit, save_dir, save_suffix): |
| 153 | calls.append({"topic": topic, "depth": depth, "emit": emit, |
| 154 | "save_dir": save_dir, "save_suffix": save_suffix}) |
| 155 | return 0 |
| 156 | |
| 157 | monkeypatch.setattr(hosted, "run_hosted", fake_run_hosted) |
| 158 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 159 | mock.patch.object(cli.pipeline, "run", |
| 160 | side_effect=AssertionError("local pipeline must not run")): |
| 161 | rc, _out, _err = run_main(["test", "topic"]) |
| 162 | |
| 163 | assert rc == 0 |
| 164 | assert calls == [{ |
| 165 | "topic": "test topic", |
| 166 | "depth": "default", |
| 167 | "emit": "compact", |
| 168 | "save_dir": None, |
| 169 | "save_suffix": "", |
| 170 | }] |
| 171 | |
| 172 | |
| 173 | def test_register_is_forwarded_to_remote_backend(monkeypatch): |
| 174 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 175 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 176 | calls = [] |
| 177 | |
| 178 | monkeypatch.setattr( |
| 179 | hosted, |
| 180 | "run_hosted", |
| 181 | lambda topic, depth, **kwargs: calls.append((topic, depth, kwargs)) or 0, |
| 182 | ) |
| 183 | with mock.patch.object(cli.env, "get_config", return_value={}): |
| 184 | rc, _out, _err = run_main( |
| 185 | ["test", "topic", "--register=creator"] |
| 186 | ) |
| 187 | |
| 188 | assert rc == 0 |
| 189 | assert calls == [ |
| 190 | ( |
| 191 | "test topic", |
| 192 | "default", |
| 193 | { |
| 194 | "emit": "compact", |
| 195 | "save_dir": None, |
| 196 | "save_suffix": "", |
| 197 | "register": "creator", |
| 198 | }, |
| 199 | ) |
| 200 | ] |
| 201 | |
| 202 | |
| 203 | def test_hosted_submit_adds_only_nondefault_register(remote_env, monkeypatch): |
| 204 | payloads = [] |
| 205 | monkeypatch.setattr( |
| 206 | hosted.http, |
| 207 | "post", |
| 208 | lambda _url, *, json_data, **_kwargs: payloads.append(json_data) or SUBMIT_OK, |
| 209 | ) |
| 210 | |
| 211 | hosted.submit("test topic", "quick") |
| 212 | hosted.submit("test topic", "quick", register="dev") |
| 213 | |
| 214 | assert payloads == [ |
| 215 | {"query": "test topic", "depth": "quick"}, |
| 216 | {"query": "test topic", "depth": "quick", "register": "dev"}, |
| 217 | ] |
| 218 | |
| 219 | |
| 220 | def test_remote_json_requires_raw_profile(monkeypatch): |
| 221 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 222 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 223 | monkeypatch.setattr( |
| 224 | hosted, |
| 225 | "run_hosted", |
| 226 | lambda *args, **kwargs: pytest.fail("remote request should not start"), |
| 227 | ) |
| 228 | |
| 229 | with mock.patch.object(cli.env, "get_config", return_value={}): |
| 230 | rc, _out, err = run_main(["test", "topic", "--emit=json"]) |
| 231 | |
| 232 | assert rc == 2 |
| 233 | assert "remote API backend only supports --json-profile=raw" in err |
| 234 | |
| 235 | |
| 236 | def test_remote_raw_json_preserves_existing_server_contract(monkeypatch): |
| 237 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 238 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 239 | calls = [] |
| 240 | monkeypatch.setattr( |
| 241 | hosted, |
| 242 | "run_hosted", |
| 243 | lambda topic, depth, **kwargs: calls.append((topic, depth, kwargs)) or 0, |
| 244 | ) |
| 245 | |
| 246 | with mock.patch.object(cli.env, "get_config", return_value={}): |
| 247 | rc, _out, _err = run_main( |
| 248 | ["test", "topic", "--emit=json", "--json-profile=raw"] |
| 249 | ) |
| 250 | |
| 251 | assert rc == 0 |
| 252 | assert calls == [ |
| 253 | ( |
| 254 | "test topic", |
| 255 | "default", |
| 256 | {"emit": "json", "save_dir": None, "save_suffix": ""}, |
| 257 | ) |
| 258 | ] |
| 259 | |
| 260 | |
| 261 | @pytest.mark.parametrize( |
| 262 | ("flag", "expected_depth"), |
| 263 | [(["--quick"], "quick"), ([], "default"), (["--deep"], "deep")], |
| 264 | ) |
| 265 | def test_depth_mapping(monkeypatch, flag, expected_depth): |
| 266 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 267 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 268 | depths = [] |
| 269 | monkeypatch.setattr( |
| 270 | hosted, "run_hosted", |
| 271 | lambda topic, depth, **kwargs: depths.append(depth) or 0, |
| 272 | ) |
| 273 | with mock.patch.object(cli.env, "get_config", return_value={}): |
| 274 | rc, _out, _err = run_main(["test", "topic", *flag]) |
| 275 | assert rc == 0 |
| 276 | assert depths == [expected_depth] |
| 277 | |
| 278 | |
| 279 | def test_mock_flag_stays_local_even_with_key(monkeypatch): |
| 280 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 281 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 282 | |
| 283 | def no_hosted(*args, **kwargs): # pragma: no cover - failure path |
| 284 | raise AssertionError("remote path must not run with --mock") |
| 285 | |
| 286 | monkeypatch.setattr(hosted, "run_hosted", no_hosted) |
| 287 | fake_progress = mock.Mock() |
| 288 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 289 | mock.patch.object(cli.pipeline, "diagnose", return_value=DIAG), \ |
| 290 | mock.patch.object(cli.pipeline, "run", return_value=make_report()) as pipeline_run, \ |
| 291 | mock.patch.object(cli.ui, "ProgressDisplay", return_value=fake_progress), \ |
| 292 | mock.patch.object(cli, "emit_output", return_value="# local rendered"): |
| 293 | rc, _out, _err = run_main(["test", "topic", "--mock"]) |
| 294 | assert rc == 0 |
| 295 | pipeline_run.assert_called_once() |
| 296 | |
| 297 | |
| 298 | def test_key_set_but_base_unset_stays_local(monkeypatch): |
| 299 | """KTD-2 inertness: with only the key set (no LAST30DAYS_API_BASE), hosted |
| 300 | mode does not activate - the local engine runs and no HTTP is attempted. |
| 301 | This is the leak-proofing guarantee: a key alone can never phone anywhere.""" |
| 302 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 303 | # LAST30DAYS_API_BASE deliberately left unset by the _clean_env fixture. |
| 304 | |
| 305 | def no_hosted(*args, **kwargs): # pragma: no cover - failure path |
| 306 | raise AssertionError("remote path must not run without LAST30DAYS_API_BASE") |
| 307 | |
| 308 | def no_http(*args, **kwargs): # pragma: no cover - failure path |
| 309 | raise AssertionError(f"unexpected HTTP call when base is unset: {args}") |
| 310 | |
| 311 | monkeypatch.setattr(hosted, "run_hosted", no_hosted) |
| 312 | monkeypatch.setattr(http, "request", no_http) |
| 313 | |
| 314 | fake_progress = mock.Mock() |
| 315 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 316 | mock.patch.object(cli.pipeline, "diagnose", return_value=DIAG), \ |
| 317 | mock.patch.object(cli.pipeline, "run", return_value=make_report()) as pipeline_run, \ |
| 318 | mock.patch.object(cli.ui, "ProgressDisplay", return_value=fake_progress), \ |
| 319 | mock.patch.object(cli, "emit_output", return_value="# local rendered"): |
| 320 | rc, out, _err = run_main(["test", "topic"]) |
| 321 | |
| 322 | assert rc == 0 |
| 323 | pipeline_run.assert_called_once() |
| 324 | assert "# local rendered" in out |
| 325 | |
| 326 | |
| 327 | # --------------------------------------------------------------------------- |
| 328 | # Remote client: submit -> poll -> complete |
| 329 | # --------------------------------------------------------------------------- |
| 330 | |
| 331 | |
| 332 | @pytest.fixture() |
| 333 | def remote_env(monkeypatch): |
| 334 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 335 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 336 | monkeypatch.setattr(hosted.time, "sleep", lambda _s: None) |
| 337 | |
| 338 | |
| 339 | @pytest.mark.parametrize( |
| 340 | ("flags", "reported_flag"), |
| 341 | [ |
| 342 | (["--days=30"], "--days"), |
| 343 | (["--lookback-days=7"], "--lookback-days"), |
| 344 | (["--as-of=2026-05-13"], "--as-of"), |
| 345 | (["--search=reddit"], "--search"), |
| 346 | (["--hiring-signals"], "--hiring-signals"), |
| 347 | (["--company=Widget Co"], "--company"), |
| 348 | (["--ticker=WDGT:Widget Co"], "--ticker"), |
| 349 | (["--jobs-board=https://jobs.example.test/widget"], "--jobs-board"), |
| 350 | (["--x-handle=widget"], "--x-handle"), |
| 351 | (["--plan", json.dumps(schema.to_dict(make_report("widget").query_plan))], "--plan"), |
| 352 | (["--competitors"], "--competitors"), |
| 353 | (["--competitors-list=Peer A,Peer B"], "--competitors-list"), |
| 354 | (["--competitors-plan", "{}"], "--competitors-plan"), |
| 355 | (["--emit=html"], "--emit=html"), |
| 356 | (["--x-handle=widget", "--search=reddit"], "--x-handle, --search"), |
| 357 | ], |
| 358 | ) |
| 359 | def test_hosted_cli_rejects_unapplied_options_before_submitting( |
| 360 | remote_env, monkeypatch, flags, reported_flag, |
| 361 | ): |
| 362 | post = mock.Mock(return_value=SUBMIT_OK) |
| 363 | get = mock.Mock(return_value=POLL_COMPLETE) |
| 364 | monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: {}) |
| 365 | monkeypatch.setattr(hosted.http, "post", post) |
| 366 | monkeypatch.setattr(hosted.http, "get", get) |
| 367 | |
| 368 | rc, out, err = run_main(["widget", *flags]) |
| 369 | |
| 370 | post.assert_not_called() |
| 371 | get.assert_not_called() |
| 372 | assert rc == 2 |
| 373 | assert out == "" |
| 374 | assert reported_flag in err |
| 375 | assert "hosted backend" in err |
| 376 | |
| 377 | |
| 378 | @pytest.mark.parametrize("form", [("--as-of=2026-11-13",), ("--as-of", "2026-11-14")]) |
| 379 | def test_hosted_cli_rejects_explicit_today_before_submitting(remote_env, monkeypatch, form): |
| 380 | local_now = datetime(2026, 11, 13, 17, tzinfo=timezone(timedelta(hours=-8))) |
| 381 | monkeypatch.setattr(cli.dates, "_local_now", lambda: local_now) |
| 382 | monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: {}) |
| 383 | post = mock.Mock(return_value=SUBMIT_OK) |
| 384 | monkeypatch.setattr(hosted.http, "post", post) |
| 385 | monkeypatch.setattr(hosted.http, "get", mock.Mock(return_value=POLL_COMPLETE)) |
| 386 | |
| 387 | rc, out, err = run_main(["Nvidia", *form]) |
| 388 | |
| 389 | post.assert_not_called() |
| 390 | assert rc == 2 |
| 391 | assert out == "" |
| 392 | assert "--as-of" in err |
| 393 | assert "hosted backend" in err |
| 394 | |
| 395 | |
| 396 | @pytest.mark.parametrize("topic", ["Nvidia vs AMD", "Nvidia compared to AMD"]) |
| 397 | def test_hosted_cli_rejects_comparison_before_submitting(remote_env, monkeypatch, topic): |
| 398 | monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: {}) |
| 399 | post = mock.Mock(return_value=SUBMIT_OK) |
| 400 | monkeypatch.setattr(hosted.http, "post", post) |
| 401 | monkeypatch.setattr(hosted.http, "get", mock.Mock(return_value=POLL_COMPLETE)) |
| 402 | |
| 403 | rc, out, err = run_main([topic]) |
| 404 | |
| 405 | post.assert_not_called() |
| 406 | assert rc == 2 |
| 407 | assert out == "" |
| 408 | assert "hosted backend cannot run comparisons" in err |
| 409 | assert "Run locally" in err |
| 410 | |
| 411 | |
| 412 | def test_hosted_cli_submits_supported_query_once(remote_env, monkeypatch, tmp_path): |
| 413 | save_dir = tmp_path / "saved" |
| 414 | post = mock.Mock(return_value=SUBMIT_OK) |
| 415 | get = mock.Mock(return_value=POLL_COMPLETE) |
| 416 | monkeypatch.setenv("CLAUDECODE", "1") |
| 417 | monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: {}) |
| 418 | monkeypatch.setattr(hosted.http, "post", post) |
| 419 | monkeypatch.setattr(hosted.http, "get", get) |
| 420 | |
| 421 | rc, out, _err = run_main([ |
| 422 | "Nvidia", "--register=exec", "--save-dir", str(save_dir), |
| 423 | ]) |
| 424 | |
| 425 | assert rc == 0 |
| 426 | assert "Synthesized report body." in out |
| 427 | post.assert_called_once() |
| 428 | assert post.call_args.kwargs["json_data"] == { |
| 429 | "query": "Nvidia", "depth": "default", "register": "exec", |
| 430 | } |
| 431 | get.assert_called_once() |
| 432 | assert (save_dir / "nvidia-raw.md").read_text(encoding="utf-8") == POLL_COMPLETE["raw_markdown"] |
| 433 | |
| 434 | |
| 435 | @pytest.mark.parametrize( |
| 436 | ("flags", "config", "backend"), |
| 437 | [ |
| 438 | ([], {}, "hosted"), |
| 439 | (["--mock"], {}, "local"), |
| 440 | (["--deep-research"], {}, "local"), |
| 441 | (["--corpus=/local-notes"], {}, "local"), |
| 442 | ([], {"LAST30DAYS_CORPUS_DIRS": "/local-notes"}, "local"), |
| 443 | (["--perplexity-search-type=fast"], {}, "hosted"), |
| 444 | (["--perplexity-search-type=fast"], {"PERPLEXITY_API_KEY": "dummy-perplexity"}, "local"), |
| 445 | ], |
| 446 | ) |
| 447 | def test_diagnose_identifies_research_backend(remote_env, monkeypatch, flags, config, backend): |
| 448 | monkeypatch.setattr(cli.env, "get_config", lambda **kwargs: dict(config)) |
| 449 | monkeypatch.setattr(cli.pipeline, "diagnose", lambda *args, **kwargs: {"available_sources": []}) |
| 450 | post = mock.Mock() |
| 451 | monkeypatch.setattr(hosted.http, "post", post) |
| 452 | |
| 453 | rc, out, _err = run_main(["--diagnose", "--include-research-backend", *flags]) |
| 454 | |
| 455 | assert rc == 0 |
| 456 | assert json.loads(out) == {"available_sources": [], "research_backend": backend} |
| 457 | post.assert_not_called() |
| 458 | |
| 459 | |
| 460 | def test_include_research_backend_requires_diagnose(remote_env, monkeypatch, capsys): |
| 461 | post = mock.Mock() |
| 462 | monkeypatch.setattr(hosted.http, "post", post) |
| 463 | monkeypatch.setattr(sys, "argv", ["last30days.py", "Nvidia", "--include-research-backend"]) |
| 464 | |
| 465 | with pytest.raises(SystemExit) as error: |
| 466 | cli.main() |
| 467 | |
| 468 | captured = capsys.readouterr() |
| 469 | assert error.value.code == 2 |
| 470 | assert captured.out == "" |
| 471 | assert "--include-research-backend requires --diagnose" in captured.err |
| 472 | post.assert_not_called() |
| 473 | |
| 474 | |
| 475 | def test_happy_path_submit_poll_complete(remote_env, monkeypatch, capsys): |
| 476 | posts, gets = [], [] |
| 477 | |
| 478 | def fake_post(url, json_data, headers=None, **kwargs): |
| 479 | posts.append({"url": url, "json": json_data, "headers": headers}) |
| 480 | return dict(SUBMIT_OK) |
| 481 | |
| 482 | poll_rows = [dict(POLL_RUNNING), dict(POLL_RUNNING), dict(POLL_COMPLETE)] |
| 483 | |
| 484 | def fake_get(url, headers=None, params=None, **kwargs): |
| 485 | gets.append({"url": url, "headers": headers, "params": params}) |
| 486 | return poll_rows.pop(0) |
| 487 | |
| 488 | monkeypatch.setattr(hosted.http, "post", fake_post) |
| 489 | monkeypatch.setattr(hosted.http, "get", fake_get) |
| 490 | |
| 491 | rc = hosted.run_hosted("test topic", "default", emit="compact", |
| 492 | save_dir=None, save_suffix="") |
| 493 | out = capsys.readouterr().out |
| 494 | |
| 495 | assert rc == 0 |
| 496 | # Contract: submit |
| 497 | assert posts == [{ |
| 498 | "url": f"{TEST_BASE}/search", |
| 499 | "json": {"query": "test topic", "depth": "default"}, |
| 500 | "headers": {"Authorization": f"Bearer {TEST_KEY}"}, |
| 501 | }] |
| 502 | # Contract: poll same auth, id param |
| 503 | assert all(g["url"] == f"{TEST_BASE}/search" for g in gets) |
| 504 | assert all(g["params"] == {"id": SEARCH_ID} for g in gets) |
| 505 | assert all(g["headers"] == {"Authorization": f"Bearer {TEST_KEY}"} for g in gets) |
| 506 | assert len(gets) == 3 |
| 507 | # Synthesis rendered on stdout |
| 508 | assert "Synthesized report body." in out |
| 509 | |
| 510 | |
| 511 | def test_happy_path_narration_printed_once_and_no_key_echo(remote_env, monkeypatch, capsys): |
| 512 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 513 | poll_rows = [dict(POLL_RUNNING), dict(POLL_RUNNING), dict(POLL_COMPLETE)] |
| 514 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: poll_rows.pop(0)) |
| 515 | |
| 516 | rc = hosted.run_hosted("test topic", "default", emit="compact", |
| 517 | save_dir=None, save_suffix="") |
| 518 | captured = capsys.readouterr() |
| 519 | |
| 520 | assert rc == 0 |
| 521 | # Each narration step printed exactly once even though the stderr blob |
| 522 | # was returned twice by consecutive polls. |
| 523 | assert captured.err.count("[narrate] step=planning queries") == 1 |
| 524 | assert captured.err.count("[narrate] step=searching sources") == 1 |
| 525 | # Progress line with elapsed/eta shape |
| 526 | assert "eta" in captured.err |
| 527 | # The API key never appears anywhere in output. |
| 528 | assert TEST_KEY not in captured.out |
| 529 | assert TEST_KEY not in captured.err |
| 530 | |
| 531 | |
| 532 | def test_save_dir_writes_raw_markdown(remote_env, monkeypatch, capsys, tmp_path): |
| 533 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 534 | poll_rows = [dict(POLL_COMPLETE)] |
| 535 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: poll_rows.pop(0)) |
| 536 | |
| 537 | rc = hosted.run_hosted("Test Topic!", "default", emit="compact", |
| 538 | save_dir=str(tmp_path), save_suffix="") |
| 539 | captured = capsys.readouterr() |
| 540 | |
| 541 | assert rc == 0 |
| 542 | saved = tmp_path / "test-topic-raw.md" |
| 543 | assert saved.exists() |
| 544 | assert "# Raw markdown" in saved.read_text(encoding="utf-8") |
| 545 | assert "Saved output to" in captured.err |
| 546 | assert TEST_KEY not in captured.err |
| 547 | |
| 548 | |
| 549 | def test_save_dir_shortens_a_long_topic_like_the_local_save( |
| 550 | remote_env, monkeypatch, capsys, tmp_path, |
| 551 | ): |
| 552 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 553 | poll_rows = [dict(POLL_COMPLETE)] |
| 554 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: poll_rows.pop(0)) |
| 555 | long_topic = "multi model comparison across providers and pricing tiers " * 8 |
| 556 | |
| 557 | rc = hosted.run_hosted(long_topic, "default", emit="compact", |
| 558 | save_dir=str(tmp_path), save_suffix="") |
| 559 | capsys.readouterr() |
| 560 | |
| 561 | assert rc == 0 |
| 562 | saved = tmp_path / f"{cli.slugify(long_topic)}-raw.md" |
| 563 | assert saved.exists() |
| 564 | assert "# Raw markdown" in saved.read_text(encoding="utf-8") |
| 565 | |
| 566 | |
| 567 | def test_save_dir_uses_unique_dated_fallback(remote_env, monkeypatch, capsys, tmp_path): |
| 568 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 569 | poll_rows = [dict(POLL_COMPLETE)] |
| 570 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: poll_rows.pop(0)) |
| 571 | today = datetime.now().strftime("%Y-%m-%d") |
| 572 | base = tmp_path / "test-topic-raw.md" |
| 573 | dated = tmp_path / f"test-topic-raw-{today}.md" |
| 574 | base.write_text("base content", encoding="utf-8") |
| 575 | dated.write_text("dated content", encoding="utf-8") |
| 576 | |
| 577 | rc = hosted.run_hosted("Test Topic!", "default", emit="compact", |
| 578 | save_dir=str(tmp_path), save_suffix="") |
| 579 | captured = capsys.readouterr() |
| 580 | |
| 581 | saved = tmp_path / f"test-topic-raw-{today}-1.md" |
| 582 | assert rc == 0 |
| 583 | assert saved.exists() |
| 584 | assert "# Raw markdown" in saved.read_text(encoding="utf-8") |
| 585 | assert base.read_text(encoding="utf-8") == "base content" |
| 586 | assert dated.read_text(encoding="utf-8") == "dated content" |
| 587 | assert f"Saved output to {saved.resolve()}" in captured.err |
| 588 | assert TEST_KEY not in captured.err |
| 589 | |
| 590 | |
| 591 | # --------------------------------------------------------------------------- |
| 592 | # Save-suffix sanitization: --save-suffix must never shape the path |
| 593 | # --------------------------------------------------------------------------- |
| 594 | |
| 595 | |
| 596 | @pytest.mark.parametrize( |
| 597 | ("suffix", "expected_name"), |
| 598 | [ |
| 599 | pytest.param("../../evil", "test-topic-raw-evil.md", id="parent-ref"), |
| 600 | pytest.param("/var/tmp/evil", "test-topic-raw-var-tmp-evil.md", id="abs-path"), |
| 601 | pytest.param("Report V3", "test-topic-raw-report-v3.md", id="mixed-case"), |
| 602 | pytest.param("GEMINI-DEEP", "test-topic-raw-gemini-deep.md", id="upper"), |
| 603 | pytest.param("", "test-topic-raw.md", id="empty"), |
| 604 | pytest.param("...?!..", "test-topic-raw.md", id="punct-only-drops"), |
| 605 | pytest.param("-edge-", "test-topic-raw-edge.md", id="edge-hyphens"), |
| 606 | ], |
| 607 | ) |
| 608 | def test_save_suffix_sanitized_stays_in_save_dir( |
| 609 | remote_env, monkeypatch, capsys, tmp_path, suffix, expected_name |
| 610 | ): |
| 611 | """Whatever --save-suffix holds, the saved file lands directly under the |
| 612 | requested save dir with a [a-z0-9-] suffix token (or none at all).""" |
| 613 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 614 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: dict(POLL_COMPLETE)) |
| 615 | |
| 616 | rc = hosted.run_hosted("Test Topic!", "default", emit="compact", |
| 617 | save_dir=str(tmp_path), save_suffix=suffix) |
| 618 | captured = capsys.readouterr() |
| 619 | |
| 620 | assert rc == 0 |
| 621 | assert [saved_path.name for saved_path in tmp_path.iterdir()] == [expected_name] |
| 622 | saved = tmp_path / expected_name |
| 623 | # Directly under the requested save directory - no separators, no `..`. |
| 624 | assert saved.is_file() |
| 625 | assert saved.resolve().parent == tmp_path.resolve() |
| 626 | assert "# Raw markdown" in saved.read_text(encoding="utf-8") |
| 627 | assert f"Saved output to {saved.resolve()}" in captured.err |
| 628 | assert TEST_KEY not in captured.err |
| 629 | |
| 630 | |
| 631 | def test_save_suffix_collision_falls_back_to_dated_sanitized_name( |
| 632 | remote_env, monkeypatch, capsys, tmp_path |
| 633 | ): |
| 634 | """Collision fallback still applies once the suffix is sanitized: hostile |
| 635 | '../Report V3' -> '-report-v3', and pre-existing files keep their content.""" |
| 636 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 637 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: dict(POLL_COMPLETE)) |
| 638 | today = datetime.now().strftime("%Y-%m-%d") |
| 639 | base = tmp_path / "test-topic-raw-report-v3.md" |
| 640 | dated = tmp_path / f"test-topic-raw-report-v3-{today}.md" |
| 641 | base.write_text("prior base", encoding="utf-8") |
| 642 | dated.write_text("prior dated", encoding="utf-8") |
| 643 | |
| 644 | rc = hosted.run_hosted("Test Topic!", "default", emit="compact", |
| 645 | save_dir=str(tmp_path), save_suffix="../Report V3") |
| 646 | captured = capsys.readouterr() |
| 647 | |
| 648 | saved = tmp_path / f"test-topic-raw-report-v3-{today}-1.md" |
| 649 | assert rc == 0 |
| 650 | assert saved.exists() |
| 651 | assert saved.resolve().parent == tmp_path.resolve() |
| 652 | assert "# Raw markdown" in saved.read_text(encoding="utf-8") |
| 653 | assert base.read_text(encoding="utf-8") == "prior base" |
| 654 | assert dated.read_text(encoding="utf-8") == "prior dated" |
| 655 | assert f"Saved output to {saved.resolve()}" in captured.err |
| 656 | assert TEST_KEY not in captured.err |
| 657 | |
| 658 | |
| 659 | def test_api_base_override(remote_env, monkeypatch, capsys): |
| 660 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://staging.example.dev/api/v1/") |
| 661 | urls = [] |
| 662 | |
| 663 | def fake_post(url, json_data, headers=None, **kwargs): |
| 664 | urls.append(url) |
| 665 | return dict(SUBMIT_OK) |
| 666 | |
| 667 | monkeypatch.setattr(hosted.http, "post", fake_post) |
| 668 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: dict(POLL_COMPLETE)) |
| 669 | |
| 670 | rc = hosted.run_hosted("test topic", "quick", emit="compact", |
| 671 | save_dir=None, save_suffix="") |
| 672 | capsys.readouterr() |
| 673 | assert rc == 0 |
| 674 | assert urls == ["https://staging.example.dev/api/v1/search"] |
| 675 | |
| 676 | |
| 677 | @pytest.mark.parametrize("base", [ |
| 678 | TEST_BASE, |
| 679 | "http://localhost:8080/api/v1", |
| 680 | "http://127.0.0.1:8080/api/v1", |
| 681 | "http://[::1]:8080/api/v1", |
| 682 | ]) |
| 683 | def test_api_base_allows_https_and_loopback_http(remote_env, monkeypatch, base): |
| 684 | monkeypatch.setenv("LAST30DAYS_API_BASE", base) |
| 685 | with mock.patch.object(hosted.http, "post", return_value=SUBMIT_OK) as post, \ |
| 686 | mock.patch.object(hosted.http, "get", return_value=POLL_COMPLETE) as get: |
| 687 | assert hosted.run_hosted("test topic", "quick") == 0 |
| 688 | |
| 689 | assert post.call_args.args == (f"{base}/search",) |
| 690 | assert get.call_args.args == (f"{base}/search",) |
| 691 | assert post.call_args.kwargs["headers"] == {"Authorization": f"Bearer {TEST_KEY}"} |
| 692 | assert get.call_args.kwargs["headers"] == {"Authorization": f"Bearer {TEST_KEY}"} |
| 693 | |
| 694 | |
| 695 | @pytest.mark.parametrize("base", [ |
| 696 | "http://remote.example.test/api/v1", |
| 697 | f"http://remote.example.test/{TEST_KEY}", |
| 698 | "ftp://remote.example.test/api/v1", |
| 699 | ]) |
| 700 | def test_api_base_rejects_insecure_remote_without_request( |
| 701 | remote_env, monkeypatch, capsys, base, |
| 702 | ): |
| 703 | monkeypatch.setenv("LAST30DAYS_API_BASE", base) |
| 704 | with mock.patch.object(hosted.http, "post", return_value=SUBMIT_OK) as post, \ |
| 705 | mock.patch.object(hosted.http, "get", return_value=POLL_COMPLETE) as get: |
| 706 | rc = hosted.run_hosted("test topic", "quick") |
| 707 | |
| 708 | captured = capsys.readouterr() |
| 709 | post.assert_not_called() |
| 710 | get.assert_not_called() |
| 711 | assert rc == 1 |
| 712 | assert "LAST30DAYS_API_BASE" in captured.err |
| 713 | assert "https://" in captured.err |
| 714 | assert "loopback" in captured.err |
| 715 | assert TEST_KEY not in captured.out + captured.err |
| 716 | |
| 717 | |
| 718 | @pytest.mark.parametrize("operation", ["submit", "poll"]) |
| 719 | def test_direct_hosted_requests_reject_insecure_remote(remote_env, monkeypatch, operation): |
| 720 | monkeypatch.setenv("LAST30DAYS_API_BASE", "http://remote.example.test/api/v1") |
| 721 | with mock.patch.object(hosted.http, "post") as post, \ |
| 722 | mock.patch.object(hosted.http, "get") as get: |
| 723 | with pytest.raises(ValueError, match="LAST30DAYS_API_BASE.*https://") as exc: |
| 724 | if operation == "submit": |
| 725 | hosted.submit("test topic", "quick") |
| 726 | else: |
| 727 | hosted.poll(SEARCH_ID) |
| 728 | |
| 729 | post.assert_not_called() |
| 730 | get.assert_not_called() |
| 731 | assert TEST_KEY not in str(exc.value) |
| 732 | |
| 733 | |
| 734 | # --------------------------------------------------------------------------- |
| 735 | # Error handling |
| 736 | # --------------------------------------------------------------------------- |
| 737 | |
| 738 | |
| 739 | def test_401_invalid_or_revoked_key(remote_env, monkeypatch, capsys): |
| 740 | def fake_post(*a, **k): |
| 741 | raise http.HTTPError("HTTP 401: Unauthorized", 401, |
| 742 | json.dumps({"error": "Invalid API key"})) |
| 743 | |
| 744 | monkeypatch.setattr(hosted.http, "post", fake_post) |
| 745 | rc = hosted.run_hosted("test topic", "default", emit="compact", |
| 746 | save_dir=None, save_suffix="") |
| 747 | captured = capsys.readouterr() |
| 748 | assert rc == 1 |
| 749 | assert "invalid or revoked" in captured.err.lower() |
| 750 | assert TEST_KEY not in captured.err |
| 751 | |
| 752 | |
| 753 | def test_402_shows_balance_needed_and_billing_url(remote_env, monkeypatch, capsys): |
| 754 | body = {"error": "Insufficient credits", "requires_credits": True, |
| 755 | "balance": 40, "needed": 200} |
| 756 | |
| 757 | def fake_post(*a, **k): |
| 758 | raise http.HTTPError("HTTP 402: Payment Required", 402, json.dumps(body)) |
| 759 | |
| 760 | monkeypatch.setattr(hosted.http, "post", fake_post) |
| 761 | rc = hosted.run_hosted("test topic", "deep", emit="compact", |
| 762 | save_dir=None, save_suffix="") |
| 763 | captured = capsys.readouterr() |
| 764 | assert rc == 1 |
| 765 | # Balance and needed shown verbatim from the API response. |
| 766 | assert "40" in captured.err |
| 767 | assert "200" in captured.err |
| 768 | # Billing link is derived from the configured base (base minus /api/v1, |
| 769 | # plus /dashboard/billing) - never hardcoded. |
| 770 | assert "https://api.example.test/dashboard/billing" in captured.err |
| 771 | assert TEST_KEY not in captured.err |
| 772 | |
| 773 | |
| 774 | def test_429_rate_limited(remote_env, monkeypatch, capsys): |
| 775 | def fake_post(*a, **k): |
| 776 | raise http.HTTPError("HTTP 429: Too Many Requests", 429, |
| 777 | json.dumps({"error": "Rate limit exceeded"})) |
| 778 | |
| 779 | monkeypatch.setattr(hosted.http, "post", fake_post) |
| 780 | rc = hosted.run_hosted("test topic", "default", emit="compact", |
| 781 | save_dir=None, save_suffix="") |
| 782 | captured = capsys.readouterr() |
| 783 | assert rc == 1 |
| 784 | assert "rate limit" in captured.err.lower() |
| 785 | |
| 786 | |
| 787 | def test_clarify_response_prints_question_options_distinct_exit(remote_env, monkeypatch, capsys): |
| 788 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(CLARIFY_RESPONSE)) |
| 789 | |
| 790 | def no_get(*a, **k): # pragma: no cover - failure path |
| 791 | raise AssertionError("must not poll on clarify") |
| 792 | |
| 793 | monkeypatch.setattr(hosted.http, "get", no_get) |
| 794 | rc = hosted.run_hosted("mercury", "default", emit="compact", |
| 795 | save_dir=None, save_suffix="") |
| 796 | captured = capsys.readouterr() |
| 797 | assert rc == hosted.EXIT_CLARIFY |
| 798 | assert rc not in (0, 1) |
| 799 | assert "Which 'mercury' do you mean?" in captured.err |
| 800 | assert "Mercury the planet" in captured.err |
| 801 | assert "Mercury the band" in captured.err |
| 802 | assert "re-run" in captured.err.lower() |
| 803 | |
| 804 | |
| 805 | def test_error_status_run_prints_server_message(remote_env, monkeypatch, capsys): |
| 806 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 807 | error_row = {"id": SEARCH_ID, "status": "error", |
| 808 | "error": "Synthesis failed upstream"} |
| 809 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: dict(error_row)) |
| 810 | rc = hosted.run_hosted("test topic", "default", emit="compact", |
| 811 | save_dir=None, save_suffix="") |
| 812 | captured = capsys.readouterr() |
| 813 | assert rc == 1 |
| 814 | assert "Synthesis failed upstream" in captured.err |
| 815 | |
| 816 | |
| 817 | def test_network_timeout_mid_poll_retries_get(remote_env, monkeypatch, capsys): |
| 818 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 819 | attempts = [] |
| 820 | |
| 821 | def flaky_get(*a, **k): |
| 822 | attempts.append(1) |
| 823 | if len(attempts) < 3: |
| 824 | raise http.HTTPError("Connection error: TimeoutError: timed out") |
| 825 | return dict(POLL_COMPLETE) |
| 826 | |
| 827 | monkeypatch.setattr(hosted.http, "get", flaky_get) |
| 828 | rc = hosted.run_hosted("test topic", "default", emit="compact", |
| 829 | save_dir=None, save_suffix="") |
| 830 | captured = capsys.readouterr() |
| 831 | assert rc == 0 |
| 832 | assert len(attempts) == 3 |
| 833 | assert "Synthesized report body." in captured.out |
| 834 | |
| 835 | |
| 836 | def test_persistent_network_failure_gives_up_with_message(remote_env, monkeypatch, capsys): |
| 837 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 838 | |
| 839 | def dead_get(*a, **k): |
| 840 | raise http.HTTPError("Connection error: TimeoutError: timed out") |
| 841 | |
| 842 | monkeypatch.setattr(hosted.http, "get", dead_get) |
| 843 | rc = hosted.run_hosted("test topic", "default", emit="compact", |
| 844 | save_dir=None, save_suffix="") |
| 845 | captured = capsys.readouterr() |
| 846 | assert rc == 1 |
| 847 | assert "poll" in captured.err.lower() |
| 848 | assert TEST_KEY not in captured.err |
| 849 | |
| 850 | |
| 851 | def test_emit_json_prints_terminal_row_without_stderr(remote_env, monkeypatch, capsys, tmp_path): |
| 852 | terminal = { |
| 853 | **POLL_COMPLETE, |
| 854 | "stderr": f"PRIVATE-STDERR-{tmp_path.name}", |
| 855 | "internal_trace": f"PRIVATE-TRACE-{tmp_path.name}", |
| 856 | } |
| 857 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 858 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: dict(terminal)) |
| 859 | rc = hosted.run_hosted("test topic", "default", emit="json", |
| 860 | save_dir=None, save_suffix="") |
| 861 | captured = capsys.readouterr() |
| 862 | assert rc == 0 |
| 863 | payload = json.loads(captured.out) |
| 864 | assert payload == { |
| 865 | "id": SEARCH_ID, |
| 866 | "status": "complete", |
| 867 | "synthesis_text": "## What happened\nSynthesized report body.", |
| 868 | "raw_markdown": "# Raw markdown\nFull dump.", |
| 869 | } |
| 870 | assert terminal["stderr"] not in captured.out |
| 871 | assert terminal["stderr"] not in captured.err |
| 872 | assert terminal["internal_trace"] not in captured.out |
| 873 | assert terminal["internal_trace"] not in captured.err |
| 874 | assert TEST_KEY not in captured.out |
| 875 | |
| 876 | |
| 877 | # --------------------------------------------------------------------------- |
| 878 | # Clarify round trip, failure reasons, engine version, proxy mode |
| 879 | # --------------------------------------------------------------------------- |
| 880 | |
| 881 | |
| 882 | CLARIFY_WITH_ANGLES = { |
| 883 | **CLARIFY_RESPONSE, |
| 884 | "angles": [ |
| 885 | {"label": "Mercury the planet", "query": "mercury planet news"}, |
| 886 | {"label": "Mercury the element", "query": "mercury element research"}, |
| 887 | {"label": "Mercury the band", "query": "mercury band tour"}, |
| 888 | ], |
| 889 | } |
| 890 | |
| 891 | |
| 892 | def test_clarify_prints_each_options_angle_query(remote_env, monkeypatch, capsys): |
| 893 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(CLARIFY_WITH_ANGLES)) |
| 894 | rc = hosted.run_hosted("mercury", "default", emit="compact", save_dir=None, save_suffix="") |
| 895 | err = capsys.readouterr().err |
| 896 | assert rc == hosted.EXIT_CLARIFY |
| 897 | assert '1. Mercury the planet (--clarify-angle "mercury planet news")' in err |
| 898 | assert "--clarify-broadly" in err |
| 899 | |
| 900 | |
| 901 | @pytest.mark.parametrize( |
| 902 | ("flags", "clarify"), |
| 903 | [ |
| 904 | (["--clarify-angle", "mercury planet news"], {"angle": "mercury planet news"}), |
| 905 | (["--clarify-broadly"], {"run_broadly": True}), |
| 906 | ], |
| 907 | ) |
| 908 | def test_clarify_rerun_sends_structured_clarify_without_default_register( |
| 909 | remote_env, monkeypatch, flags, clarify, |
| 910 | ): |
| 911 | payloads = [] |
| 912 | monkeypatch.setattr( |
| 913 | hosted.http, "post", |
| 914 | lambda _url, *, json_data, **_kwargs: payloads.append(json_data) or dict(SUBMIT_OK), |
| 915 | ) |
| 916 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: dict(POLL_COMPLETE)) |
| 917 | with mock.patch.object(cli.env, "get_config", return_value={}): |
| 918 | rc, out, _err = run_main(["mercury", *flags]) |
| 919 | |
| 920 | assert rc == 0 |
| 921 | assert payloads == [{"query": "mercury", "depth": "default", "clarify": clarify}] |
| 922 | assert "Synthesized report body." in out |
| 923 | |
| 924 | |
| 925 | def test_clarify_flags_are_rejected_outside_hosted_runs(monkeypatch): |
| 926 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 927 | mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("must not run")): |
| 928 | rc, _out, err = run_main(["mercury", "--clarify-broadly"]) |
| 929 | assert rc == 2 |
| 930 | assert "apply only to a hosted run" in err |
| 931 | |
| 932 | |
| 933 | def test_clarify_flags_are_mutually_exclusive(remote_env, monkeypatch): |
| 934 | with pytest.raises(SystemExit) as exc: |
| 935 | run_main(["mercury", "--clarify-broadly", "--clarify-angle", "x"]) |
| 936 | assert exc.value.code == 2 |
| 937 | |
| 938 | |
| 939 | def test_error_row_prints_synthesis_text_when_no_error_field(remote_env, monkeypatch, capsys): |
| 940 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 941 | error_row = {"id": SEARCH_ID, "status": "error", |
| 942 | "synthesis_text": "Every source timed out; no credits were charged."} |
| 943 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: dict(error_row)) |
| 944 | rc = hosted.run_hosted("test topic", "default", emit="compact", save_dir=None, save_suffix="") |
| 945 | err = capsys.readouterr().err |
| 946 | assert rc == 1 |
| 947 | assert "Every source timed out; no credits were charged." in err |
| 948 | assert "unknown server error" not in err |
| 949 | |
| 950 | |
| 951 | @pytest.mark.parametrize( |
| 952 | ("remote", "notices"), |
| 953 | [("3.38.1", 1), ("4.0.9", 0), (None, 0), ("unknown", 0)], |
| 954 | ) |
| 955 | def test_engine_version_skew_prints_one_notice(remote_env, monkeypatch, capsys, remote, notices): |
| 956 | monkeypatch.setattr(hosted, "_local_engine_version", lambda: "4.3.2") |
| 957 | monkeypatch.setattr(hosted.http, "post", lambda *a, **k: dict(SUBMIT_OK)) |
| 958 | row = dict(POLL_COMPLETE) |
| 959 | if remote is not None: |
| 960 | row["engine_version"] = remote |
| 961 | poll_rows = [dict(POLL_RUNNING, engine_version=remote), row] |
| 962 | monkeypatch.setattr(hosted.http, "get", lambda *a, **k: poll_rows.pop(0)) |
| 963 | rc = hosted.run_hosted("test topic", "default", emit="compact", save_dir=None, save_suffix="") |
| 964 | err = capsys.readouterr().err |
| 965 | assert rc == 0 |
| 966 | assert err.count("on the hosted backend; this skill is v4.3.2") == notices |
| 967 | |
| 968 | |
| 969 | def test_proxy_mode_keeps_the_run_local(monkeypatch): |
| 970 | monkeypatch.setenv("LAST30DAYS_API_KEY", TEST_KEY) |
| 971 | monkeypatch.setenv("LAST30DAYS_API_BASE", TEST_BASE) |
| 972 | monkeypatch.setenv("LAST30DAYS_API_MODE", "proxy") |
| 973 | monkeypatch.setattr( |
| 974 | hosted, "run_hosted", |
| 975 | lambda *a, **k: (_ for _ in ()).throw(AssertionError("hosted path must not run")), |
| 976 | ) |
| 977 | fake_progress = mock.Mock() |
| 978 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 979 | mock.patch.object(cli.pipeline, "diagnose", return_value=DIAG), \ |
| 980 | mock.patch.object(cli.pipeline, "run", return_value=make_report()) as pipeline_run, \ |
| 981 | mock.patch.object(cli.ui, "ProgressDisplay", return_value=fake_progress), \ |
| 982 | mock.patch.object(cli, "emit_output", return_value="# local rendered"): |
| 983 | rc, out, _err = run_main(["test", "topic", "--days=7"]) |
| 984 | |
| 985 | assert rc == 0 |
| 986 | pipeline_run.assert_called_once() |
| 987 | assert "# local rendered" in out |
| 988 |