| 1 | """U4: unified `doctor` command (lib/doctor.py + topic-word dispatch). |
| 2 | |
| 3 | Covers the plan's U4 scenarios: |
| 4 | 1. Fully keyless env -> free sources (reddit, hackernews, polymarket, |
| 5 | github) tier ok; key-gated sources tier off with prescriptions; exit 0. |
| 6 | 2. `--json` per-source shape for every registered source (chained and |
| 7 | single-backend), tier/status rollup rows asserted. |
| 8 | 3. One probe timing out -> that source status `timeout`, tier `error`, |
| 9 | all other sources still render (plus per-source exception isolation). |
| 10 | 4. No-secrets invariant: seeded fake credentials never appear in text or |
| 11 | JSON output. |
| 12 | 5. Topic-word dispatch: `doctor` triggers the report; a longer research |
| 13 | topic containing the word does not (setup's exact-match collision rule). |
| 14 | 6. Native-search host + no web keys -> web tier off with a host-native |
| 15 | note, never a false-alarm error. |
| 16 | """ |
| 17 | |
| 18 | import datetime |
| 19 | import io |
| 20 | import itertools |
| 21 | import json |
| 22 | import os |
| 23 | import re |
| 24 | import sys |
| 25 | import tempfile |
| 26 | import unittest |
| 27 | import urllib.error |
| 28 | from contextlib import redirect_stderr, redirect_stdout |
| 29 | from pathlib import Path |
| 30 | from unittest import mock |
| 31 | |
| 32 | import last30days as cli |
| 33 | from lib import backends, digg, doctor, env, grok_x, health, http, prescriptions, reddit_health, setup_wizard |
| 34 | |
| 35 | BIRD_STATUS_OFF = { |
| 36 | "installed": False, |
| 37 | "authenticated": False, |
| 38 | "username": None, |
| 39 | "can_install": True, |
| 40 | } |
| 41 | |
| 42 | # Obvious dummies only (repo security hygiene). |
| 43 | FAKE_SECRETS = { |
| 44 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 45 | "XAI_API_KEY": "dummy-xai-secret-000", |
| 46 | "BRAVE_API_KEY": "dummy-brave-secret-000", |
| 47 | "GROQ_API_KEY": "dummy-groq-secret-000", |
| 48 | "AUTH_TOKEN": "dummy-auth-token-secret-000", |
| 49 | "CT0": "dummy-ct0-secret-000", |
| 50 | "BSKY_HANDLE": "dummy.example.social", |
| 51 | "BSKY_APP_PASSWORD": "dummy-bsky-secret-000", |
| 52 | "TRUTHSOCIAL_TOKEN": "dummy-truth-secret-000", |
| 53 | "GITHUB_TOKEN": "dummy-github-secret-000", |
| 54 | "X_BEARER_TOKEN": "dummy-x-bearer-secret-000", |
| 55 | } |
| 56 | |
| 57 | VALID_TIERS = {"ok", "warn", "off", "error"} |
| 58 | VALID_STATUSES = { |
| 59 | "ok", "degraded", "opt-in", "unconfigured", "missing", "broken", "timeout", "error", |
| 60 | } |
| 61 | # The R1 rollup table, row by row. |
| 62 | TIER_BY_STATUS = { |
| 63 | "ok": "ok", |
| 64 | "degraded": "warn", |
| 65 | "opt-in": "off", |
| 66 | "unconfigured": "off", |
| 67 | "missing": "error", |
| 68 | "broken": "error", |
| 69 | "timeout": "error", |
| 70 | "error": "error", |
| 71 | } |
| 72 | |
| 73 | |
| 74 | def _probe_dep(status_map=None, default_status=health.MISSING): |
| 75 | """Fake health.probe_dependency honoring a per-name status map.""" |
| 76 | status_map = status_map or {} |
| 77 | |
| 78 | def fake(name, timeout=health.PROBE_TIMEOUT): |
| 79 | status = status_map.get(name, default_status) |
| 80 | if status == health.OK: |
| 81 | return health.DependencyProbe(name=name, status=health.OK, detail=f"{name} 1.0.0") |
| 82 | return health.DependencyProbe( |
| 83 | name=name, |
| 84 | status=status, |
| 85 | detail=f"{name} probe simulated {status}", |
| 86 | prescription=( |
| 87 | f"install {name}" if status == health.MISSING else f"reinstall {name}" |
| 88 | ), |
| 89 | owner_pkg_manager="brew", |
| 90 | ) |
| 91 | |
| 92 | return fake |
| 93 | |
| 94 | |
| 95 | class _Hermetic: |
| 96 | """Context manager stack making doctor runs machine-independent.""" |
| 97 | |
| 98 | def __init__(self, probe_map=None, default_status=health.MISSING): |
| 99 | # yt-dlp now backs YouTube comments (free, keyless), so the comment |
| 100 | # gate reads env.is_ytdlp_available() -> shutil.which on the real host. |
| 101 | # Pin it to the same yt-dlp the probe_map declares, or doctor's comment |
| 102 | # branch would silently depend on whether the dev box has yt-dlp. |
| 103 | ytdlp_ok = (probe_map or {}).get("yt-dlp", default_status) == health.OK |
| 104 | self._patches = [ |
| 105 | mock.patch("lib.health.probe_dependency", _probe_dep(probe_map, default_status)), |
| 106 | mock.patch("lib.env.is_ytdlp_available", return_value=ytdlp_ok), |
| 107 | # env.is_ytdlp_available() is a thin wrapper over |
| 108 | # youtube_yt.is_ytdlp_installed(). The keyless shortform fallback |
| 109 | # probe (is_shortform_oss_available) calls the youtube_yt symbol |
| 110 | # directly, so pin that one too or the result depends on whether |
| 111 | # the host actually has yt-dlp on PATH. |
| 112 | mock.patch("lib.youtube_yt.is_ytdlp_installed", return_value=ytdlp_ok), |
| 113 | # Never read the real digg-pp-cli's help text. Tests of an older |
| 114 | # Digg CLI override this. |
| 115 | mock.patch("lib.digg.cli_searches_all_topics", return_value=True), |
| 116 | mock.patch("lib.bird_x.is_bird_installed", return_value=False), |
| 117 | mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None), |
| 118 | mock.patch("lib.bird_x.get_bird_status", return_value=dict(BIRD_STATUS_OFF)), |
| 119 | # The doctor path is local-only for xurl: the live `xurl whoami` |
| 120 | # network check must never run (no-network guarantee). |
| 121 | mock.patch( |
| 122 | "lib.xurl_x.is_available", |
| 123 | side_effect=AssertionError( |
| 124 | "doctor path ran the live `xurl whoami` network check" |
| 125 | ), |
| 126 | ), |
| 127 | mock.patch("lib.xurl_x.has_stored_auth", return_value=False), |
| 128 | mock.patch( |
| 129 | "lib.xurl_x.stored_auth_status", |
| 130 | return_value=("missing", "no token store at ~/.xurl"), |
| 131 | ), |
| 132 | mock.patch("lib.backends.which", lambda name: None), |
| 133 | # Hermetic library: never glob the user's real saved-research dir. |
| 134 | # Tests that assert a specific brief count override this. |
| 135 | mock.patch("lib.doctor._count_saved_briefs", return_value=0), |
| 136 | # Hermetic run-evidence: never read the user's real last-report.json. |
| 137 | # Tests that inject run evidence override this with a temp file. |
| 138 | mock.patch("lib.doctor._last_report_path", return_value=None), |
| 139 | # Hermetic live probe: never make a real network call. Tests that |
| 140 | # exercise probing override this with canned results. |
| 141 | mock.patch("lib.doctor._probe_sources", return_value={}), |
| 142 | # FTS5 is present on CI/dev SQLite; pin it so the library record's |
| 143 | # branch is deterministic regardless of the host's SQLite build. |
| 144 | mock.patch("lib.library_index.fts5_available", return_value=True), |
| 145 | # Snapshot os.environ so the CLAUDECODE scrub below is restored on |
| 146 | # exit. The real test shell (Claude Code) sets CLAUDECODE=1, which |
| 147 | # would otherwise make doctor's host-native web detection fire in |
| 148 | # every test and mask the keyless-degraded path. Tests that want the |
| 149 | # host-native path pass CLAUDECODE explicitly in their config dict. |
| 150 | mock.patch.dict(os.environ, {}, clear=False), |
| 151 | ] |
| 152 | |
| 153 | def __enter__(self): |
| 154 | for p in self._patches: |
| 155 | p.start() |
| 156 | os.environ.pop("CLAUDECODE", None) |
| 157 | return self |
| 158 | |
| 159 | def __exit__(self, *exc): |
| 160 | for p in reversed(self._patches): |
| 161 | p.stop() |
| 162 | return False |
| 163 | |
| 164 | |
| 165 | def _build(config, **kwargs): |
| 166 | with _Hermetic(**kwargs): |
| 167 | return doctor.build_report(dict(config)) |
| 168 | |
| 169 | |
| 170 | def _run_cli_doctor(argv, config): |
| 171 | with _Hermetic(), \ |
| 172 | mock.patch.object(cli.env, "get_config", return_value=dict(config)), \ |
| 173 | mock.patch.object(sys, "argv", ["last30days.py"] + argv): |
| 174 | stdout = io.StringIO() |
| 175 | stderr = io.StringIO() |
| 176 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 177 | rc = cli.main() |
| 178 | return rc, stdout.getvalue() |
| 179 | |
| 180 | |
| 181 | class KeylessEnvironment(unittest.TestCase): |
| 182 | """Scenario 1: fully keyless env.""" |
| 183 | |
| 184 | def setUp(self): |
| 185 | self.report = _build({}) |
| 186 | |
| 187 | def test_free_sources_tier_ok(self): |
| 188 | for name in ("reddit", "hackernews", "polymarket", "github"): |
| 189 | self.assertEqual("ok", self.report["sources"][name]["tier"], name) |
| 190 | self.assertEqual("ok", self.report["sources"][name]["status"], name) |
| 191 | |
| 192 | def test_key_gated_sources_off_with_prescriptions(self): |
| 193 | for name in ("x", "tiktok", "instagram", "threads", "bluesky", "truthsocial"): |
| 194 | record = self.report["sources"][name] |
| 195 | self.assertEqual("off", record["tier"], name) |
| 196 | self.assertIn(record["status"], ("unconfigured", "opt-in"), name) |
| 197 | self.assertTrue(record["fix"], f"{name} must carry a fix prescription") |
| 198 | |
| 199 | def test_youtube_off_when_ytdlp_missing_and_no_key(self): |
| 200 | record = self.report["sources"]["youtube"] |
| 201 | self.assertEqual("off", record["tier"]) |
| 202 | self.assertEqual("unconfigured", record["status"]) |
| 203 | self.assertTrue(record["fix"]) |
| 204 | |
| 205 | def test_web_keyless_floor_is_degraded_not_error(self): |
| 206 | record = self.report["sources"]["web"] |
| 207 | self.assertEqual("warn", record["tier"]) |
| 208 | self.assertEqual("degraded", record["status"]) |
| 209 | self.assertEqual("keyless", record["active_backend"]) |
| 210 | |
| 211 | def test_cli_exit_code_zero_even_with_problems(self): |
| 212 | rc, out = _run_cli_doctor(["doctor"], {}) |
| 213 | self.assertEqual(0, rc) |
| 214 | self.assertIn("last30days doctor", out) |
| 215 | |
| 216 | |
| 217 | class PerplexityKeyBoundary(unittest.TestCase): |
| 218 | def test_openrouter_only_enables_sonar_fallback(self): |
| 219 | record = _build( |
| 220 | { |
| 221 | "OPENROUTER_API_KEY": "dummy-openrouter-secret-000", |
| 222 | "INCLUDE_SOURCES": "perplexity", |
| 223 | } |
| 224 | )["sources"]["perplexity"] |
| 225 | |
| 226 | self.assertEqual("ok", record["status"]) |
| 227 | self.assertIn("PERPLEXITY_API_KEY", record["requires"]) |
| 228 | self.assertIn("OPENROUTER_API_KEY", record["requires"]) |
| 229 | |
| 230 | def test_direct_perplexity_key_with_opt_in_is_ready(self): |
| 231 | record = _build( |
| 232 | { |
| 233 | "PERPLEXITY_API_KEY": "dummy-perplexity-secret-000", |
| 234 | "INCLUDE_SOURCES": "perplexity", |
| 235 | } |
| 236 | )["sources"]["perplexity"] |
| 237 | |
| 238 | self.assertEqual("ok", record["status"]) |
| 239 | |
| 240 | |
| 241 | class GitHubAuthDetection(unittest.TestCase): |
| 242 | """GitHub doctor auth must mirror the real fetcher token source.""" |
| 243 | |
| 244 | def test_github_env_token_without_gh_reports_authenticated_tier(self): |
| 245 | with mock.patch.dict("os.environ", {"GITHUB_TOKEN": "dummy-github-secret-000"}), \ |
| 246 | mock.patch("lib.doctor.shutil.which", return_value=None): |
| 247 | record = _build({})["sources"]["github"] |
| 248 | |
| 249 | self.assertEqual("ok", record["tier"]) |
| 250 | self.assertEqual("ok", record["status"]) |
| 251 | self.assertEqual("authenticated tier (GITHUB_TOKEN or gh CLI)", record["detail"]) |
| 252 | |
| 253 | def test_github_without_env_token_or_gh_reports_unauthenticated_tier(self): |
| 254 | with mock.patch.dict("os.environ", {"GITHUB_TOKEN": ""}), \ |
| 255 | mock.patch("lib.doctor.shutil.which", return_value=None): |
| 256 | record = _build({})["sources"]["github"] |
| 257 | |
| 258 | self.assertEqual("ok", record["tier"]) |
| 259 | self.assertEqual("ok", record["status"]) |
| 260 | self.assertIn("unauthenticated REST tier", record["detail"]) |
| 261 | |
| 262 | |
| 263 | class UnconfiguredXWithBrokenNode(unittest.TestCase): |
| 264 | """F9 repro: no X configuration + a broken node runtime must read as |
| 265 | off/unconfigured with the cookie fix on bird — never a configured-but- |
| 266 | broken error carrying a node prescription.""" |
| 267 | |
| 268 | def test_x_rolls_up_off_with_cookie_prescription(self): |
| 269 | report = _build({}, probe_map={"node": health.BROKEN}) |
| 270 | record = report["sources"]["x"] |
| 271 | self.assertEqual("off", record["tier"]) |
| 272 | self.assertEqual("unconfigured", record["status"]) |
| 273 | bird = next(b for b in record["backends"] if b["name"] == "bird") |
| 274 | self.assertEqual("missing", bird["status"]) |
| 275 | self.assertIn("cookie", (bird["detail"] + bird["fix"]).lower()) |
| 276 | self.assertNotIn("node", bird["fix"].lower()) |
| 277 | |
| 278 | |
| 279 | class CookieBackedXReadiness(unittest.TestCase): |
| 280 | """U2: when bird is installed and FROM_BROWSER will authenticate X at run |
| 281 | time, doctor reports X as Ready (not Off) with an honest, unverified note - |
| 282 | matching the real run behavior where browser cookies serve X fine even |
| 283 | though diagnose loads config in plan_only mode.""" |
| 284 | |
| 285 | def test_x_ready_when_bird_installed_and_from_browser(self): |
| 286 | with _Hermetic(probe_map={"node": health.OK}), mock.patch("lib.bird_x.is_bird_installed", return_value=True): |
| 287 | report = doctor.build_report({"FROM_BROWSER": "auto"}) |
| 288 | record = report["sources"]["x"] |
| 289 | self.assertEqual("ok", record["tier"]) |
| 290 | self.assertEqual("ok", record["status"]) |
| 291 | note = record["note"].lower() |
| 292 | self.assertIn("browser cookies", note) |
| 293 | self.assertIn("not verified", note) |
| 294 | self.assertIn("xai_api_key", note) |
| 295 | |
| 296 | def test_last_setup_permission_denial_overrides_unverified_cookie_prediction(self): |
| 297 | config = { |
| 298 | "FROM_BROWSER": "edge", "BROWSER_CONSENT": "true", |
| 299 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 300 | } |
| 301 | with _Hermetic(), mock.patch( |
| 302 | "lib.bird_x.is_bird_installed", return_value=True |
| 303 | ), mock.patch( |
| 304 | "lib.cookie_extract.extract_cookies", |
| 305 | side_effect=AssertionError("doctor read cookies"), |
| 306 | ): |
| 307 | record = doctor._x_record(config) |
| 308 | self.assertEqual("error", record["tier"]) |
| 309 | self.assertIn("Last setup", record["note"]) |
| 310 | self.assertIn("permission denied", record["note"]) |
| 311 | self.assertIn("AUTH_TOKEN", record["fix"]) |
| 312 | |
| 313 | def test_last_setup_denial_preserves_exclusive_xurl_pin_repair(self): |
| 314 | config = { |
| 315 | "LAST30DAYS_X_BACKEND": "xurl", |
| 316 | "FROM_BROWSER": "edge", "BROWSER_CONSENT": "true", |
| 317 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 318 | } |
| 319 | with _Hermetic(): |
| 320 | record = doctor._x_record(config) |
| 321 | self.assertTrue(record["pinned"]) |
| 322 | self.assertIn("xurl", record["fix"].lower()) |
| 323 | self.assertIn("Last setup", record["note"]) |
| 324 | |
| 325 | def test_discovery_stat_denial_reaches_setup_and_no_read_doctor(self): |
| 326 | with tempfile.TemporaryDirectory() as temp_dir: |
| 327 | profiles = Path(temp_dir) |
| 328 | profile = profiles / "default" |
| 329 | profile.mkdir() |
| 330 | blocked = profile / "cookies.sqlite" |
| 331 | blocked.touch() |
| 332 | real_stat = Path.stat |
| 333 | real_is_file = Path.is_file |
| 334 | |
| 335 | def guarded_stat(path, *args, **kwargs): |
| 336 | if path == blocked: |
| 337 | raise PermissionError(1, "Operation not permitted", str(path)) |
| 338 | return real_stat(path, *args, **kwargs) |
| 339 | |
| 340 | def simulated_py314_is_file(path, *args, **kwargs): |
| 341 | if path == blocked: |
| 342 | return False |
| 343 | return real_is_file(path, *args, **kwargs) |
| 344 | |
| 345 | with mock.patch("lib.cookie_extract._get_firefox_profiles_dir", return_value=profiles), mock.patch( |
| 346 | "lib.cookie_extract._is_wsl", return_value=False |
| 347 | ), mock.patch.object( |
| 348 | Path, "stat", guarded_stat |
| 349 | ), mock.patch.object(Path, "is_file", simulated_py314_is_file), mock.patch( |
| 350 | "lib.setup_wizard.shutil.which", return_value="/usr/bin/fake" |
| 351 | ), mock.patch("lib.setup_wizard._install_digg_cli", return_value=(True, "already_installed", "", "")), mock.patch( |
| 352 | "lib.setup_wizard.install_default_pp_sources", return_value={} |
| 353 | ), mock.patch("lib.setup_wizard.brightdata_status", return_value={}): |
| 354 | results = setup_wizard.run_auto_setup( |
| 355 | {"FROM_BROWSER": "firefox"}, allow_browser_cookies=True |
| 356 | ) |
| 357 | self.assertEqual(["firefox"], results["x_cookie_access_denied"], results) |
| 358 | self.assertIn("permission denied", setup_wizard.get_setup_status_text(results).lower()) |
| 359 | config = { |
| 360 | "FROM_BROWSER": "firefox", |
| 361 | "BROWSER_CONSENT": "true", |
| 362 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "firefox", |
| 363 | } |
| 364 | with _Hermetic(), mock.patch( |
| 365 | "lib.cookie_extract.extract_cookies", |
| 366 | side_effect=AssertionError("doctor read cookies"), |
| 367 | ): |
| 368 | record = doctor._x_record(config) |
| 369 | self.assertEqual("error", record["tier"]) |
| 370 | self.assertIn("Last setup", record["note"]) |
| 371 | |
| 372 | def test_manual_cookie_pair_supersedes_last_setup_denial(self): |
| 373 | config = { |
| 374 | "FROM_BROWSER": "edge", "BROWSER_CONSENT": "true", |
| 375 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 376 | "AUTH_TOKEN": "dummy-auth-token", "CT0": "dummy-ct0", |
| 377 | } |
| 378 | with _Hermetic(probe_map={"node": health.OK}), mock.patch( |
| 379 | "lib.bird_x.is_bird_installed", return_value=True |
| 380 | ): |
| 381 | record = doctor._x_record(config) |
| 382 | self.assertEqual("ok", record["tier"]) |
| 383 | self.assertNotIn("permission denied", record["note"]) |
| 384 | |
| 385 | def test_denial_after_auto_setup_is_visible_without_from_browser(self): |
| 386 | config = { |
| 387 | "BROWSER_CONSENT": "true", |
| 388 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 389 | } |
| 390 | with _Hermetic(), mock.patch( |
| 391 | "lib.cookie_extract.extract_cookies", |
| 392 | side_effect=AssertionError("doctor read cookies"), |
| 393 | ): |
| 394 | record = doctor._x_record(config) |
| 395 | self.assertEqual("error", record["tier"]) |
| 396 | self.assertIn("Last setup", record["note"]) |
| 397 | |
| 398 | def test_other_source_browser_selection_does_not_hide_x_denial(self): |
| 399 | config = { |
| 400 | "FROM_BROWSER": "chrome", "BROWSER_CONSENT": "true", |
| 401 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 402 | } |
| 403 | with _Hermetic(), mock.patch("lib.bird_x.is_bird_installed", return_value=True): |
| 404 | record = doctor._x_record(config) |
| 405 | self.assertEqual("error", record["tier"]) |
| 406 | self.assertIn("edge", record["note"]) |
| 407 | |
| 408 | def test_refused_browser_access_suppresses_old_denial_marker(self): |
| 409 | config = { |
| 410 | "FROM_BROWSER": "off", "BROWSER_CONSENT": "false", |
| 411 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 412 | } |
| 413 | with _Hermetic(): |
| 414 | record = doctor._x_record(config) |
| 415 | self.assertNotIn("permission denied", record.get("note", "")) |
| 416 | |
| 417 | def test_denial_marker_invalidates_cached_doctor_result(self): |
| 418 | before = doctor._config_fingerprint({"FROM_BROWSER": "edge"}) |
| 419 | after = doctor._config_fingerprint({ |
| 420 | "FROM_BROWSER": "edge", "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 421 | }) |
| 422 | assert before != after |
| 423 | |
| 424 | def test_x_stays_off_when_bird_installed_but_no_consent(self): |
| 425 | # bird installed but FROM_BROWSER=off -> no cookie path -> genuinely off. |
| 426 | with _Hermetic(), mock.patch("lib.bird_x.is_bird_installed", return_value=True): |
| 427 | report = doctor.build_report({"FROM_BROWSER": "off"}) |
| 428 | record = report["sources"]["x"] |
| 429 | self.assertEqual("off", record["tier"]) |
| 430 | self.assertEqual("unconfigured", record["status"]) |
| 431 | |
| 432 | def test_x_stays_off_when_consent_but_bird_missing(self): |
| 433 | # FROM_BROWSER set but bird not installed -> no runtime path -> off. |
| 434 | report = _build({"FROM_BROWSER": "auto"}) |
| 435 | record = report["sources"]["x"] |
| 436 | self.assertEqual("off", record["tier"]) |
| 437 | self.assertEqual("unconfigured", record["status"]) |
| 438 | |
| 439 | |
| 440 | class SidecarOptInHint(unittest.TestCase): |
| 441 | """A present, unadmitted sidecar has an actionable, no-cookie-read hint.""" |
| 442 | |
| 443 | def _record(self, config=None, *, present=True, system="Linux", probe_map=None): |
| 444 | with ( |
| 445 | _Hermetic(probe_map=probe_map), |
| 446 | mock.patch("platform.system", return_value=system), |
| 447 | mock.patch("lib.env._mac_model", return_value="MacBookPro18,2"), |
| 448 | mock.patch("lib.bird_x.is_bird_installed", return_value=True), |
| 449 | mock.patch("shutil.which", side_effect=lambda name: ( |
| 450 | "/mock/agentcookie" if name == "agentcookie" and present else None |
| 451 | )), |
| 452 | mock.patch("lib.agentcookie.read_x_cookies") as cookies, |
| 453 | mock.patch("subprocess.run") as run, |
| 454 | ): |
| 455 | record = doctor._x_record(dict(config or {})) |
| 456 | cookies.assert_not_called() |
| 457 | run.assert_not_called() |
| 458 | return record |
| 459 | |
| 460 | def test_present_unadmitted_sidecar_has_could_be_on_hint(self): |
| 461 | record = self._record() |
| 462 | self.assertEqual(doctor.AUDIT_COULD_BE_ON, doctor.audit_state("x", record)) |
| 463 | self.assertIsNone(record["active_backend"]) |
| 464 | self.assertIn("agentcookie", record["note"]) |
| 465 | self.assertIn("AGENTCOOKIE=on", record["fix"]) |
| 466 | line = doctor._audit_source_line("x", record, doctor.AUDIT_COULD_BE_ON) |
| 467 | self.assertIn("AGENTCOOKIE=on", line) |
| 468 | |
| 469 | def test_refusal_never_offers_sidecar_opt_in(self): |
| 470 | for config in ( |
| 471 | {"BROWSER_CONSENT": "false"}, |
| 472 | {"BROWSER_CONSENT": "unknown"}, |
| 473 | {"FROM_BROWSER": "off"}, |
| 474 | {"AGENTCOOKIE": "off"}, |
| 475 | ): |
| 476 | with self.subTest(config=config): |
| 477 | record = self._record(config) |
| 478 | self.assertNotIn("AGENTCOOKIE=on", record["fix"]) |
| 479 | |
| 480 | def test_absent_binary_or_non_extra_host_has_no_sidecar_hint(self): |
| 481 | for options in ({"present": False}, {"system": "Darwin"}): |
| 482 | with self.subTest(options=options): |
| 483 | self.assertNotIn("AGENTCOOKIE=on", self._record(**options)["fix"]) |
| 484 | |
| 485 | def test_admitted_sidecar_predicts_browser_auth_without_opt_in_hint(self): |
| 486 | record = self._record({"AGENTCOOKIE": "on"}, probe_map={"node": health.OK}) |
| 487 | self.assertEqual("ok", record["tier"]) |
| 488 | self.assertIn("not verified", record["note"]) |
| 489 | self.assertEqual("", record["fix"]) |
| 490 | |
| 491 | def test_backend_connector_and_pin_diagnoses_keep_precedence(self): |
| 492 | for config, active in ( |
| 493 | ({"XAI_API_KEY": "dummy-xai-key"}, "xai"), |
| 494 | ({"LAST30DAYS_X_HOST_LANE": "1"}, "connector"), |
| 495 | ({"LAST30DAYS_X_BACKEND": "xurl"}, None), |
| 496 | ({"LAST30DAYS_HOST": "grok-bot", "LAST30DAYS_X_BACKEND": "bird"}, None), |
| 497 | ): |
| 498 | with self.subTest(config=config): |
| 499 | record = self._record(config) |
| 500 | self.assertEqual(active, record["active_backend"]) |
| 501 | self.assertNotIn("AGENTCOOKIE=on", record["fix"]) |
| 502 | |
| 503 | def test_broken_configured_backend_keeps_its_repair(self): |
| 504 | record = self._record( |
| 505 | {"AUTH_TOKEN": "dummy-auth-token", "CT0": "dummy-ct0"}, |
| 506 | probe_map={"node": health.BROKEN}, |
| 507 | ) |
| 508 | self.assertEqual("broken", record["status"]) |
| 509 | self.assertIn("node", record["fix"]) |
| 510 | self.assertNotIn("AGENTCOOKIE=on", record["fix"]) |
| 511 | |
| 512 | |
| 513 | class LibraryDoctorLine(unittest.TestCase): |
| 514 | """U5: doctor reports the local research library so the report's |
| 515 | 'From your library' block is explained on the health surface.""" |
| 516 | |
| 517 | def test_library_reports_indexed_brief_count(self): |
| 518 | with _Hermetic(), mock.patch("lib.doctor._count_saved_briefs", return_value=3): |
| 519 | record = doctor.build_report({})["sources"]["library"] |
| 520 | self.assertEqual("ok", record["status"]) |
| 521 | self.assertIn("3 saved briefs", record["note"]) |
| 522 | |
| 523 | def test_library_empty_store_is_informational_ok(self): |
| 524 | record = _build({})["sources"]["library"] # count stubbed to 0 |
| 525 | self.assertEqual("ok", record["status"]) |
| 526 | self.assertIn("no saved briefs yet", record["note"]) |
| 527 | |
| 528 | def test_library_without_fts5_degrades_informationally(self): |
| 529 | # Inner patch overrides the _Hermetic FTS5 pin. |
| 530 | with _Hermetic(), mock.patch("lib.library_index.fts5_available", return_value=False): |
| 531 | record = doctor.build_report({})["sources"]["library"] |
| 532 | self.assertEqual("ok", record["status"]) |
| 533 | self.assertIn("FTS5", record["note"]) |
| 534 | |
| 535 | def test_library_scan_failure_is_informational_ok(self): |
| 536 | # A glob/OS error must never fail the run - it degrades to an OK line. |
| 537 | with _Hermetic(), mock.patch( |
| 538 | "lib.doctor._count_saved_briefs", side_effect=OSError("permission denied") |
| 539 | ): |
| 540 | record = doctor.build_report({})["sources"]["library"] |
| 541 | self.assertEqual("ok", record["status"]) |
| 542 | self.assertIn("local research library", record["note"]) |
| 543 | |
| 544 | def test_library_line_present_in_text_render(self): |
| 545 | text = doctor.render_text(_build({})) |
| 546 | self.assertTrue( |
| 547 | any("library" in l for l in text.splitlines()), |
| 548 | "doctor text output must carry a library line", |
| 549 | ) |
| 550 | |
| 551 | |
| 552 | class JsonShape(unittest.TestCase): |
| 553 | """Scenario 2: documented per-source shape for every registered source.""" |
| 554 | |
| 555 | def setUp(self): |
| 556 | self.report = _build(dict(FAKE_SECRETS)) |
| 557 | |
| 558 | def test_every_registered_source_present(self): |
| 559 | self.assertEqual(set(doctor.SOURCE_ORDER), set(self.report["sources"].keys())) |
| 560 | |
| 561 | def test_per_source_record_shape(self): |
| 562 | for name, record in self.report["sources"].items(): |
| 563 | for key in ("tier", "status", "backends", "mode", "active_backend", "fix", "requires"): |
| 564 | self.assertIn(key, record, f"{name} missing {key}") |
| 565 | self.assertIn(record["tier"], VALID_TIERS, name) |
| 566 | self.assertIn(record["status"], VALID_STATUSES, name) |
| 567 | |
| 568 | def test_tier_status_rollup_rows(self): |
| 569 | for name, record in self.report["sources"].items(): |
| 570 | self.assertEqual( |
| 571 | TIER_BY_STATUS[record["status"]], record["tier"], |
| 572 | f"{name}: status {record['status']} must roll up to " |
| 573 | f"{TIER_BY_STATUS[record['status']]}", |
| 574 | ) |
| 575 | |
| 576 | def test_chained_sources_expose_backends_and_mode(self): |
| 577 | for name in ("x", "youtube", "web"): |
| 578 | record = self.report["sources"][name] |
| 579 | self.assertEqual("alternative", record["mode"], name) |
| 580 | self.assertIsInstance(record["backends"], list, name) |
| 581 | self.assertTrue(record["backends"], name) |
| 582 | self.assertEqual("conditional", self.report["sources"]["reddit"]["mode"]) |
| 583 | self.assertIsInstance(self.report["sources"]["reddit"]["backends"], list) |
| 584 | |
| 585 | def test_single_backend_sources_have_single_mode(self): |
| 586 | for name in ("hackernews", "polymarket", "github", "bluesky"): |
| 587 | record = self.report["sources"][name] |
| 588 | self.assertEqual("single", record["mode"], name) |
| 589 | self.assertIsNone(record["backends"], name) |
| 590 | |
| 591 | def test_conditional_reddit_never_picks_a_winner(self): |
| 592 | record = self.report["sources"]["reddit"] |
| 593 | self.assertIsNone(record["active_backend"]) |
| 594 | # Conditional wording is U2's, verbatim. |
| 595 | with _Hermetic(): |
| 596 | expected = backends.resolve("reddit", dict(FAKE_SECRETS)).conditional |
| 597 | self.assertEqual(expected, record["note"]) |
| 598 | |
| 599 | def test_web_pin_is_flag_only_no_env_pin(self): |
| 600 | # Web search has NO env pin; only the --web-backend flag. |
| 601 | record = self.report["sources"]["web"] |
| 602 | self.assertIsNone(record["pin_var"]) |
| 603 | self.assertEqual("--web-backend", record["pin_flag"]) |
| 604 | |
| 605 | def test_chained_ok_source_predicts_will_use(self): |
| 606 | record = self.report["sources"]["web"] |
| 607 | self.assertEqual("ok", record["tier"]) |
| 608 | self.assertEqual("brave", record["active_backend"]) |
| 609 | self.assertIn("will use: brave", record["note"]) |
| 610 | |
| 611 | def test_top_level_block(self): |
| 612 | for key in ("engine_version", "config", "setup", "permissions", "sources"): |
| 613 | self.assertIn(key, self.report) |
| 614 | self.assertIsInstance(self.report["engine_version"], str) |
| 615 | self.assertTrue(self.report["engine_version"]) |
| 616 | setup = self.report["setup"] |
| 617 | self.assertIsInstance(setup["setup_complete"], bool) |
| 618 | for name, present in setup["keys_present"].items(): |
| 619 | self.assertIsInstance(present, bool, name) |
| 620 | self.assertIn("status", self.report["permissions"]) |
| 621 | |
| 622 | def test_json_renderer_round_trips(self): |
| 623 | payload = json.loads(doctor.render_json(self.report)) |
| 624 | self.assertEqual(set(doctor.SOURCE_ORDER), set(payload["sources"].keys())) |
| 625 | |
| 626 | |
| 627 | class ProbeFailureIsolation(unittest.TestCase): |
| 628 | """Scenario 3: one bad probe cannot blank the report.""" |
| 629 | |
| 630 | def test_timeout_probe_maps_to_timeout_status_error_tier(self): |
| 631 | report = _build({}, probe_map={"yt-dlp": health.TIMEOUT}) |
| 632 | record = report["sources"]["youtube"] |
| 633 | self.assertEqual("timeout", record["status"]) |
| 634 | self.assertEqual("error", record["tier"]) |
| 635 | self.assertTrue(record["fix"]) |
| 636 | # Everything else still renders. |
| 637 | self.assertEqual("ok", report["sources"]["reddit"]["tier"]) |
| 638 | self.assertEqual("ok", report["sources"]["hackernews"]["tier"]) |
| 639 | |
| 640 | def test_broken_probe_maps_to_broken(self): |
| 641 | report = _build({}, probe_map={"yt-dlp": health.BROKEN}) |
| 642 | record = report["sources"]["youtube"] |
| 643 | self.assertEqual("broken", record["status"]) |
| 644 | self.assertEqual("error", record["tier"]) |
| 645 | |
| 646 | def test_chained_failure_requires_names_the_failed_backend(self): |
| 647 | """F4: chain[0] merely MISSING while a later backend is BROKEN -> |
| 648 | the record's requires is the BROKEN backend's (mirroring how the |
| 649 | OK/WARN branches use the active finding), never chain[0]'s.""" |
| 650 | config = { |
| 651 | "AUTH_TOKEN": "dummy-auth-token-secret-000", |
| 652 | "CT0": "dummy-ct0-secret-000", |
| 653 | } |
| 654 | with _Hermetic(probe_map={"node": health.BROKEN}), \ |
| 655 | mock.patch("lib.bird_x.is_bird_installed", return_value=True): |
| 656 | report = doctor.build_report(dict(config)) |
| 657 | record = report["sources"]["x"] |
| 658 | self.assertEqual("broken", record["status"]) |
| 659 | self.assertEqual("error", record["tier"]) |
| 660 | by_name = {b["name"]: b for b in record["backends"]} |
| 661 | # chain[0] (xai) is merely unconfigured; bird is the broken one. |
| 662 | self.assertEqual("missing", by_name["xai"]["status"]) |
| 663 | self.assertEqual("broken", by_name["bird"]["status"]) |
| 664 | self.assertEqual(by_name["bird"]["requires"], record["requires"]) |
| 665 | self.assertNotEqual(by_name["xai"]["requires"], record["requires"]) |
| 666 | |
| 667 | def test_source_exception_is_isolated(self): |
| 668 | real_resolve = backends.resolve |
| 669 | |
| 670 | def exploding(source, config, pin=None): |
| 671 | if source == "x": |
| 672 | raise RuntimeError("probe blew up") |
| 673 | return real_resolve(source, config, pin) |
| 674 | |
| 675 | with _Hermetic(), mock.patch("lib.backends.resolve", exploding): |
| 676 | report = doctor.build_report({}) |
| 677 | record = report["sources"]["x"] |
| 678 | self.assertEqual("error", record["status"]) |
| 679 | self.assertEqual("error", record["tier"]) |
| 680 | self.assertIn("RuntimeError", record["detail"]) |
| 681 | # The rest of the report survives. |
| 682 | self.assertEqual("ok", report["sources"]["reddit"]["tier"]) |
| 683 | self.assertEqual(set(doctor.SOURCE_ORDER), set(report["sources"].keys())) |
| 684 | # And the whole report still renders as text and JSON. |
| 685 | self.assertTrue(doctor.render_text(report)) |
| 686 | json.loads(doctor.render_json(report)) |
| 687 | |
| 688 | |
| 689 | class NoSecretsInvariant(unittest.TestCase): |
| 690 | """Scenario 4: seeded fake credentials never appear in any output.""" |
| 691 | |
| 692 | def test_no_secret_values_in_text_or_json(self): |
| 693 | report = _build(dict(FAKE_SECRETS)) |
| 694 | text = doctor.render_text(report) |
| 695 | raw_json = doctor.render_json(report) |
| 696 | for var, secret in FAKE_SECRETS.items(): |
| 697 | if var == "BSKY_HANDLE": |
| 698 | continue # a handle is an identifier, not a credential |
| 699 | self.assertNotIn(secret, text, var) |
| 700 | self.assertNotIn(secret, raw_json, var) |
| 701 | |
| 702 | def test_keys_present_are_booleans(self): |
| 703 | report = _build(dict(FAKE_SECRETS)) |
| 704 | for name, value in report["setup"]["keys_present"].items(): |
| 705 | self.assertIsInstance(value, bool, name) |
| 706 | |
| 707 | |
| 708 | class TopicWordDispatch(unittest.TestCase): |
| 709 | """Scenario 5: `doctor` dispatches exactly like `setup` (exact match only).""" |
| 710 | |
| 711 | def test_doctor_topic_triggers_report(self): |
| 712 | with mock.patch("lib.doctor.run", return_value=0) as run, \ |
| 713 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 714 | mock.patch.object(sys, "argv", ["last30days.py", "doctor"]): |
| 715 | stdout, stderr = io.StringIO(), io.StringIO() |
| 716 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 717 | rc = cli.main() |
| 718 | self.assertEqual(0, rc) |
| 719 | self.assertTrue(run.called) |
| 720 | |
| 721 | def test_doctor_json_flag_passes_through(self): |
| 722 | with mock.patch("lib.doctor.run", return_value=0) as run, \ |
| 723 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 724 | mock.patch.object(sys, "argv", ["last30days.py", "doctor", "--json"]): |
| 725 | stdout, stderr = io.StringIO(), io.StringIO() |
| 726 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 727 | rc = cli.main() |
| 728 | self.assertEqual(0, rc) |
| 729 | self.assertTrue(run.call_args.kwargs.get("emit_json")) |
| 730 | |
| 731 | def test_doctor_emit_json_also_works(self): |
| 732 | rc, out = _run_cli_doctor(["doctor", "--emit=json"], {}) |
| 733 | self.assertEqual(0, rc) |
| 734 | payload = json.loads(out) |
| 735 | self.assertIn("sources", payload) |
| 736 | |
| 737 | def test_multiword_topic_containing_doctor_is_research_not_report(self): |
| 738 | # Same collision rule as setup: exact single-word match only. A real |
| 739 | # research topic goes down the research path (sentinel raised there). |
| 740 | with mock.patch("lib.doctor.run", side_effect=AssertionError("doctor must not run")), \ |
| 741 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 742 | mock.patch.object( |
| 743 | cli.pipeline, "diagnose", side_effect=RuntimeError("research path reached") |
| 744 | ), \ |
| 745 | mock.patch.object(sys, "argv", ["last30days.py", "doctor", "who", "reviews"]): |
| 746 | stdout, stderr = io.StringIO(), io.StringIO() |
| 747 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 748 | with self.assertRaises(RuntimeError): |
| 749 | cli.main() |
| 750 | |
| 751 | def test_json_flag_rejected_for_research_topics(self): |
| 752 | with mock.patch.object( |
| 753 | cli.env, "get_config", side_effect=AssertionError("config should not load") |
| 754 | ), mock.patch.object(sys, "argv", ["last30days.py", "some", "topic", "--json"]): |
| 755 | stderr = io.StringIO() |
| 756 | with redirect_stderr(stderr), self.assertRaises(SystemExit) as exc: |
| 757 | cli.main() |
| 758 | self.assertEqual(2, exc.exception.code) |
| 759 | self.assertIn("--json", stderr.getvalue()) |
| 760 | |
| 761 | |
| 762 | class IncludeSourcesTokenParsing(unittest.TestCase): |
| 763 | """Opt-in gates match whole INCLUDE_SOURCES tokens, never substrings.""" |
| 764 | |
| 765 | def test_substring_token_does_not_enable_linkedin(self): |
| 766 | report = _build({ |
| 767 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 768 | "INCLUDE_SOURCES": "notlinkedincorp", |
| 769 | }) |
| 770 | record = report["sources"]["linkedin"] |
| 771 | self.assertEqual("opt-in", record["status"]) |
| 772 | self.assertEqual("off", record["tier"]) |
| 773 | |
| 774 | def test_exact_token_enables_linkedin(self): |
| 775 | report = _build({ |
| 776 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 777 | "INCLUDE_SOURCES": "linkedin", |
| 778 | }) |
| 779 | record = report["sources"]["linkedin"] |
| 780 | self.assertEqual("ok", record["status"]) |
| 781 | self.assertEqual("ok", record["tier"]) |
| 782 | |
| 783 | |
| 784 | class YoutubeTranscriptionNote(unittest.TestCase): |
| 785 | """The caption-free transcription module is not called by any source yet, |
| 786 | so doctor must not prescribe a GROQ_API_KEY/OPENAI_API_KEY for it: the key |
| 787 | would change nothing. A healthy yt-dlp YouTube record carries no |
| 788 | transcription note and no fix.""" |
| 789 | |
| 790 | def setUp(self): |
| 791 | self.report = _build({}, probe_map={"yt-dlp": health.OK}) |
| 792 | |
| 793 | def test_ok_record_prescribes_no_transcription_key(self): |
| 794 | record = self.report["sources"]["youtube"] |
| 795 | self.assertEqual("ok", record["tier"]) |
| 796 | self.assertEqual("ok", record["status"]) |
| 797 | self.assertNotIn("caption-free", (record.get("note") or "").lower()) |
| 798 | self.assertNotIn("GROQ_API_KEY", record.get("fix") or "") |
| 799 | self.assertNotIn("GROQ_API_KEY", doctor.render_text(self.report)) |
| 800 | |
| 801 | def test_no_paid_comment_prescription_when_ytdlp_is_installed(self): |
| 802 | # yt-dlp fetches comment text free. With it installed, doctor must NOT |
| 803 | # tell the user to buy a ScrapeCreators key for comments, which would |
| 804 | # be selling a fix for a problem they do not have. |
| 805 | note = (self.report["sources"]["youtube"].get("note") or "").lower() |
| 806 | self.assertNotIn("comment text needs", note) |
| 807 | self.assertNotIn("scrapecreators", note) |
| 808 | |
| 809 | |
| 810 | class YoutubeCommentsFixLine(unittest.TestCase): |
| 811 | """Greptile P2: when only the comment-text caveat fires (transcription key |
| 812 | present), the record still carries an actionable fix line.""" |
| 813 | |
| 814 | def test_no_comment_caveat_when_ytdlp_present(self): |
| 815 | """yt-dlp installed -> comments are free -> nothing to prescribe.""" |
| 816 | record = _build( |
| 817 | {"GROQ_API_KEY": "dummy-groq-secret-000"}, |
| 818 | probe_map={"yt-dlp": health.OK}, |
| 819 | )["sources"]["youtube"] |
| 820 | self.assertEqual("ok", record["status"]) |
| 821 | note = record["note"].lower() |
| 822 | self.assertNotIn("comment text needs", note) |
| 823 | |
| 824 | def test_comment_caveat_fires_when_ytdlp_absent_but_sc_backs_youtube(self): |
| 825 | """No yt-dlp, but an SC key keeps YouTube itself alive. Comments then |
| 826 | still need the youtube_comments opt-in, so the caveat must surface — |
| 827 | and must name yt-dlp as the free way out, not only the paid one. |
| 828 | |
| 829 | (With neither yt-dlp nor a key, YouTube has no backend at all and the |
| 830 | record short-circuits to 'no backend configured' — no video, no |
| 831 | comments to caveat.) |
| 832 | """ |
| 833 | record = _build( |
| 834 | { |
| 835 | "GROQ_API_KEY": "dummy-groq-secret-000", |
| 836 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 837 | }, |
| 838 | probe_map={"yt-dlp": health.MISSING}, |
| 839 | )["sources"]["youtube"] |
| 840 | note = record["note"].lower() |
| 841 | self.assertIn("comment text needs", note) |
| 842 | self.assertIn("yt-dlp (free)", note) |
| 843 | self.assertTrue(record["fix"], "comment-text caveat must carry a fix") |
| 844 | |
| 845 | |
| 846 | class YoutubeHealthyWhenFullyConfigured(unittest.TestCase): |
| 847 | """U3: with a transcription key AND comment access, the YouTube note carries |
| 848 | no caveat - it is cleanly Ready.""" |
| 849 | |
| 850 | def test_no_caveats_when_transcription_and_comments_available(self): |
| 851 | report = _build( |
| 852 | { |
| 853 | "GROQ_API_KEY": "dummy-groq-secret-000", |
| 854 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 855 | "INCLUDE_SOURCES": "youtube_comments", |
| 856 | }, |
| 857 | probe_map={"yt-dlp": health.OK}, |
| 858 | ) |
| 859 | record = report["sources"]["youtube"] |
| 860 | self.assertEqual("ok", record["status"]) |
| 861 | note = record["note"].lower() |
| 862 | self.assertNotIn("caption-free", note) |
| 863 | self.assertNotIn("comment text needs", note) |
| 864 | |
| 865 | |
| 866 | class NativeSearchHost(unittest.TestCase): |
| 867 | """Scenario 6: native-search host with no web keys -> off, not error.""" |
| 868 | |
| 869 | def test_web_maps_to_off_with_host_native_note(self): |
| 870 | report = _build({"LAST30DAYS_NATIVE_SEARCH": "1"}) |
| 871 | record = report["sources"]["web"] |
| 872 | self.assertEqual("off", record["tier"]) |
| 873 | self.assertEqual("unconfigured", record["status"]) |
| 874 | self.assertIn("host-native search", record["note"]) |
| 875 | |
| 876 | def test_web_on_claudecode_host_is_native_not_degraded(self): |
| 877 | # CLAUDECODE set but LAST30DAYS_NATIVE_SEARCH unset (the standalone |
| 878 | # `doctor` case) -> host-native note, not "degraded/keyless". |
| 879 | report = _build({"CLAUDECODE": "1"}) |
| 880 | record = report["sources"]["web"] |
| 881 | self.assertEqual("off", record["tier"]) |
| 882 | self.assertEqual("unconfigured", record["status"]) |
| 883 | note = record["note"] |
| 884 | self.assertIn("Claude Code", note) |
| 885 | # Must NOT cite an env var the user never set. |
| 886 | self.assertNotIn("LAST30DAYS_NATIVE_SEARCH", note) |
| 887 | |
| 888 | def test_web_native_via_real_env_var_not_just_config(self): |
| 889 | # Production path: env.get_config() never puts CLAUDECODE in the config |
| 890 | # dict, so the os.environ branch is the ONLY one a real Claude Code |
| 891 | # session hits. Set the process env var (config has no CLAUDECODE key). |
| 892 | with _Hermetic(), mock.patch.dict(os.environ, {"CLAUDECODE": "1"}): |
| 893 | record = doctor.build_report({})["sources"]["web"] |
| 894 | self.assertEqual("off", record["tier"]) |
| 895 | self.assertIn("Claude Code", record["note"]) |
| 896 | self.assertNotIn("LAST30DAYS_NATIVE_SEARCH", record["note"]) |
| 897 | |
| 898 | def test_web_stays_degraded_keyless_without_native_signal(self): |
| 899 | # No CLAUDECODE, no LAST30DAYS_NATIVE_SEARCH -> genuine keyless floor. |
| 900 | record = _build({})["sources"]["web"] |
| 901 | self.assertEqual("warn", record["tier"]) |
| 902 | self.assertEqual("degraded", record["status"]) |
| 903 | self.assertEqual("keyless", record["active_backend"]) |
| 904 | |
| 905 | def test_web_with_key_stays_ok_on_native_host(self): |
| 906 | report = _build({ |
| 907 | "LAST30DAYS_NATIVE_SEARCH": "1", |
| 908 | "EXA_API_KEY": "dummy-exa-secret-000", |
| 909 | }) |
| 910 | record = report["sources"]["web"] |
| 911 | self.assertEqual("ok", record["tier"]) |
| 912 | self.assertEqual("exa", record["active_backend"]) |
| 913 | |
| 914 | |
| 915 | class TextReport(unittest.TestCase): |
| 916 | """Grouped text rendering: four-state audit.""" |
| 917 | |
| 918 | def test_groups_and_lines(self): |
| 919 | report = _build({}, probe_map={"yt-dlp": health.BROKEN}) |
| 920 | text = doctor.render_text(report) |
| 921 | self.assertIn("last30days doctor", text) |
| 922 | for header in ( |
| 923 | "WORKING", |
| 924 | "TURNED ON - UNVERIFIED", |
| 925 | "NOT WORKING", |
| 926 | "COULD BE ON", |
| 927 | ): |
| 928 | self.assertIn(header, text) |
| 929 | # One line per source: glyph + source name; fix on non-ok lines. |
| 930 | self.assertIn("reddit", text) |
| 931 | self.assertIn("youtube", text) |
| 932 | self.assertIn("reinstall yt-dlp", text) |
| 933 | # Reddit renders U2's conditional wording verbatim, no single winner. |
| 934 | with _Hermetic(): |
| 935 | conditional = backends.resolve("reddit", {}).conditional |
| 936 | self.assertIn(conditional, text) |
| 937 | |
| 938 | def test_will_use_rendered_for_chained_ok_source(self): |
| 939 | report = _build({"BRAVE_API_KEY": "dummy-brave-secret-000"}) |
| 940 | text = doctor.render_text(report) |
| 941 | self.assertIn("will use: brave", text) |
| 942 | |
| 943 | |
| 944 | def _write_last_report(dir_path, *, source_status, topic="wordpress", fresh=True): |
| 945 | """Write a minimal last-report.json the run-evidence loader can read.""" |
| 946 | ts = datetime.datetime.now(datetime.timezone.utc) |
| 947 | if not fresh: |
| 948 | ts = ts - datetime.timedelta( |
| 949 | seconds=doctor.DEFAULT_REPORT_CACHE_TTL_SECONDS + 600 |
| 950 | ) |
| 951 | iso = ts.isoformat() |
| 952 | payload = { |
| 953 | "schema": doctor.REPORT_CACHE_SCHEMA_VERSION, |
| 954 | "timestamp": iso, |
| 955 | "topic": topic, |
| 956 | "reports": [ |
| 957 | { |
| 958 | "entity": "", |
| 959 | "report": { |
| 960 | "generated_at": iso, |
| 961 | "source_status": { |
| 962 | src: { |
| 963 | "source": src, |
| 964 | "state": st.get("state"), |
| 965 | "items_returned": st.get("items_returned", 0), |
| 966 | "detail": st.get("detail"), |
| 967 | "at": iso, |
| 968 | "fix_hint": st.get("fix_hint"), |
| 969 | } |
| 970 | for src, st in source_status.items() |
| 971 | }, |
| 972 | }, |
| 973 | } |
| 974 | ], |
| 975 | } |
| 976 | path = Path(dir_path) / doctor.REPORT_CACHE_FILENAME |
| 977 | path.write_text(json.dumps(payload), encoding="utf-8") |
| 978 | return path |
| 979 | |
| 980 | |
| 981 | class RunEvidenceOverlay(unittest.TestCase): |
| 982 | """U1: build_report overlays last-report.json per-source outcomes.""" |
| 983 | |
| 984 | def _build_with_evidence(self, source_status, fresh=True): |
| 985 | tmp = tempfile.mkdtemp() |
| 986 | path = _write_last_report(tmp, source_status=source_status, fresh=fresh) |
| 987 | with _Hermetic(), mock.patch( |
| 988 | "lib.doctor._last_report_path", return_value=path |
| 989 | ): |
| 990 | return doctor.build_report({}) |
| 991 | |
| 992 | def test_failed_source_outcome_overlaid(self): |
| 993 | report = self._build_with_evidence( |
| 994 | { |
| 995 | "youtube": {"state": "error", "items_returned": 0, "detail": "HTTP 500"}, |
| 996 | "reddit": {"state": "ok", "items_returned": 13}, |
| 997 | } |
| 998 | ) |
| 999 | yt = report["sources"]["youtube"]["run_outcome"] |
| 1000 | self.assertIsNotNone(yt) |
| 1001 | self.assertEqual("error", yt["state"]) |
| 1002 | self.assertIn("HTTP 500", yt["detail"]) |
| 1003 | self.assertEqual( |
| 1004 | 13, report["sources"]["reddit"]["run_outcome"]["items_returned"] |
| 1005 | ) |
| 1006 | self.assertTrue(report["run_evidence"]["fresh"]) |
| 1007 | self.assertTrue(report["run_evidence"]["present"]) |
| 1008 | |
| 1009 | def test_no_cache_yields_no_outcomes(self): |
| 1010 | with _Hermetic(): # _last_report_path -> None |
| 1011 | report = doctor.build_report({}) |
| 1012 | self.assertIsNone(report["sources"]["reddit"]["run_outcome"]) |
| 1013 | self.assertFalse(report["run_evidence"]["present"]) |
| 1014 | |
| 1015 | def test_corrupt_cache_treated_as_absent(self): |
| 1016 | tmp = tempfile.mkdtemp() |
| 1017 | path = Path(tmp) / doctor.REPORT_CACHE_FILENAME |
| 1018 | path.write_text("{not valid json", encoding="utf-8") |
| 1019 | with _Hermetic(), mock.patch( |
| 1020 | "lib.doctor._last_report_path", return_value=path |
| 1021 | ): |
| 1022 | report = doctor.build_report({}) |
| 1023 | self.assertIsNone(report["sources"]["reddit"]["run_outcome"]) |
| 1024 | self.assertFalse(report["run_evidence"]["present"]) |
| 1025 | |
| 1026 | def test_stale_cache_present_but_not_overlaid(self): |
| 1027 | report = self._build_with_evidence( |
| 1028 | {"youtube": {"state": "error", "items_returned": 0}}, fresh=False |
| 1029 | ) |
| 1030 | # Present but not fresh: overlay withheld from plain doctor (R4), |
| 1031 | # while --postmortem (U4) can still read it by age. |
| 1032 | self.assertIsNone(report["sources"]["youtube"]["run_outcome"]) |
| 1033 | self.assertTrue(report["run_evidence"]["present"]) |
| 1034 | self.assertFalse(report["run_evidence"]["fresh"]) |
| 1035 | |
| 1036 | |
| 1037 | class FourStateAudit(unittest.TestCase): |
| 1038 | """U2: audit_state derivation + grouped render.""" |
| 1039 | |
| 1040 | def test_keyless_ok_no_evidence_is_working(self): |
| 1041 | rec = {"tier": "ok", "status": "ok"} |
| 1042 | self.assertEqual(doctor.AUDIT_WORKING, doctor.audit_state("hackernews", rec)) |
| 1043 | |
| 1044 | def test_reddit_is_not_keyless_always_on(self): |
| 1045 | # Every anonymous Reddit route closed; the floor rides third-party |
| 1046 | # search and an archive, so Reddit needs run or probe evidence. |
| 1047 | self.assertNotIn("reddit", doctor.KEYLESS_ALWAYS_ON) |
| 1048 | rec = {"tier": "ok", "status": "ok"} |
| 1049 | self.assertEqual(doctor.AUDIT_UNVERIFIED, doctor.audit_state("reddit", rec)) |
| 1050 | |
| 1051 | def test_configured_ok_no_evidence_is_unverified(self): |
| 1052 | rec = {"tier": "ok", "status": "ok"} |
| 1053 | self.assertEqual(doctor.AUDIT_UNVERIFIED, doctor.audit_state("tiktok", rec)) |
| 1054 | |
| 1055 | def test_fresh_run_items_is_working(self): |
| 1056 | rec = {"tier": "ok", "status": "ok"} |
| 1057 | ro = {"state": "ok", "items_returned": 13} |
| 1058 | self.assertEqual(doctor.AUDIT_WORKING, doctor.audit_state("tiktok", rec, ro)) |
| 1059 | |
| 1060 | def test_fresh_run_error_is_not_working(self): |
| 1061 | rec = {"tier": "ok", "status": "ok"} |
| 1062 | ro = {"state": "error", "items_returned": 0, "detail": "HTTP 500"} |
| 1063 | self.assertEqual( |
| 1064 | doctor.AUDIT_NOT_WORKING, doctor.audit_state("youtube", rec, ro) |
| 1065 | ) |
| 1066 | |
| 1067 | def test_fresh_run_partial_is_unverified(self): |
| 1068 | rec = {"tier": "ok", "status": "ok"} |
| 1069 | ro = {"state": "partial", "items_returned": 8, "detail": "HTTP 400"} |
| 1070 | self.assertEqual( |
| 1071 | doctor.AUDIT_UNVERIFIED, doctor.audit_state("instagram", rec, ro) |
| 1072 | ) |
| 1073 | |
| 1074 | def test_off_tier_is_could_be_on(self): |
| 1075 | rec = {"tier": "off", "status": "opt-in"} |
| 1076 | self.assertEqual( |
| 1077 | doctor.AUDIT_COULD_BE_ON, doctor.audit_state("threads", rec) |
| 1078 | ) |
| 1079 | |
| 1080 | def test_probe_result_decides_when_no_run(self): |
| 1081 | rec = {"tier": "ok", "status": "ok"} |
| 1082 | self.assertEqual( |
| 1083 | doctor.AUDIT_WORKING, doctor.audit_state("tiktok", rec, None, {"ok": True}) |
| 1084 | ) |
| 1085 | self.assertEqual( |
| 1086 | doctor.AUDIT_NOT_WORKING, |
| 1087 | doctor.audit_state("tiktok", rec, None, {"ok": False}), |
| 1088 | ) |
| 1089 | |
| 1090 | def test_transient_probe_failure_is_unverified_not_broken(self): |
| 1091 | # A source that rate-limited the probe is unknown, not down. Calling it |
| 1092 | # NOT WORKING sends people debugging a source that serves fine. |
| 1093 | rec = {"tier": "ok", "status": "ok"} |
| 1094 | self.assertEqual( |
| 1095 | doctor.AUDIT_UNVERIFIED, |
| 1096 | doctor.audit_state( |
| 1097 | "reddit", rec, None, {"ok": False, "transient": True} |
| 1098 | ), |
| 1099 | ) |
| 1100 | |
| 1101 | def test_render_json_keeps_legacy_keys_and_adds_audit(self): |
| 1102 | report = _build({}) |
| 1103 | for name, rec in report["sources"].items(): |
| 1104 | self.assertIn("tier", rec, name) |
| 1105 | self.assertIn("status", rec, name) |
| 1106 | self.assertIn("audit_state", rec, name) |
| 1107 | self.assertEqual("config", report["mode"]) |
| 1108 | blob = json.loads(doctor.render_json(report)) |
| 1109 | self.assertIn("mode", blob) |
| 1110 | self.assertIn("audit_state", blob["sources"]["github"]) |
| 1111 | |
| 1112 | def test_every_source_its_own_line(self): |
| 1113 | text = doctor.render_text(_build({})) |
| 1114 | self.assertRegex(text, r"[●◐✕○] github") |
| 1115 | |
| 1116 | def test_working_line_shows_item_count(self): |
| 1117 | tmp = tempfile.mkdtemp() |
| 1118 | path = _write_last_report( |
| 1119 | tmp, source_status={"reddit": {"state": "ok", "items_returned": 13}} |
| 1120 | ) |
| 1121 | with _Hermetic(), mock.patch( |
| 1122 | "lib.doctor._last_report_path", return_value=path |
| 1123 | ): |
| 1124 | text = doctor.render_text(doctor.build_report({})) |
| 1125 | self.assertIn("13 items last run", text) |
| 1126 | |
| 1127 | |
| 1128 | class JsonContract(unittest.TestCase): |
| 1129 | """U9: doctor --json is additive; --cached serves the new audit shape.""" |
| 1130 | |
| 1131 | LEGACY_RECORD_KEYS = { |
| 1132 | "tier", "status", "mode", "backends", "active_backend", "fix", |
| 1133 | "requires", "note", "detail", "pin_var", "pin_flag", "pinned", |
| 1134 | } |
| 1135 | |
| 1136 | def test_legacy_record_keys_preserved(self): |
| 1137 | blob = json.loads(doctor.render_json(_build({}))) |
| 1138 | rec = blob["sources"]["reddit"] |
| 1139 | for key in self.LEGACY_RECORD_KEYS: |
| 1140 | self.assertIn(key, rec, key) |
| 1141 | self.assertIn("audit_state", rec) # additive |
| 1142 | self.assertIn("mode", blob) # top-level additive |
| 1143 | |
| 1144 | def test_new_keys_additive(self): |
| 1145 | blob = json.loads( |
| 1146 | doctor.render_json( |
| 1147 | _build( |
| 1148 | {"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}, |
| 1149 | probe_map={"yt-dlp": health.OK}, |
| 1150 | ) |
| 1151 | ) |
| 1152 | ) |
| 1153 | yt = blob["sources"]["youtube"] |
| 1154 | self.assertIn("cli", yt) |
| 1155 | self.assertIn("backups", yt) |
| 1156 | self.assertIn("comments", yt) |
| 1157 | |
| 1158 | def test_cached_roundtrip_serves_audit_shape(self): |
| 1159 | tmp = Path(tempfile.mkdtemp()) / "doctor-cache.json" |
| 1160 | with _Hermetic(), mock.patch("lib.doctor.cache_path", return_value=tmp): |
| 1161 | report = doctor.build_report({}) |
| 1162 | report["generated_at"] = datetime.datetime.now( |
| 1163 | datetime.timezone.utc |
| 1164 | ).isoformat() |
| 1165 | report["from_cache"] = False |
| 1166 | self.assertTrue(doctor._write_cache(report, {})) |
| 1167 | served = doctor.read_cached_report({}) |
| 1168 | self.assertIsNotNone(served) |
| 1169 | self.assertIn("audit_state", served["sources"]["reddit"]) |
| 1170 | self.assertIn("WORKING", doctor.render_text(served)) |
| 1171 | |
| 1172 | def test_cached_denial_invalidated_by_browser_gate_changes(self): |
| 1173 | tmp = Path(tempfile.mkdtemp()) / "doctor-cache.json" |
| 1174 | config = { |
| 1175 | "FROM_BROWSER": "edge", |
| 1176 | "BROWSER_CONSENT": "true", |
| 1177 | "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge", |
| 1178 | } |
| 1179 | with _Hermetic(), mock.patch("lib.doctor.cache_path", return_value=tmp): |
| 1180 | report = doctor.build_report(config) |
| 1181 | report["generated_at"] = datetime.datetime.now( |
| 1182 | datetime.timezone.utc |
| 1183 | ).isoformat() |
| 1184 | self.assertTrue(doctor._write_cache(report, config)) |
| 1185 | self.assertIsNotNone(doctor.read_cached_report(config)) |
| 1186 | self.assertIsNone(doctor.read_cached_report({**config, "BROWSER_CONSENT": "false"})) |
| 1187 | self.assertIsNone(doctor.read_cached_report({**config, "FROM_BROWSER": "off"})) |
| 1188 | |
| 1189 | def test_sidecar_opt_in_invalidates_cached_advice(self): |
| 1190 | with tempfile.TemporaryDirectory() as directory: |
| 1191 | path = Path(directory) / "doctor-cache.json" |
| 1192 | with _Hermetic(), mock.patch("lib.doctor.cache_path", return_value=path): |
| 1193 | report = doctor.build_report({}) |
| 1194 | self.assertTrue(doctor._write_cache(report, {})) |
| 1195 | self.assertIsNotNone(doctor.read_cached_report({})) |
| 1196 | self.assertIsNone(doctor.read_cached_report({"AGENTCOOKIE": "on"})) |
| 1197 | self.assertTrue(doctor._write_cache(report, {"AGENTCOOKIE": "on"})) |
| 1198 | self.assertIsNone(doctor.read_cached_report({"AGENTCOOKIE": "off"})) |
| 1199 | |
| 1200 | def test_sidecar_environment_fallback_invalidates_cached_advice(self): |
| 1201 | with tempfile.TemporaryDirectory() as directory: |
| 1202 | path = Path(directory) / "doctor-cache.json" |
| 1203 | with _Hermetic(), mock.patch("lib.doctor.cache_path", return_value=path): |
| 1204 | report = doctor.build_report({}) |
| 1205 | with mock.patch.dict(os.environ, {"AGENTCOOKIE": "off"}): |
| 1206 | self.assertTrue(doctor._write_cache(report, {})) |
| 1207 | with mock.patch.dict(os.environ, {"AGENTCOOKIE": "on"}): |
| 1208 | self.assertTrue(doctor.read_cached_report({}) is None) |
| 1209 | self.assertTrue(doctor._write_cache(report, {})) |
| 1210 | with mock.patch.dict(os.environ, {"AGENTCOOKIE": "off"}): |
| 1211 | self.assertTrue(doctor.read_cached_report({}) is None) |
| 1212 | self.assertIsNotNone(doctor.read_cached_report({"AGENTCOOKIE": "on"})) |
| 1213 | |
| 1214 | |
| 1215 | class LiveProbe(unittest.TestCase): |
| 1216 | """U5: bounded live probe (--probe / no-fresh-run auto-fallback).""" |
| 1217 | |
| 1218 | def test_probeable_excludes_credit_gated(self): |
| 1219 | probeable = set(doctor._probeable_sources()) |
| 1220 | for gated in ("x", "tiktok", "instagram", "threads", "linkedin"): |
| 1221 | self.assertNotIn(gated, probeable, gated) |
| 1222 | # free HTTP + keyless CLI sources ARE probeable |
| 1223 | for free in ("reddit", "hackernews", "polymarket", "github", "youtube"): |
| 1224 | self.assertIn(free, probeable, free) |
| 1225 | |
| 1226 | def test_probe_source_http_reachable(self): |
| 1227 | with mock.patch("lib.doctor._http_ok", return_value=(True, "HTTP 200")): |
| 1228 | res = doctor._probe_source("hackernews", {}, 5) |
| 1229 | self.assertTrue(res["ok"]) |
| 1230 | self.assertTrue(res["probed"]) |
| 1231 | |
| 1232 | def test_probe_source_credit_gated_returns_none(self): |
| 1233 | self.assertIsNone(doctor._probe_source("tiktok", {}, 5)) |
| 1234 | |
| 1235 | def test_reddit_probe_targets_the_endpoint_the_engine_uses(self): |
| 1236 | # Probing a hand-copied URL certified endpoints the engine had already |
| 1237 | # abandoned (hot.json, the retired feed, then the anonymous site |
| 1238 | # search). The probe asks the floor the lane asks: Brave, then Arctic. |
| 1239 | url = doctor._HTTP_PROBE_URLS["reddit"] |
| 1240 | self.assertEqual(reddit_health.brave_probe_url(), url) |
| 1241 | self.assertTrue(url.startswith("https://search.brave.com/search?")) |
| 1242 | self.assertIn("site%3Areddit.com", url) |
| 1243 | self.assertNotIn("reddit.com/svc", url) |
| 1244 | follow = doctor._PROBE_FOLLOW_UPS["reddit"] |
| 1245 | self.assertEqual("arctic", follow[0][0]) |
| 1246 | self.assertIn("/api/posts/ids?ids=", follow[0][2]) |
| 1247 | |
| 1248 | BRAVE_PAGE = (Path(__file__).resolve().parent.parent / "fixtures" / "brave_reddit_serp.html") |
| 1249 | |
| 1250 | def _probe_reddit_with_bodies(self, *bodies): |
| 1251 | answers = [(200, body.encode("utf-8"), None) for body in bodies] |
| 1252 | with mock.patch("lib.bounded_get.get", side_effect=answers) as get: |
| 1253 | return doctor._probe_source("reddit", {}, 5), get |
| 1254 | |
| 1255 | def test_reddit_probe_brave_results_and_arctic_answer_passes(self): |
| 1256 | res, get = self._probe_reddit_with_bodies(self.BRAVE_PAGE.read_text(), '{"data": []}') |
| 1257 | self.assertTrue(res["ok"]) |
| 1258 | self.assertEqual("Brave HTTP 200; Arctic Shift HTTP 200", res["detail"]) |
| 1259 | self.assertEqual(2, get.call_count) |
| 1260 | # A pass is fresh evidence: both paths read ok in the health cache. |
| 1261 | entries = reddit_health.entries() |
| 1262 | self.assertEqual("ok", entries["brave"]["state"]) |
| 1263 | self.assertEqual("ok", entries["arctic"]["state"]) |
| 1264 | |
| 1265 | def test_reddit_probe_brave_page_without_results_is_blocked(self): |
| 1266 | # A 200 challenge page is the failure the lane hits: status alone |
| 1267 | # would report a refused floor as working. Arctic is not asked. |
| 1268 | res, get = self._probe_reddit_with_bodies("<html><title>Captcha</title></html>") |
| 1269 | self.assertFalse(res["ok"]) |
| 1270 | self.assertIn("HTTP 200", res["detail"]) |
| 1271 | self.assertIn("blocked", res["detail"]) |
| 1272 | self.assertFalse(res.get("transient", False)) |
| 1273 | self.assertEqual(2, get.call_count) |
| 1274 | |
| 1275 | def test_reddit_probe_arctic_failure_fails_the_floor(self): |
| 1276 | res, _get = self._probe_reddit_with_bodies(self.BRAVE_PAGE.read_text(), "<html>down</html>") |
| 1277 | self.assertFalse(res["ok"]) |
| 1278 | self.assertTrue(res["detail"].startswith("Arctic Shift: HTTP 200 but blocked")) |
| 1279 | |
| 1280 | def test_reddit_probe_never_reads_a_cookie(self): |
| 1281 | with mock.patch("lib.env.extract_browser_credentials") as creds, \ |
| 1282 | mock.patch("lib.cookie_extract.extract_cookies") as cookies, \ |
| 1283 | mock.patch("lib.cookie_extract.extract_cookies_with_source") as sourced: |
| 1284 | self._probe_reddit_with_bodies(self.BRAVE_PAGE.read_text(), '{"data": []}') |
| 1285 | creds.assert_not_called() |
| 1286 | cookies.assert_not_called() |
| 1287 | sourced.assert_not_called() |
| 1288 | |
| 1289 | def _probe_reddit_with_status(self, code): |
| 1290 | error = urllib.error.HTTPError( |
| 1291 | doctor._HTTP_PROBE_URLS["reddit"], code, "Blocked", {}, None |
| 1292 | ) |
| 1293 | with ( |
| 1294 | mock.patch("lib.bounded_get.get", return_value=(code, None, error)), |
| 1295 | # 429 buys a retry; don't pay the real backoff in the suite. |
| 1296 | mock.patch("lib.doctor.time.sleep"), |
| 1297 | ): |
| 1298 | return doctor._probe_source("reddit", {}, 5) |
| 1299 | |
| 1300 | def test_reddit_probe_403_is_not_reachable(self): |
| 1301 | res = self._probe_reddit_with_status(403) |
| 1302 | self.assertFalse(res["ok"]) |
| 1303 | self.assertIn("403", res["detail"]) |
| 1304 | |
| 1305 | def test_reddit_probe_429_is_not_reachable(self): |
| 1306 | res = self._probe_reddit_with_status(429) |
| 1307 | self.assertFalse(res["ok"]) |
| 1308 | self.assertIn("429", res["detail"]) |
| 1309 | |
| 1310 | def test_reddit_probe_429_is_retried_once(self): |
| 1311 | # A single keyless probe draws a 429 during a burst while the lane — |
| 1312 | # which retries with backoff — serves the same query fine. Give the |
| 1313 | # probe that same second chance before it accuses a working source. |
| 1314 | with ( |
| 1315 | mock.patch( |
| 1316 | "lib.doctor._http_ok", return_value=(False, "HTTP 429") |
| 1317 | ) as http_ok, |
| 1318 | mock.patch("lib.doctor.time.sleep") as sleep, |
| 1319 | ): |
| 1320 | res = doctor._probe_source("reddit", {}, 5) |
| 1321 | self.assertEqual(2, http_ok.call_count) |
| 1322 | sleep.assert_called_once_with(doctor._PROBE_RETRY_DELAY_SECONDS) |
| 1323 | self.assertTrue(res["transient"]) |
| 1324 | self.assertIn("429", res["detail"]) |
| 1325 | |
| 1326 | def test_reddit_probe_429_then_ok_is_reachable(self): |
| 1327 | # The retry is the whole point: a probe that lands on the second |
| 1328 | # attempt reports plain success, with no transient residue. |
| 1329 | with ( |
| 1330 | mock.patch( |
| 1331 | "lib.doctor._http_ok", |
| 1332 | side_effect=[(False, "HTTP 429"), (True, "HTTP 200"), (True, "HTTP 200")], |
| 1333 | ), |
| 1334 | mock.patch("lib.doctor.time.sleep"), |
| 1335 | ): |
| 1336 | res = doctor._probe_source("reddit", {}, 5) |
| 1337 | self.assertTrue(res["ok"]) |
| 1338 | self.assertNotIn("transient", res) |
| 1339 | |
| 1340 | def test_reddit_archive_requires_checked_success(self): |
| 1341 | for code in (400, 404, 422): |
| 1342 | with mock.patch("lib.doctor._probe_url", side_effect=[ |
| 1343 | {"ok": False, "detail": "HTTP 403", "probed": True}, |
| 1344 | {"ok": True, "detail": f"HTTP {code}", "probed": True}, |
| 1345 | ]): |
| 1346 | result = doctor._probe_source("reddit", {}, 5) |
| 1347 | self.assertFalse(result.get("partial", False)) |
| 1348 | with mock.patch("lib.doctor._probe_url", side_effect=[ |
| 1349 | {"ok": False, "detail": "HTTP 403", "probed": True}, |
| 1350 | {"ok": True, "detail": "HTTP 200", "probed": True}, |
| 1351 | ]): |
| 1352 | result = doctor._probe_source("reddit", {}, 5) |
| 1353 | self.assertTrue(result["partial"]) |
| 1354 | self.assertEqual(doctor.AUDIT_UNVERIFIED, |
| 1355 | doctor.audit_state("reddit", {"tier": doctor.TIER_OK}, probe_result=result)) |
| 1356 | |
| 1357 | def test_reddit_probe_403_is_not_retried(self): |
| 1358 | # 403 is the standing keyless block, not a burst. Retrying it only |
| 1359 | # doubles the wait before reporting a real outage. |
| 1360 | with ( |
| 1361 | mock.patch( |
| 1362 | "lib.doctor._http_ok", return_value=(False, "HTTP 403") |
| 1363 | ) as http_ok, |
| 1364 | mock.patch("lib.doctor.time.sleep") as sleep, |
| 1365 | ): |
| 1366 | res = doctor._probe_source("reddit", {}, 5) |
| 1367 | self.assertEqual(2, http_ok.call_count) |
| 1368 | sleep.assert_not_called() |
| 1369 | self.assertFalse(res.get("transient", False)) |
| 1370 | |
| 1371 | def test_transient_retry_is_per_source(self): |
| 1372 | # Like the blocked-status carve-out above, the retry is scoped to the |
| 1373 | # source that actually rate-limits us. |
| 1374 | with ( |
| 1375 | mock.patch( |
| 1376 | "lib.doctor._http_ok", return_value=(False, "HTTP 429") |
| 1377 | ) as http_ok, |
| 1378 | mock.patch("lib.doctor.time.sleep") as sleep, |
| 1379 | ): |
| 1380 | res = doctor._probe_source("hackernews", {}, 5) |
| 1381 | self.assertEqual(1, http_ok.call_count) |
| 1382 | sleep.assert_not_called() |
| 1383 | self.assertFalse(res.get("transient", False)) |
| 1384 | |
| 1385 | def test_non_reddit_probe_keeps_4xx_as_reachable(self): |
| 1386 | # The blocked-status carve-out is per-source: a 4xx elsewhere still |
| 1387 | # means the endpoint responded. |
| 1388 | error = urllib.error.HTTPError( |
| 1389 | doctor._HTTP_PROBE_URLS["github"], 403, "Forbidden", {}, None |
| 1390 | ) |
| 1391 | with mock.patch("lib.bounded_get.get", return_value=(403, None, error)): |
| 1392 | res = doctor._probe_source("github", {}, 5) |
| 1393 | self.assertTrue(res["ok"]) |
| 1394 | |
| 1395 | def test_reddit_probe_sends_the_engine_user_agent(self): |
| 1396 | # Probing with a different UA measures the User-Agent, not the endpoint. |
| 1397 | seen = {} |
| 1398 | |
| 1399 | def capture(req, **kwargs): |
| 1400 | seen.setdefault("ua", req.get_header("User-agent")) |
| 1401 | seen.setdefault("accept", req.get_header("Accept")) |
| 1402 | return 500, None, urllib.error.HTTPError(req.full_url, 500, "boom", {}, None) |
| 1403 | |
| 1404 | with mock.patch("lib.bounded_get.get", capture): |
| 1405 | doctor._probe_source("reddit", {}, 5) |
| 1406 | self.assertEqual(http.BROWSER_USER_AGENT, seen["ua"]) |
| 1407 | self.assertIn("text/html", seen["accept"]) |
| 1408 | |
| 1409 | def test_probe_failure_is_isolated(self): |
| 1410 | def flaky(name, config, timeout): |
| 1411 | if name == "reddit": |
| 1412 | raise RuntimeError("boom") |
| 1413 | return {"ok": True, "probed": True} |
| 1414 | |
| 1415 | with mock.patch("lib.doctor._probe_source", flaky): |
| 1416 | results = doctor._probe_sources({}, timeout=5) |
| 1417 | self.assertFalse(results["reddit"]["ok"]) # isolated failure |
| 1418 | self.assertIn("boom", results["reddit"]["detail"]) |
| 1419 | self.assertTrue(results["hackernews"]["ok"]) # others unaffected |
| 1420 | |
| 1421 | def test_zero_probe_budget_starts_no_transport(self): |
| 1422 | with mock.patch("lib.bounded_get.get") as transport: |
| 1423 | results = doctor._probe_sources({}, timeout=0) |
| 1424 | transport.assert_not_called() |
| 1425 | self.assertTrue(results) |
| 1426 | self.assertTrue(all("deadline" in r["detail"] for r in results.values())) |
| 1427 | |
| 1428 | def test_probe_result_flips_unverified_to_working(self): |
| 1429 | rec = {"tier": "ok", "status": "ok", "audit_state": doctor.AUDIT_UNVERIFIED} |
| 1430 | report = {"sources": {"hackernews": rec}} |
| 1431 | doctor._apply_probe(report, {"hackernews": {"ok": True, "probed": True}}) |
| 1432 | self.assertEqual(doctor.AUDIT_WORKING, rec["audit_state"]) |
| 1433 | self.assertTrue(rec["probe"]["ok"]) |
| 1434 | |
| 1435 | def test_auto_probe_fires_when_no_fresh_run(self): |
| 1436 | canned = {"hackernews": {"ok": True, "detail": "HTTP 200", "probed": True}} |
| 1437 | with _Hermetic(), mock.patch( |
| 1438 | "lib.doctor._probe_sources", return_value=canned |
| 1439 | ) as probed: |
| 1440 | out = io.StringIO() |
| 1441 | err = io.StringIO() |
| 1442 | with redirect_stdout(out), redirect_stderr(err): |
| 1443 | rc = doctor.run({}) |
| 1444 | self.assertEqual(0, rc) |
| 1445 | probed.assert_called() # auto-fired: no fresh run |
| 1446 | self.assertIn("live probe", err.getvalue()) |
| 1447 | |
| 1448 | def test_no_auto_probe_when_fresh_run(self): |
| 1449 | tmp = tempfile.mkdtemp() |
| 1450 | path = _write_last_report( |
| 1451 | tmp, source_status={"reddit": {"state": "ok", "items_returned": 5}} |
| 1452 | ) |
| 1453 | with _Hermetic(), mock.patch( |
| 1454 | "lib.doctor._last_report_path", return_value=path |
| 1455 | ), mock.patch("lib.doctor._probe_sources") as probed: |
| 1456 | with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): |
| 1457 | doctor.run({}) |
| 1458 | probed.assert_not_called() # fresh run -> overlay, no probe |
| 1459 | |
| 1460 | |
| 1461 | class Postmortem(unittest.TestCase): |
| 1462 | """U4: --postmortem reads the last run's per-source outcomes.""" |
| 1463 | |
| 1464 | def _pm(self, source_status, fresh=True): |
| 1465 | tmp = tempfile.mkdtemp() |
| 1466 | path = _write_last_report(tmp, source_status=source_status, fresh=fresh) |
| 1467 | with _Hermetic(), mock.patch( |
| 1468 | "lib.doctor._last_report_path", return_value=path |
| 1469 | ): |
| 1470 | return doctor.build_postmortem({}) |
| 1471 | |
| 1472 | def test_failed_partial_succeeded_grouping(self): |
| 1473 | pm = self._pm( |
| 1474 | { |
| 1475 | "youtube": { |
| 1476 | "state": "error", |
| 1477 | "items_returned": 0, |
| 1478 | "detail": "HTTP 500", |
| 1479 | "fix_hint": "retry later", |
| 1480 | }, |
| 1481 | "instagram": { |
| 1482 | "state": "partial", |
| 1483 | "items_returned": 8, |
| 1484 | "detail": "HTTP 400", |
| 1485 | }, |
| 1486 | "reddit": {"state": "ok", "items_returned": 13}, |
| 1487 | } |
| 1488 | ) |
| 1489 | text = doctor.render_postmortem_text(pm) |
| 1490 | self.assertIn("Failed:", text) |
| 1491 | self.assertIn("HTTP 500", text) |
| 1492 | self.assertIn("retry later", text) |
| 1493 | self.assertIn("Partial:", text) |
| 1494 | self.assertIn("instagram", text) |
| 1495 | self.assertIn("Succeeded:", text) |
| 1496 | self.assertIn("reddit (13)", text) |
| 1497 | |
| 1498 | def test_empty_state(self): |
| 1499 | with _Hermetic(): # _last_report_path -> None |
| 1500 | pm = doctor.build_postmortem({}) |
| 1501 | self.assertFalse(pm["present"]) |
| 1502 | self.assertIn("No saved run found", doctor.render_postmortem_text(pm)) |
| 1503 | |
| 1504 | def test_json_mode_shape(self): |
| 1505 | pm = self._pm({"youtube": {"state": "error", "items_returned": 0}}) |
| 1506 | self.assertEqual("postmortem", pm["mode"]) |
| 1507 | self.assertIn("youtube", pm["outcomes"]) |
| 1508 | |
| 1509 | def test_reads_stale_run_by_age(self): |
| 1510 | pm = self._pm( |
| 1511 | {"youtube": {"state": "timeout", "items_returned": 0}}, fresh=False |
| 1512 | ) |
| 1513 | self.assertTrue(pm["present"]) |
| 1514 | self.assertIn("youtube", pm["outcomes"]) |
| 1515 | |
| 1516 | def test_cli_dispatch_exits_zero(self): |
| 1517 | rc, out = _run_cli_doctor(["doctor", "--postmortem"], {}) |
| 1518 | self.assertEqual(0, rc) |
| 1519 | self.assertIn("post-mortem", out) |
| 1520 | |
| 1521 | |
| 1522 | class BackupAndCommentLanes(unittest.TestCase): |
| 1523 | """U7: backup + comment sub-lanes render on their parent source.""" |
| 1524 | |
| 1525 | def test_youtube_pin_disarms_only_the_youtube_backstop(self): |
| 1526 | report = _build({ |
| 1527 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 1528 | "LAST30DAYS_YOUTUBE_BACKEND": "yt-dlp", |
| 1529 | }) |
| 1530 | self.assertTrue(report["sources"]["reddit"]["backups"][0]["armed"]) |
| 1531 | self.assertFalse(report["sources"]["youtube"]["backups"][0]["armed"]) |
| 1532 | |
| 1533 | def test_backups_armed_with_sc_key(self): |
| 1534 | report = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}) |
| 1535 | self.assertTrue(report["sources"]["reddit"]["backups"][0]["armed"]) |
| 1536 | yt_backup = report["sources"]["youtube"]["backups"][0] |
| 1537 | self.assertTrue(yt_backup["armed"]) |
| 1538 | self.assertIn("rate-limited", yt_backup["note"]) |
| 1539 | text = doctor.render_text(report) |
| 1540 | self.assertIn("backup: ScrapeCreators transcript/search backstop — armed", text) |
| 1541 | |
| 1542 | def test_reddit_backup_note_names_the_floor(self): |
| 1543 | report = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}) |
| 1544 | note = report["sources"]["reddit"]["backups"][0]["note"] |
| 1545 | self.assertIn("below the 5-item floor", note) |
| 1546 | |
| 1547 | def test_reddit_backup_note_floor_off_means_empty_only(self): |
| 1548 | report = _build({ |
| 1549 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 1550 | env.REDDIT_SC_MIN_ITEMS_VAR: "0", |
| 1551 | }) |
| 1552 | note = report["sources"]["reddit"]["backups"][0]["note"] |
| 1553 | self.assertIn("returns nothing", note) |
| 1554 | |
| 1555 | def test_backups_off_without_sc_key(self): |
| 1556 | report = _build({}) |
| 1557 | self.assertFalse(report["sources"]["reddit"]["backups"][0]["armed"]) |
| 1558 | self.assertFalse(report["sources"]["youtube"]["backups"][0]["armed"]) |
| 1559 | |
| 1560 | def test_youtube_comments_reflect_include_sources(self): |
| 1561 | on = _build( |
| 1562 | { |
| 1563 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 1564 | "INCLUDE_SOURCES": "tiktok,instagram,youtube_comments", |
| 1565 | } |
| 1566 | ) |
| 1567 | self.assertTrue(on["sources"]["youtube"]["comments"]["enabled"]) |
| 1568 | off = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}) |
| 1569 | self.assertFalse(off["sources"]["youtube"]["comments"]["enabled"]) |
| 1570 | |
| 1571 | def test_x_dual_path_note(self): |
| 1572 | keyed = _build({"XAI_API_KEY": "dummy-xai-secret-000"}) |
| 1573 | note = keyed["sources"]["x"]["backups"][0]["note"] |
| 1574 | self.assertIn("XAI_API_KEY", note) |
| 1575 | self.assertTrue(keyed["sources"]["x"]["backups"][0]["armed"]) |
| 1576 | |
| 1577 | def test_sub_lanes_in_json(self): |
| 1578 | report = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}) |
| 1579 | blob = json.loads(doctor.render_json(report)) |
| 1580 | self.assertIn("backups", blob["sources"]["youtube"]) |
| 1581 | self.assertIn("comments", blob["sources"]["youtube"]) |
| 1582 | |
| 1583 | |
| 1584 | class ThreadsOptIn(unittest.TestCase): |
| 1585 | """U6: Threads reports opt-in state honestly against INCLUDE_SOURCES.""" |
| 1586 | |
| 1587 | def test_key_without_optin_is_could_be_on(self): |
| 1588 | report = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}) |
| 1589 | rec = report["sources"]["threads"] |
| 1590 | self.assertEqual("opt-in", rec["status"]) |
| 1591 | self.assertEqual(doctor.AUDIT_COULD_BE_ON, rec["audit_state"]) |
| 1592 | self.assertIn("INCLUDE_SOURCES", rec["fix"]) |
| 1593 | |
| 1594 | def test_key_with_optin_is_working(self): |
| 1595 | report = _build( |
| 1596 | { |
| 1597 | "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000", |
| 1598 | "INCLUDE_SOURCES": "tiktok,instagram,threads", |
| 1599 | } |
| 1600 | ) |
| 1601 | rec = report["sources"]["threads"] |
| 1602 | self.assertEqual("ok", rec["status"]) |
| 1603 | |
| 1604 | def test_no_key_is_could_be_on_with_sc_fix(self): |
| 1605 | rec = _build({})["sources"]["threads"] |
| 1606 | self.assertEqual("unconfigured", rec["status"]) |
| 1607 | self.assertEqual(doctor.AUDIT_COULD_BE_ON, rec["audit_state"]) |
| 1608 | |
| 1609 | def test_tiktok_on_by_default_with_key_unchanged(self): |
| 1610 | # Regression: TikTok/Instagram stay on-by-default with a key (WORKING), |
| 1611 | # they are NOT opt-in-gated like Threads. |
| 1612 | report = _build({"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}) |
| 1613 | self.assertEqual("ok", report["sources"]["tiktok"]["status"]) |
| 1614 | self.assertEqual("ok", report["sources"]["instagram"]["status"]) |
| 1615 | |
| 1616 | |
| 1617 | class CliHealth(unittest.TestCase): |
| 1618 | """U3: CLI-dependency health + techmeme/arxiv/trustpilot sources.""" |
| 1619 | |
| 1620 | def test_new_cli_sources_present(self): |
| 1621 | report = _build( |
| 1622 | {}, |
| 1623 | probe_map={ |
| 1624 | "techmeme-pp-cli": health.OK, |
| 1625 | "arxiv-pp-cli": health.OK, |
| 1626 | "trustpilot-pp-cli": health.OK, |
| 1627 | }, |
| 1628 | ) |
| 1629 | for src in ("techmeme", "arxiv", "trustpilot"): |
| 1630 | self.assertIn(src, report["sources"], src) |
| 1631 | self.assertEqual("ok", report["sources"][src]["cli"]["status"], src) |
| 1632 | self.assertEqual("ok", report["sources"]["techmeme"]["status"]) |
| 1633 | |
| 1634 | def test_outdated_techmeme_still_runs_and_shows_an_upgrade(self): |
| 1635 | install = health.pp_install_cmd("techmeme") |
| 1636 | detail = ("2026.9.1 (older than 2026.11.1; it still runs but reads " |
| 1637 | "only Techmeme's first 10 results; upgrade to read more pages)") |
| 1638 | missing = _probe_dep() |
| 1639 | |
| 1640 | def fake(name, timeout=health.PROBE_TIMEOUT): |
| 1641 | if name == "techmeme-pp-cli": |
| 1642 | return health.DependencyProbe( |
| 1643 | name=name, status=health.OK, outdated=True, |
| 1644 | detail=detail, prescription=install, |
| 1645 | ) |
| 1646 | return missing(name, timeout) |
| 1647 | |
| 1648 | with tempfile.TemporaryDirectory() as folder: |
| 1649 | successful_run = _write_last_report( |
| 1650 | folder, source_status={"techmeme": {"state": "ok", "items_returned": 10}} |
| 1651 | ) |
| 1652 | for path, state, heading in ( |
| 1653 | (None, doctor.AUDIT_UNVERIFIED, "◐ TURNED ON - UNVERIFIED:"), |
| 1654 | (successful_run, doctor.AUDIT_WORKING, "● WORKING:"), |
| 1655 | ): |
| 1656 | with self.subTest(state=state), _Hermetic(), mock.patch( |
| 1657 | "lib.health.probe_dependency", fake |
| 1658 | ), mock.patch("lib.doctor._last_report_path", return_value=path): |
| 1659 | report = doctor.build_report({}) |
| 1660 | block = next( |
| 1661 | block for block in doctor.render_text(report).split("\n\n") |
| 1662 | if "techmeme [CLI:" in block |
| 1663 | ) |
| 1664 | self.assertEqual(heading, block.splitlines()[0]) |
| 1665 | line = next(ln for ln in block.splitlines() if "techmeme [CLI:" in ln) |
| 1666 | self.assertIn("first 10 results", line) |
| 1667 | self.assertIn(f"fix: {install}", line) |
| 1668 | |
| 1669 | record = json.loads(doctor.render_json(report))["sources"]["techmeme"] |
| 1670 | self.assertEqual(state, record["audit_state"]) |
| 1671 | self.assertEqual("ok", record["status"]) |
| 1672 | self.assertEqual("ok", record["tier"]) |
| 1673 | self.assertEqual("ok", record["cli"]["status"]) |
| 1674 | self.assertEqual(detail, record["detail"]) |
| 1675 | self.assertEqual(install, record["fix"]) |
| 1676 | self.assertEqual("opt-in", _build({})["sources"]["techmeme"]["status"]) |
| 1677 | |
| 1678 | def test_yahoo_finance_listed_with_cli_marker(self): |
| 1679 | report = _build({}, probe_map={"yahoo-finance-pp-cli": health.OK}) |
| 1680 | rec = report["sources"]["yahoo_finance"] |
| 1681 | self.assertEqual("ok", rec["status"]) |
| 1682 | self.assertEqual("yahoo-finance-pp-cli", rec["cli"]["name"]) |
| 1683 | self.assertEqual("ok", rec["cli"]["status"]) |
| 1684 | text = doctor.render_text(report) |
| 1685 | self.assertIn("yahoo_finance [CLI: yahoo-finance-pp-cli ✓]", text) |
| 1686 | self.assertIn("yahoo-finance-pp-cli — yahoo_finance", text) |
| 1687 | |
| 1688 | def test_patents_listed_as_a_keyless_company_lane(self): |
| 1689 | report = _build({}) |
| 1690 | rec = report["sources"]["patents"] |
| 1691 | self.assertEqual("opt-in", rec["status"]) |
| 1692 | self.assertEqual( |
| 1693 | "none (public USPTO search); activates for company topics", rec["requires"] |
| 1694 | ) |
| 1695 | for expected in ("not companies", "no filings in the window", "sign-in"): |
| 1696 | self.assertIn(expected, rec["note"]) |
| 1697 | self.assertIsNone(rec.get("cli")) |
| 1698 | self.assertEqual(set(doctor.SOURCE_ORDER), set(report["sources"])) |
| 1699 | self.assertLess( |
| 1700 | doctor.SOURCE_ORDER.index("jobs"), doctor.SOURCE_ORDER.index("patents") |
| 1701 | ) |
| 1702 | |
| 1703 | def test_yahoo_finance_quiet_on_a_non_company_topic_is_not_broken(self): |
| 1704 | # The lane only runs for a topic that resolves to a listed company, so |
| 1705 | # a fresh run that recorded nothing for it is the normal case. |
| 1706 | tmp = tempfile.mkdtemp() |
| 1707 | path = _write_last_report( |
| 1708 | tmp, source_status={"reddit": {"state": "ok", "items_returned": 4}} |
| 1709 | ) |
| 1710 | with _Hermetic(probe_map={"yahoo-finance-pp-cli": health.OK}), mock.patch( |
| 1711 | "lib.doctor._last_report_path", return_value=path |
| 1712 | ): |
| 1713 | report = doctor.build_report({}) |
| 1714 | rec = report["sources"]["yahoo_finance"] |
| 1715 | self.assertIsNone(rec["run_outcome"]) |
| 1716 | self.assertNotEqual(doctor.AUDIT_NOT_WORKING, rec["audit_state"]) |
| 1717 | self.assertIn("listed company", rec["note"]) |
| 1718 | line = next( |
| 1719 | ln for ln in doctor.render_text(report).splitlines() |
| 1720 | if "yahoo_finance [CLI" in ln |
| 1721 | ) |
| 1722 | self.assertIn("no price line on other topics", line) |
| 1723 | self.assertNotIn("✕", line) |
| 1724 | |
| 1725 | def test_yahoo_finance_missing_prescribes_catalog_install(self): |
| 1726 | def fake(name, timeout=health.PROBE_TIMEOUT): |
| 1727 | prescription = ( |
| 1728 | health.pp_install_cmd("yahoo-finance") |
| 1729 | if name == "yahoo-finance-pp-cli" else f"install {name}" |
| 1730 | ) |
| 1731 | return health.DependencyProbe( |
| 1732 | name=name, status=health.MISSING, |
| 1733 | detail=f"{name} not found on PATH", |
| 1734 | prescription=prescription, owner_pkg_manager="npx", |
| 1735 | ) |
| 1736 | |
| 1737 | with _Hermetic(), mock.patch("lib.health.probe_dependency", fake): |
| 1738 | report = doctor.build_report({}) |
| 1739 | rec = report["sources"]["yahoo_finance"] |
| 1740 | # Never installed: an optional lane that is off, not a failure. |
| 1741 | self.assertEqual("opt-in", rec["status"]) |
| 1742 | self.assertEqual(doctor.AUDIT_COULD_BE_ON, rec["audit_state"]) |
| 1743 | self.assertIn( |
| 1744 | f"npx -y {setup_wizard.PRINTING_PRESS_NPM} install yahoo-finance --cli-only", |
| 1745 | rec["fix"], |
| 1746 | ) |
| 1747 | text = doctor.render_text(report) |
| 1748 | self.assertIn("[CLI: yahoo-finance-pp-cli ✗ missing]", text) |
| 1749 | self.assertIn("install yahoo-finance --cli-only", text) |
| 1750 | blob = json.loads(doctor.render_json(report)) |
| 1751 | self.assertEqual("missing", blob["sources"]["yahoo_finance"]["cli"]["status"]) |
| 1752 | |
| 1753 | def test_yahoo_finance_off_path_is_not_working(self): |
| 1754 | def fake(name, timeout=health.PROBE_TIMEOUT): |
| 1755 | return health.DependencyProbe( |
| 1756 | name=name, status=health.MISSING, detail="installed off PATH", |
| 1757 | off_path=name == "yahoo-finance-pp-cli", |
| 1758 | prescription="add $HOME/.local/bin to PATH", |
| 1759 | ) |
| 1760 | |
| 1761 | with _Hermetic(), mock.patch("lib.health.probe_dependency", fake): |
| 1762 | report = doctor.build_report({}) |
| 1763 | rec = report["sources"]["yahoo_finance"] |
| 1764 | self.assertTrue(rec["cli"]["off_path"]) |
| 1765 | self.assertEqual(doctor.AUDIT_NOT_WORKING, rec["audit_state"]) |
| 1766 | self.assertIn("PATH", rec["fix"]) |
| 1767 | |
| 1768 | def test_cli_marker_and_block_for_ytdlp(self): |
| 1769 | report = _build({}, probe_map={"yt-dlp": health.OK}) |
| 1770 | self.assertEqual("ok", report["sources"]["youtube"]["cli"]["status"]) |
| 1771 | text = doctor.render_text(report) |
| 1772 | self.assertIn("CLI health", text) |
| 1773 | self.assertIn("[CLI: yt-dlp ✓]", text) |
| 1774 | |
| 1775 | def test_keyless_source_has_no_cli(self): |
| 1776 | report = _build({}) |
| 1777 | self.assertNotIn("cli", report["sources"]["polymarket"]) |
| 1778 | self.assertIn("need no CLI", doctor.render_text(report)) |
| 1779 | |
| 1780 | def test_digg_off_path_is_not_working(self): |
| 1781 | def fake(name, timeout=health.PROBE_TIMEOUT): |
| 1782 | if name == "digg-pp-cli": |
| 1783 | return health.DependencyProbe( |
| 1784 | name=name, |
| 1785 | status=health.BROKEN, |
| 1786 | detail="installed off PATH", |
| 1787 | off_path=True, |
| 1788 | prescription="add ~/.local/bin to PATH", |
| 1789 | ) |
| 1790 | return health.DependencyProbe( |
| 1791 | name=name, status=health.MISSING, detail="missing", |
| 1792 | prescription="install", |
| 1793 | ) |
| 1794 | |
| 1795 | with _Hermetic(), mock.patch("lib.health.probe_dependency", fake): |
| 1796 | report = doctor.build_report({}) |
| 1797 | self.assertTrue(report["sources"]["digg"]["cli"]["off_path"]) |
| 1798 | self.assertEqual( |
| 1799 | doctor.AUDIT_NOT_WORKING, report["sources"]["digg"]["audit_state"] |
| 1800 | ) |
| 1801 | |
| 1802 | def test_older_digg_cli_gets_the_upgrade_fix_and_stays_on(self): |
| 1803 | with _Hermetic(probe_map={"digg-pp-cli": health.OK}), mock.patch( |
| 1804 | "lib.digg.cli_searches_all_topics", return_value=False |
| 1805 | ): |
| 1806 | report = doctor.build_report({}) |
| 1807 | rec = report["sources"]["digg"] |
| 1808 | # An older CLI still answers, so Digg is not reported as failing. |
| 1809 | self.assertEqual("ok", rec["tier"]) |
| 1810 | self.assertNotEqual(doctor.AUDIT_NOT_WORKING, rec["audit_state"]) |
| 1811 | self.assertIn("AI and tech", rec["note"]) |
| 1812 | install = "npx -y @mvanhorn/printing-press-library" |
| 1813 | self.assertIn(install, rec["fix"]) |
| 1814 | self.assertIn("install digg --cli-only", rec["fix"]) |
| 1815 | digg_line = next( |
| 1816 | line for line in doctor.render_text(report).splitlines() |
| 1817 | if "digg [CLI: digg-pp-cli" in line |
| 1818 | ) |
| 1819 | self.assertIn("AI and tech", digg_line) |
| 1820 | self.assertIn("install digg --cli-only", digg_line) |
| 1821 | |
| 1822 | def test_current_digg_cli_is_healthy_with_no_fix(self): |
| 1823 | with _Hermetic(probe_map={"digg-pp-cli": health.OK}), mock.patch( |
| 1824 | "lib.digg.cli_searches_all_topics", return_value=True |
| 1825 | ): |
| 1826 | report = doctor.build_report({}) |
| 1827 | rec = report["sources"]["digg"] |
| 1828 | self.assertEqual("ok", rec["status"]) |
| 1829 | self.assertEqual("", rec["fix"]) |
| 1830 | self.assertEqual("", rec["note"]) |
| 1831 | |
| 1832 | def test_digg_cli_whose_help_could_not_be_read_gets_no_upgrade_fix(self): |
| 1833 | with _Hermetic(probe_map={"digg-pp-cli": health.OK}), mock.patch( |
| 1834 | "lib.digg.cli_searches_all_topics", return_value=None |
| 1835 | ): |
| 1836 | report = doctor.build_report({}) |
| 1837 | rec = report["sources"]["digg"] |
| 1838 | self.assertEqual("ok", rec["status"]) |
| 1839 | self.assertEqual("", rec["fix"]) |
| 1840 | self.assertEqual("", rec["note"]) |
| 1841 | |
| 1842 | def test_digg_cli_that_is_not_installed_is_not_asked_for_its_help_text(self): |
| 1843 | with _Hermetic(), mock.patch( |
| 1844 | "lib.digg.cli_searches_all_topics", |
| 1845 | side_effect=AssertionError("asked a missing CLI for its help text"), |
| 1846 | ): |
| 1847 | report = doctor.build_report({}) |
| 1848 | self.assertEqual("opt-in", report["sources"]["digg"]["status"]) |
| 1849 | |
| 1850 | def test_gh_absent_github_still_working(self): |
| 1851 | report = _build({}) # gh missing by default in _Hermetic |
| 1852 | gh = report["sources"]["github"] |
| 1853 | self.assertEqual(doctor.AUDIT_WORKING, gh["audit_state"]) |
| 1854 | self.assertTrue(gh["cli"]["optional"]) |
| 1855 | |
| 1856 | |
| 1857 | # --------------------------------------------------------------------------- |
| 1858 | # Grok Bot host (official-only X policy): doctor names only the official path |
| 1859 | # --------------------------------------------------------------------------- |
| 1860 | |
| 1861 | # R4 vocabulary that must never appear in an X status or fix line on a Grok |
| 1862 | # Bot host (the pinned backend's own name is the one carve-out). |
| 1863 | GROK_BOT_FORBIDDEN = ( |
| 1864 | "cookie", "cdp", "box-chrome", "bird", "auth_token", "ct0", "xquik", |
| 1865 | "grok login", "grok cli", |
| 1866 | ) |
| 1867 | BEARER_CAVEAT = ( |
| 1868 | "recent posts, about the last week, unless your X developer project has " |
| 1869 | "full-archive access" |
| 1870 | ) |
| 1871 | |
| 1872 | |
| 1873 | def _grok_bot(**over): |
| 1874 | cfg = {"LAST30DAYS_HOST": "grok-bot"} |
| 1875 | cfg.update(over) |
| 1876 | return cfg |
| 1877 | |
| 1878 | |
| 1879 | def _x_text_lines(text): |
| 1880 | """The X source line plus its indented sub-lane lines from doctor text.""" |
| 1881 | lines = text.splitlines() |
| 1882 | out = [] |
| 1883 | for i, line in enumerate(lines): |
| 1884 | if not re.match(r"^\s*\S+\s+x(?:\s|$)", line): |
| 1885 | continue |
| 1886 | out.append(line) |
| 1887 | for follow in lines[i + 1:]: |
| 1888 | if follow.startswith(" "): |
| 1889 | out.append(follow) |
| 1890 | else: |
| 1891 | break |
| 1892 | break |
| 1893 | return out |
| 1894 | |
| 1895 | |
| 1896 | def _grok_signed_in(): |
| 1897 | """A signed-in Grok CLI as the doctor probes see it (filesystem only).""" |
| 1898 | return [ |
| 1899 | mock.patch("lib.backends.which", lambda n: "/usr/bin/grok" if n == "grok" else None), |
| 1900 | mock.patch("lib.grok_x.has_stored_auth", return_value=True), |
| 1901 | mock.patch( |
| 1902 | "lib.grok_x.stored_auth_status", |
| 1903 | return_value=(grok_x.AUTH_OK, "signed in", None), |
| 1904 | ), |
| 1905 | ] |
| 1906 | |
| 1907 | |
| 1908 | def _build_with(config, patches, **kwargs): |
| 1909 | with _Hermetic(**kwargs): |
| 1910 | for p in patches: |
| 1911 | p.start() |
| 1912 | try: |
| 1913 | return doctor.build_report(dict(config)) |
| 1914 | finally: |
| 1915 | for p in reversed(patches): |
| 1916 | p.stop() |
| 1917 | |
| 1918 | |
| 1919 | class GrokBotHostDoctor(unittest.TestCase): |
| 1920 | """AE2, AE2a, AE3: on a Grok Bot host every X line names only the |
| 1921 | official path (connector lane, X_BEARER_TOKEN, XAI_API_KEY, xurl).""" |
| 1922 | |
| 1923 | def _assert_official_vocabulary(self, report, allow=()): |
| 1924 | blob = json.dumps(report["sources"]["x"]).lower() |
| 1925 | text = "\n".join(_x_text_lines(doctor.render_text(report))).lower() |
| 1926 | self.assertTrue(text, "doctor text has no X line") |
| 1927 | for word in GROK_BOT_FORBIDDEN: |
| 1928 | if word in allow: |
| 1929 | continue |
| 1930 | self.assertNotIn(word, blob, f"{word!r} in X JSON record") |
| 1931 | self.assertNotIn(word, text, f"{word!r} in X text lines") |
| 1932 | |
| 1933 | def test_nothing_configured_prescribes_bearer_and_names_no_cookie_path(self): |
| 1934 | config = _grok_bot( |
| 1935 | AUTH_TOKEN="dummy-auth-token-secret-000", |
| 1936 | CT0="dummy-ct0-secret-000", |
| 1937 | XQUIK_API_KEY="dummy-xquik-secret-000", |
| 1938 | FROM_BROWSER="firefox", |
| 1939 | AGENTCOOKIE="on", |
| 1940 | BROWSER_CDP_URL="http://127.0.0.1:9222", |
| 1941 | ) |
| 1942 | report = _build(config) |
| 1943 | rec = report["sources"]["x"] |
| 1944 | self.assertEqual("off", rec["tier"]) |
| 1945 | self.assertEqual("unconfigured", rec["status"]) |
| 1946 | self.assertIsNone(rec["active_backend"]) |
| 1947 | self.assertEqual(["xapi", "xai", "xurl"], [b["name"] for b in rec["backends"]]) |
| 1948 | entry = prescriptions.for_x(config, "cookies_missing") |
| 1949 | self.assertEqual("bearer_missing", entry.failure) |
| 1950 | self.assertIn(entry.fix_nl, rec["fix"]) |
| 1951 | self.assertIsNone(rec["pin_var"]) |
| 1952 | self.assertFalse(rec["backups"][0]["armed"]) |
| 1953 | self._assert_official_vocabulary(report) |
| 1954 | self.assertNotIn("LAST30DAYS_X_BACKEND", json.dumps(rec)) |
| 1955 | |
| 1956 | def test_signed_in_grok_cli_names_neither_cli_nor_pin_variable(self): |
| 1957 | report = _build_with(_grok_bot(), _grok_signed_in()) |
| 1958 | rec = report["sources"]["x"] |
| 1959 | self.assertEqual("unconfigured", rec["status"]) |
| 1960 | self.assertEqual("off", rec["tier"]) |
| 1961 | self.assertNotIn("grok", [b["name"] for b in rec["backends"]]) |
| 1962 | blob = json.dumps(rec) |
| 1963 | x_text = "\n".join(_x_text_lines(doctor.render_text(report))) |
| 1964 | for surface in (blob, x_text): |
| 1965 | # "Grok Bot settings" (the connector copy) and "xAI/Grok live |
| 1966 | # search" (the licensed xai product) are official vocabulary; |
| 1967 | # the CLI, its login, its store, and the pin knob must be absent. |
| 1968 | lowered = surface.lower() |
| 1969 | for word in ("grok cli", "grok login", "~/.grok", "grok binary", "grok --"): |
| 1970 | self.assertNotIn(word, lowered, word) |
| 1971 | self.assertNotIn("LAST30DAYS_X_BACKEND", surface) |
| 1972 | self._assert_official_vocabulary(report) |
| 1973 | |
| 1974 | def test_bearer_predicts_xapi_with_week_caveat_and_no_network(self): |
| 1975 | secret = "dummy-x-bearer-secret-000" |
| 1976 | config = _grok_bot(X_BEARER_TOKEN=secret, AUTH_TOKEN="dummy-auth-token-secret-000", |
| 1977 | CT0="dummy-ct0-secret-000") |
| 1978 | patches = [ |
| 1979 | mock.patch("lib.http.get", side_effect=AssertionError("doctor made a network call")), |
| 1980 | mock.patch("subprocess.run", side_effect=AssertionError("doctor spawned a subprocess")), |
| 1981 | mock.patch("subprocess.Popen", side_effect=AssertionError("doctor spawned a subprocess")), |
| 1982 | ] |
| 1983 | report = _build_with(config, patches) |
| 1984 | rec = report["sources"]["x"] |
| 1985 | self.assertEqual("ok", rec["status"]) |
| 1986 | self.assertEqual("xapi", rec["active_backend"]) |
| 1987 | self.assertEqual(f"will use: xapi ({BEARER_CAVEAT})", rec["note"]) |
| 1988 | text = doctor.render_text(report) |
| 1989 | self.assertIn(f"will use: xapi ({BEARER_CAVEAT})", text) |
| 1990 | self.assertNotIn(secret, text) |
| 1991 | self.assertNotIn(secret, doctor.render_json(report)) |
| 1992 | backup = rec["backups"][0] |
| 1993 | self.assertEqual("X auth path", backup["name"]) |
| 1994 | self.assertTrue(backup["armed"]) |
| 1995 | self.assertIn("X_BEARER_TOKEN", backup["note"]) |
| 1996 | self.assertIn("about the last week", backup["note"]) |
| 1997 | self.assertTrue(report["setup"]["keys_present"]["X_BEARER_TOKEN"]) |
| 1998 | self._assert_official_vocabulary(report) |
| 1999 | |
| 2000 | def test_xai_key_predicts_xai(self): |
| 2001 | report = _build(_grok_bot(XAI_API_KEY="dummy-xai-secret-000")) |
| 2002 | rec = report["sources"]["x"] |
| 2003 | self.assertEqual("xai", rec["active_backend"]) |
| 2004 | self.assertTrue(rec["note"].startswith("will use: xai")) |
| 2005 | self.assertIn("XAI_API_KEY", rec["backups"][0]["note"]) |
| 2006 | self._assert_official_vocabulary(report) |
| 2007 | |
| 2008 | def test_lane_signal_predicts_connector(self): |
| 2009 | report = _build(_grok_bot(LAST30DAYS_X_HOST_LANE="1")) |
| 2010 | rec = report["sources"]["x"] |
| 2011 | self.assertEqual("ok", rec["status"]) |
| 2012 | self.assertEqual("ok", rec["tier"]) |
| 2013 | self.assertEqual("connector", rec["active_backend"]) |
| 2014 | self.assertEqual("will use: built-in X tools or X connector (host-fetched at run time)", rec["note"]) |
| 2015 | self.assertEqual("", rec["fix"]) |
| 2016 | backup = rec["backups"][0] |
| 2017 | self.assertTrue(backup["armed"]) |
| 2018 | self.assertEqual("host X lane armed (built-in X tools or X connector)", backup["note"]) |
| 2019 | text = "\n".join(_x_text_lines(doctor.render_text(report))) |
| 2020 | self.assertIn("will use: built-in X tools or X connector (host-fetched at run time)", text) |
| 2021 | self.assertIn("host X lane armed (built-in X tools or X connector)", text) |
| 2022 | self._assert_official_vocabulary(report) |
| 2023 | |
| 2024 | def test_lane_with_bearer_keeps_backend_prediction_and_lane_armed(self): |
| 2025 | report = _build(_grok_bot(LAST30DAYS_X_HOST_LANE="1", X_BEARER_TOKEN="dummy-x-bearer-secret-000")) |
| 2026 | rec = report["sources"]["x"] |
| 2027 | self.assertEqual("xapi", rec["active_backend"]) |
| 2028 | self.assertEqual("host X lane armed (built-in X tools or X connector)", rec["backups"][0]["note"]) |
| 2029 | |
| 2030 | def test_bird_pin_names_bird_once_as_pinned(self): |
| 2031 | config = _grok_bot( |
| 2032 | LAST30DAYS_X_BACKEND="bird", |
| 2033 | AUTH_TOKEN="dummy-auth-token-secret-000", |
| 2034 | CT0="dummy-ct0-secret-000", |
| 2035 | ) |
| 2036 | report = _build_with( |
| 2037 | config, |
| 2038 | [mock.patch("lib.bird_x.is_bird_installed", return_value=True)], |
| 2039 | probe_map={"node": health.OK}, |
| 2040 | ) |
| 2041 | rec = report["sources"]["x"] |
| 2042 | self.assertEqual("bird", rec["active_backend"]) |
| 2043 | self.assertEqual("will use: bird (pinned)", rec["note"]) |
| 2044 | x_text = "\n".join(_x_text_lines(doctor.render_text(report))).lower() |
| 2045 | self.assertEqual(1, x_text.count("bird"), x_text) |
| 2046 | for word in GROK_BOT_FORBIDDEN: |
| 2047 | if word != "bird": |
| 2048 | self.assertNotIn(word, x_text, word) |
| 2049 | self.assertNotIn("LAST30DAYS_X_BACKEND", x_text.upper()) |
| 2050 | |
| 2051 | def test_grok_pin_names_grok_once_as_pinned(self): |
| 2052 | report = _build_with(_grok_bot(LAST30DAYS_X_BACKEND="grok"), _grok_signed_in()) |
| 2053 | rec = report["sources"]["x"] |
| 2054 | self.assertEqual("grok", rec["active_backend"]) |
| 2055 | self.assertEqual("will use: grok (pinned)", rec["note"]) |
| 2056 | x_text = "\n".join(_x_text_lines(doctor.render_text(report))).lower() |
| 2057 | self.assertEqual(1, x_text.count("grok"), x_text) |
| 2058 | for word in GROK_BOT_FORBIDDEN: |
| 2059 | self.assertNotIn(word, x_text, word) |
| 2060 | self.assertNotIn("LAST30DAYS_X_BACKEND", x_text.upper()) |
| 2061 | |
| 2062 | def test_bird_pin_without_cookies_prescribes_only_the_official_path(self): |
| 2063 | report = _build(_grok_bot(LAST30DAYS_X_BACKEND="bird")) |
| 2064 | rec = report["sources"]["x"] |
| 2065 | self.assertIsNone(rec["active_backend"]) |
| 2066 | self.assertIn("X_BEARER_TOKEN", rec["fix"]) |
| 2067 | self.assertNotIn("cookie", rec["fix"].lower()) |
| 2068 | self.assertNotIn("--allow-browser-cookies", rec["fix"]) |
| 2069 | |
| 2070 | def test_host_line_prints_resolved_host(self): |
| 2071 | text = doctor.render_text(_build(_grok_bot())) |
| 2072 | self.assertIn("host: grok-bot", text) |
| 2073 | default = _build({}) |
| 2074 | self.assertIsNone(default["config"]["host"]) |
| 2075 | self.assertIn("host: not set", doctor.render_text(default)) |
| 2076 | |
| 2077 | def test_lane_file_line_is_reported_as_ignored(self): |
| 2078 | report = _build(_grok_bot(_X_HOST_LANE_FILE_IGNORED=True)) |
| 2079 | text = doctor.render_text(report) |
| 2080 | self.assertIn("LAST30DAYS_X_HOST_LANE", text) |
| 2081 | self.assertIn("ignored", text) |
| 2082 | self.assertEqual("unconfigured", report["sources"]["x"]["status"]) |
| 2083 | self.assertNotIn("LAST30DAYS_X_HOST_LANE", doctor.render_text(_build(_grok_bot()))) |
| 2084 | |
| 2085 | def test_non_grok_host_prescription_unchanged(self): |
| 2086 | rec = _build({})["sources"]["x"] |
| 2087 | self.assertIs(prescriptions.get("x", "cookies_missing"), prescriptions.for_x({}, "cookies_missing")) |
| 2088 | self.assertIn("cookie", rec["fix"].lower()) |
| 2089 | self.assertEqual("LAST30DAYS_X_BACKEND", rec["pin_var"]) |
| 2090 | self.assertIn("no auth path armed", rec["backups"][0]["note"]) |
| 2091 | |
| 2092 | def test_bearer_without_pin_on_default_host_names_the_xapi_pin(self): |
| 2093 | """xapi is opt-in off Grok Bot: a bare bearer is an unconfigured X |
| 2094 | with a one-line enable, never a broken X with a cookie fix.""" |
| 2095 | rec = _build({"X_BEARER_TOKEN": "dummy-x-bearer-secret-000"})["sources"]["x"] |
| 2096 | self.assertEqual("unconfigured", rec["status"]) |
| 2097 | self.assertEqual("off", rec["tier"]) |
| 2098 | self.assertIsNone(rec["active_backend"]) |
| 2099 | self.assertIn("LAST30DAYS_X_BACKEND=xapi", rec["note"]) |
| 2100 | self.assertEqual("", rec["fix"]) |
| 2101 | self.assertNotIn("dummy-x-bearer", json.dumps(rec)) |
| 2102 | |
| 2103 | def test_xapi_pin_on_default_host_carries_the_caveat(self): |
| 2104 | rec = _build({"LAST30DAYS_X_BACKEND": "xapi", "X_BEARER_TOKEN": "dummy-x-bearer-secret-000"})["sources"]["x"] |
| 2105 | self.assertEqual("xapi", rec["active_backend"]) |
| 2106 | self.assertIn("about the last week", rec["note"]) |
| 2107 | |
| 2108 | |
| 2109 | class HostFingerprintAndCache(unittest.TestCase): |
| 2110 | """The host key, lane signal, and bearer presence all invalidate a cached |
| 2111 | report; the bearer value never lands in the cache file.""" |
| 2112 | |
| 2113 | def test_host_and_lane_keys_change_the_fingerprint(self): |
| 2114 | base = doctor._config_fingerprint({}) |
| 2115 | self.assertNotEqual(base, doctor._config_fingerprint({"LAST30DAYS_HOST": "grok-bot"})) |
| 2116 | self.assertNotEqual(base, doctor._config_fingerprint({"LAST30DAYS_X_HOST_LANE": "1"})) |
| 2117 | self.assertNotEqual(base, doctor._config_fingerprint({"X_BEARER_TOKEN": "dummy-x-bearer-secret-000"})) |
| 2118 | self.assertIn("X_BEARER_TOKEN", doctor.KEY_PRESENCE_VARS) |
| 2119 | self.assertIn("X_BEARER_TOKEN", doctor._SECRET_CONFIG_VARS) |
| 2120 | |
| 2121 | def test_cache_file_never_contains_the_bearer(self): |
| 2122 | secret = "dummy-x-bearer-secret-000" |
| 2123 | config = _grok_bot(X_BEARER_TOKEN=secret) |
| 2124 | tmp = Path(tempfile.mkdtemp()) / "doctor-cache.json" |
| 2125 | with _Hermetic(), mock.patch("lib.doctor.cache_path", return_value=tmp): |
| 2126 | report = doctor.build_report(dict(config)) |
| 2127 | report["generated_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat() |
| 2128 | report["from_cache"] = False |
| 2129 | self.assertTrue(doctor._write_cache(report, config)) |
| 2130 | served = doctor.read_cached_report(config) |
| 2131 | self.assertNotIn(secret, tmp.read_text(encoding="utf-8")) |
| 2132 | self.assertIsNotNone(served) |
| 2133 | self.assertEqual("xapi", served["sources"]["x"]["active_backend"]) |
| 2134 | # A bearer that was tampered into a fake report is refused. |
| 2135 | report["sources"]["x"]["detail"] = secret |
| 2136 | with mock.patch("lib.doctor.cache_path", return_value=tmp): |
| 2137 | self.assertFalse(doctor._write_cache(report, config)) |
| 2138 | |
| 2139 | |
| 2140 | class GrokBotParityTable(unittest.TestCase): |
| 2141 | """host x bearer x lane x pin: doctor's prediction equals the pipeline's |
| 2142 | pre-failover selection, and Grok Bot output carries no R4 vocabulary.""" |
| 2143 | |
| 2144 | def test_doctor_prediction_matches_pipeline_selection(self): |
| 2145 | cases = itertools.product( |
| 2146 | ("", "grok-bot"), (False, True), (False, True), (None, "bird", "grok", "xapi") |
| 2147 | ) |
| 2148 | for host, bearer, lane, pin in cases: |
| 2149 | config = {} |
| 2150 | if host: |
| 2151 | config["LAST30DAYS_HOST"] = host |
| 2152 | if bearer: |
| 2153 | config["X_BEARER_TOKEN"] = "dummy-x-bearer-secret-000" |
| 2154 | if lane: |
| 2155 | config["LAST30DAYS_X_HOST_LANE"] = "1" |
| 2156 | if pin: |
| 2157 | config["LAST30DAYS_X_BACKEND"] = pin |
| 2158 | with self.subTest(host=host or "default", bearer=bearer, lane=lane, pin=pin): |
| 2159 | patches = _grok_signed_in() |
| 2160 | with _Hermetic(): |
| 2161 | for p in patches: |
| 2162 | p.start() |
| 2163 | try: |
| 2164 | chain = env.x_backend_chain(dict(config), local_only=True) |
| 2165 | report = doctor.build_report(dict(config)) |
| 2166 | finally: |
| 2167 | for p in reversed(patches): |
| 2168 | p.stop() |
| 2169 | expected = chain[0] if chain else ("connector" if lane else None) |
| 2170 | rec = report["sources"]["x"] |
| 2171 | self.assertEqual(expected, rec["active_backend"]) |
| 2172 | if host != "grok-bot": |
| 2173 | continue |
| 2174 | x_text = "\n".join(_x_text_lines(doctor.render_text(report))).lower() |
| 2175 | blob = json.dumps(rec).lower() |
| 2176 | allow = {pin} if pin in ("bird", "grok") else set() |
| 2177 | for word in GROK_BOT_FORBIDDEN: |
| 2178 | if word in allow: |
| 2179 | continue |
| 2180 | self.assertNotIn(word, x_text, word) |
| 2181 | if not allow: |
| 2182 | self.assertNotIn(word, blob, word) |
| 2183 | if allow and expected == pin: |
| 2184 | self.assertLessEqual(x_text.count(pin), 1, x_text) |
| 2185 | self.assertNotIn("last30days_x_backend", x_text) |
| 2186 | |
| 2187 | |
| 2188 | def _grok_probe_raises(): |
| 2189 | """A grok probe whose filesystem scan is denied, as issue #1448 reports it.""" |
| 2190 | return [ |
| 2191 | mock.patch( |
| 2192 | "lib.health._off_path_binary", |
| 2193 | side_effect=PermissionError("simulated denial"), |
| 2194 | ), |
| 2195 | ] |
| 2196 | |
| 2197 | |
| 2198 | class GrokProbeThatCouldNotRun(unittest.TestCase): |
| 2199 | """Issue #1448: a failed probe is not a broken credential store. |
| 2200 | |
| 2201 | backends._run_probe records a raised probe as ERROR with a |
| 2202 | "probe failed: ..." detail. Doctor read every grok ERROR as a corrupt |
| 2203 | store, so it claimed a break it never observed and returned before the |
| 2204 | bearer lane could be named. |
| 2205 | """ |
| 2206 | |
| 2207 | def test_unchecked_probe_keeps_cookie_guidance_without_claiming_a_broken_store(self): |
| 2208 | report = _build_with({}, _grok_probe_raises()) |
| 2209 | |
| 2210 | rec = report["sources"]["x"] |
| 2211 | self.assertEqual("unconfigured", rec["status"]) |
| 2212 | self.assertEqual("off", rec["tier"]) |
| 2213 | self.assertIn("cookie", rec["fix"].lower()) |
| 2214 | self.assertIn("could not be checked", rec["note"].lower()) |
| 2215 | self.assertNotIn("store is broken", rec["note"].lower()) |
| 2216 | |
| 2217 | def test_unchecked_probe_does_not_hide_the_opt_in_bearer_lane(self): |
| 2218 | placeholder = "dummy-x-bearer-value" |
| 2219 | report = _build_with({"X_BEARER_TOKEN": placeholder}, _grok_probe_raises()) |
| 2220 | |
| 2221 | rec = report["sources"]["x"] |
| 2222 | self.assertIn("LAST30DAYS_X_BACKEND=xapi", rec["note"]) |
| 2223 | self.assertIn("could not be checked", rec["note"].lower()) |
| 2224 | self.assertEqual("", rec["fix"]) |
| 2225 | self.assertNotIn(placeholder, json.dumps(rec)) |
| 2226 | text = doctor.render_text(report) |
| 2227 | self.assertNotIn(placeholder, text) |
| 2228 | self.assertNotIn("store is broken", text.lower()) |
| 2229 | |
| 2230 | def test_a_store_that_really_could_not_be_read_is_still_named(self): |
| 2231 | patches = [ |
| 2232 | mock.patch( |
| 2233 | "lib.backends.which", |
| 2234 | lambda n: "/usr/bin/grok" if n == "grok" else None, |
| 2235 | ), |
| 2236 | mock.patch("lib.grok_audit.cached_status", return_value=None), |
| 2237 | mock.patch( |
| 2238 | "lib.grok_x.stored_auth_status", |
| 2239 | return_value=(grok_x.AUTH_ERROR, "PermissionError: denied", None), |
| 2240 | ), |
| 2241 | ] |
| 2242 | report = _build_with({}, patches) |
| 2243 | |
| 2244 | rec = report["sources"]["x"] |
| 2245 | self.assertIn("store is broken", rec["note"].lower()) |
| 2246 | |
| 2247 | |
| 2248 | class UnsubstitutedTemplateReporting(unittest.TestCase): |
| 2249 | """Issue #1081 defect 2: a rejected `${user_config.*}` placeholder is named |
| 2250 | as unsubstituted instead of reading as "nothing configured".""" |
| 2251 | |
| 2252 | def test_setup_block_carries_the_rejected_key_names(self): |
| 2253 | block = doctor._setup_block({env.TEMPLATE_CONFIG_KEYS: ["GEMINI_API_KEY"]}) |
| 2254 | |
| 2255 | self.assertEqual(["GEMINI_API_KEY"], block["unsubstituted_templates"]) |
| 2256 | self.assertFalse(block["keys_present"]["GEMINI_API_KEY"]) |
| 2257 | |
| 2258 | def test_setup_block_defaults_to_an_empty_list(self): |
| 2259 | self.assertEqual([], doctor._setup_block({})["unsubstituted_templates"]) |
| 2260 | |
| 2261 | def test_render_names_the_template_without_listing_it_as_present(self): |
| 2262 | report = _build({env.TEMPLATE_CONFIG_KEYS: ["GEMINI_API_KEY"]}) |
| 2263 | |
| 2264 | text = doctor.render_text(report) |
| 2265 | |
| 2266 | self.assertIn( |
| 2267 | "unsubstituted config template(s), counted as unset: GEMINI_API_KEY", text |
| 2268 | ) |
| 2269 | self.assertNotIn("credentials present: GEMINI_API_KEY", text) |
| 2270 | |
| 2271 | def test_render_is_unchanged_without_templates(self): |
| 2272 | self.assertNotIn( |
| 2273 | "unsubstituted config template(s)", doctor.render_text(_build({})) |
| 2274 | ) |
| 2275 | |
| 2276 | |
| 2277 | if __name__ == "__main__": |
| 2278 | unittest.main() |
| 2279 | |
| 2280 |