| 1 | """Tests for the first-run setup wizard module.""" |
| 2 | |
| 3 | import io |
| 4 | import json |
| 5 | import os |
| 6 | import subprocess |
| 7 | import sys |
| 8 | import tempfile |
| 9 | from pathlib import Path |
| 10 | from unittest.mock import patch, MagicMock |
| 11 | |
| 12 | import pytest |
| 13 | |
| 14 | from lib import setup_wizard |
| 15 | import last30days as cli |
| 16 | |
| 17 | |
| 18 | class _NtOs: |
| 19 | """Delegates to the real os module but reports name == 'nt'. |
| 20 | |
| 21 | Patched only in setup_wizard's own namespace (mirrors |
| 22 | tests/test_health_probe_taxonomy.py's ``_NtOs``) so pathlib and the rest |
| 23 | of the test process are unaffected. |
| 24 | """ |
| 25 | name = "nt" |
| 26 | |
| 27 | def __getattr__(self, attr): |
| 28 | return getattr(os, attr) |
| 29 | |
| 30 | |
| 31 | class _PosixOs: |
| 32 | """Delegates to the real os module but reports name == 'posix'.""" |
| 33 | name = "posix" |
| 34 | |
| 35 | def __getattr__(self, attr): |
| 36 | return getattr(os, attr) |
| 37 | |
| 38 | |
| 39 | class TestIsFirstRun: |
| 40 | """Tests for is_first_run().""" |
| 41 | |
| 42 | def test_first_run_when_setup_complete_not_set(self): |
| 43 | """SETUP_COMPLETE not in config -> first run.""" |
| 44 | config = {"AUTH_TOKEN": "abc", "CT0": "xyz"} |
| 45 | assert setup_wizard.is_first_run(config) is True |
| 46 | |
| 47 | def test_first_run_when_setup_complete_is_none(self): |
| 48 | """SETUP_COMPLETE=None -> first run.""" |
| 49 | config = {"SETUP_COMPLETE": None} |
| 50 | assert setup_wizard.is_first_run(config) is True |
| 51 | |
| 52 | def test_first_run_when_setup_complete_is_empty(self): |
| 53 | """SETUP_COMPLETE="" -> first run.""" |
| 54 | config = {"SETUP_COMPLETE": ""} |
| 55 | assert setup_wizard.is_first_run(config) is True |
| 56 | |
| 57 | def test_not_first_run_when_setup_complete_true(self): |
| 58 | """SETUP_COMPLETE=true -> not first run.""" |
| 59 | config = {"SETUP_COMPLETE": "true"} |
| 60 | assert setup_wizard.is_first_run(config) is False |
| 61 | |
| 62 | def test_not_first_run_when_setup_complete_any_value(self): |
| 63 | """SETUP_COMPLETE set to any truthy value -> not first run.""" |
| 64 | config = {"SETUP_COMPLETE": "yes"} |
| 65 | assert setup_wizard.is_first_run(config) is False |
| 66 | |
| 67 | |
| 68 | class TestRunAutoSetup: |
| 69 | """Tests for run_auto_setup().""" |
| 70 | |
| 71 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 72 | @patch("shutil.which") |
| 73 | def test_cookies_found(self, mock_which, mock_extract): |
| 74 | """When cookies are found, results dict includes them.""" |
| 75 | mock_extract.return_value = ({"auth_token": "abc", "ct0": "xyz"}, "chrome") |
| 76 | mock_which.return_value = "/usr/local/bin/yt-dlp" |
| 77 | |
| 78 | config = {} |
| 79 | results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True) |
| 80 | |
| 81 | assert "x" in results["cookies_found"] |
| 82 | assert results["cookies_found"]["x"] == "chrome" |
| 83 | assert results["ytdlp_installed"] is True |
| 84 | assert results["ytdlp_action"] == "already_installed" |
| 85 | assert results["env_written"] is False |
| 86 | assert results["browser_cookie_scan_attempted"] is True |
| 87 | |
| 88 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 89 | @patch("shutil.which") |
| 90 | def test_no_cookies_found(self, mock_which, mock_extract, monkeypatch): |
| 91 | """When no cookies found, results dict has empty cookies_found.""" |
| 92 | monkeypatch.setattr(setup_wizard, "os", _PosixOs()) |
| 93 | mock_extract.return_value = None |
| 94 | mock_which.return_value = None |
| 95 | |
| 96 | config = {} |
| 97 | results = setup_wizard.run_auto_setup(config) |
| 98 | |
| 99 | assert results["cookies_found"] == {} |
| 100 | mock_extract.assert_not_called() |
| 101 | assert results["browser_cookie_scan_attempted"] is False |
| 102 | assert results["ytdlp_installed"] is False |
| 103 | assert results["ytdlp_action"] == "no_homebrew" |
| 104 | |
| 105 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 106 | @patch("shutil.which") |
| 107 | def test_cookie_extraction_exception(self, mock_which, mock_extract): |
| 108 | """Cookie extraction raising an exception is handled gracefully.""" |
| 109 | mock_extract.side_effect = Exception("DB locked") |
| 110 | mock_which.return_value = None |
| 111 | |
| 112 | config = {} |
| 113 | results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True) |
| 114 | |
| 115 | assert results["cookies_found"] == {} |
| 116 | assert results["browser_cookie_scan_attempted"] is True |
| 117 | |
| 118 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 119 | @patch("shutil.which") |
| 120 | def test_multiple_sources(self, mock_which, mock_extract): |
| 121 | """Multiple cookie sources can be found.""" |
| 122 | def side_effect(browser, domain, cookie_names): |
| 123 | if domain == ".x.com": |
| 124 | return ({"auth_token": "abc", "ct0": "xyz"}, "firefox") |
| 125 | elif domain == ".truthsocial.com": |
| 126 | return ({"_session_id": "sess123"}, "firefox") |
| 127 | return None |
| 128 | |
| 129 | mock_extract.side_effect = side_effect |
| 130 | mock_which.return_value = None |
| 131 | |
| 132 | config = {} |
| 133 | results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True) |
| 134 | |
| 135 | assert results["cookies_found"]["x"] == "firefox" |
| 136 | assert results["cookies_found"]["truthsocial"] == "firefox" |
| 137 | |
| 138 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 139 | @patch("shutil.which") |
| 140 | def test_default_scan_order_is_chromium_first(self, mock_which, mock_extract): |
| 141 | """U1: with FROM_BROWSER unset, the scan tries Chrome before Safari. |
| 142 | |
| 143 | Safari is the only X-cookie source needing Full Disk Access; Chrome |
| 144 | reads via the Keychain with no FDA. The wizard must try the Chromium |
| 145 | family first so the common macOS user does not hit the FDA dead-end. |
| 146 | """ |
| 147 | tried = [] |
| 148 | |
| 149 | def side_effect(browser, domain, cookie_names): |
| 150 | tried.append(browser) |
| 151 | return None # never find cookies, so every browser is attempted |
| 152 | |
| 153 | mock_extract.side_effect = side_effect |
| 154 | mock_which.return_value = None |
| 155 | |
| 156 | setup_wizard.run_auto_setup({}, allow_browser_cookies=True) |
| 157 | |
| 158 | # Order within the first domain's attempts must be chromium-first. |
| 159 | assert "chrome" in tried and "safari" in tried |
| 160 | assert tried.index("chrome") < tried.index("safari") |
| 161 | assert tried.index("chrome") < tried.index("firefox") |
| 162 | assert "opera" in tried |
| 163 | assert tried.index("opera") < tried.index("firefox") |
| 164 | assert tried.index("opera") < tried.index("safari") |
| 165 | # And it must not route through the silent-first "auto" order. |
| 166 | assert tried[0] == "chrome" |
| 167 | |
| 168 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 169 | @patch("shutil.which") |
| 170 | def test_default_scan_includes_dia(self, mock_which, mock_extract): |
| 171 | """The default scan list is hardcoded, so a new browser must be added here too. |
| 172 | |
| 173 | Runtime support alone is not enough: a first-run user whose only X |
| 174 | session lives in Dia has no FROM_BROWSER set, so the wizard's own list |
| 175 | is the only thing that decides whether Dia is ever probed. |
| 176 | """ |
| 177 | tried = [] |
| 178 | |
| 179 | def side_effect(browser, domain, cookie_names): |
| 180 | tried.append(browser) |
| 181 | return None |
| 182 | |
| 183 | mock_extract.side_effect = side_effect |
| 184 | mock_which.return_value = None |
| 185 | |
| 186 | setup_wizard.run_auto_setup({}, allow_browser_cookies=True) |
| 187 | |
| 188 | assert "dia" in tried |
| 189 | assert tried.index("dia") < tried.index("safari") |
| 190 | assert "ardia" in tried |
| 191 | assert tried.index("ardia") < tried.index("safari") |
| 192 | |
| 193 | |
| 194 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 195 | @patch("shutil.which") |
| 196 | def test_official_only_host_skips_cookie_loop_for_every_domain(self, mock_which, mock_extract): |
| 197 | """U6/R5: on an official-only host (LAST30DAYS_HOST=grok-bot) the |
| 198 | consented cookie scan is skipped for X AND Truth Social, the result |
| 199 | records a neutral note, and the CLI installs (yt-dlp) still run.""" |
| 200 | mock_extract.return_value = ({"auth_token": "abc", "ct0": "xyz"}, "chrome") |
| 201 | mock_which.return_value = "/usr/local/bin/yt-dlp" |
| 202 | |
| 203 | config = {"LAST30DAYS_HOST": "grok-bot"} |
| 204 | results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True) |
| 205 | |
| 206 | mock_extract.assert_not_called() |
| 207 | assert results["cookies_found"] == {} |
| 208 | assert results["browser_cookie_scan_attempted"] is False |
| 209 | assert results["cookie_note"] == "browser sessions are not read on this host" |
| 210 | # The free CLI installs still run: the yt-dlp probe happened. |
| 211 | assert any(call.args[:1] == ("yt-dlp",) for call in mock_which.call_args_list) |
| 212 | assert results["ytdlp_installed"] is True |
| 213 | assert results["ytdlp_action"] == "already_installed" |
| 214 | |
| 215 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 216 | @patch("shutil.which") |
| 217 | def test_official_only_host_status_text_names_no_cookies(self, mock_which, mock_extract): |
| 218 | """R4: the setup summary on an official-only host never names cookies.""" |
| 219 | mock_which.return_value = None |
| 220 | results = setup_wizard.run_auto_setup( |
| 221 | {"LAST30DAYS_HOST": "grok-bot"}, allow_browser_cookies=True |
| 222 | ) |
| 223 | results["env_written"] = True # what the CLI sets before rendering |
| 224 | text = setup_wizard.get_setup_status_text(results) |
| 225 | assert setup_wizard.OFFICIAL_HOST_COOKIE_NOTE in text |
| 226 | assert "Configuration saved." in text |
| 227 | lowered = text.lower() |
| 228 | for banned in ("cookies", "cdp", "box-chrome", "bird", "auth_token", "ct0", "xquik", "browsers"): |
| 229 | assert banned not in lowered, f"{banned!r} leaked into setup status text: {text!r}" |
| 230 | |
| 231 | def test_status_text_without_note_keeps_browser_tail(self): |
| 232 | """R14: non-Grok hosts keep today's status tail byte for byte.""" |
| 233 | text = setup_wizard.get_setup_status_text({"env_written": True, "ytdlp_action": "already_installed"}) |
| 234 | assert "Configuration saved. Future runs will auto-detect your browsers." in text |
| 235 | |
| 236 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 237 | @patch("shutil.which") |
| 238 | def test_bird_pin_on_official_only_host_re_enables_cookie_scan(self, mock_which, mock_extract): |
| 239 | """KTD7: the exclusive LAST30DAYS_X_BACKEND=bird pin is the one path |
| 240 | that re-enables discovery on an official-only host.""" |
| 241 | mock_extract.return_value = None |
| 242 | mock_which.return_value = None |
| 243 | config = {"LAST30DAYS_HOST": "grok-bot", "LAST30DAYS_X_BACKEND": "bird"} |
| 244 | results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True) |
| 245 | assert mock_extract.called |
| 246 | assert results["browser_cookie_scan_attempted"] is True |
| 247 | assert "cookie_note" not in results |
| 248 | |
| 249 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 250 | @patch("shutil.which") |
| 251 | def test_partial_pair_not_recorded_as_found(self, mock_which, mock_extract): |
| 252 | """A partial X pair (lone ct0) is not a found source.""" |
| 253 | mock_extract.return_value = ({"ct0": "lone_ct0"}, "chrome") |
| 254 | mock_which.return_value = None |
| 255 | |
| 256 | results = setup_wizard.run_auto_setup({}, allow_browser_cookies=True) |
| 257 | |
| 258 | assert results["cookies_found"] == {} |
| 259 | assert results["browser_cookie_scan_attempted"] is True |
| 260 | |
| 261 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 262 | @patch("shutil.which") |
| 263 | def test_partial_then_complete_records_complete_source(self, mock_which, mock_extract): |
| 264 | """The scan keeps looking past a partial pair and records the |
| 265 | browser that yielded the complete one.""" |
| 266 | def side_effect(browser, domain, cookie_names): |
| 267 | if domain == ".x.com": |
| 268 | if browser == "chrome": |
| 269 | return ({"ct0": "lone_ct0"}, "chrome") |
| 270 | if browser == "firefox": |
| 271 | return ({"auth_token": "abc", "ct0": "xyz"}, "firefox") |
| 272 | return None |
| 273 | mock_extract.side_effect = side_effect |
| 274 | mock_which.return_value = None |
| 275 | |
| 276 | config = {"FROM_BROWSER": "chrome,firefox"} |
| 277 | results = setup_wizard.run_auto_setup(config, allow_browser_cookies=True) |
| 278 | |
| 279 | assert results["cookies_found"]["x"] == "firefox" |
| 280 | |
| 281 | |
| 282 | class TestYtdlpAutoInstall: |
| 283 | """Tests for yt-dlp auto-install via Homebrew in run_auto_setup().""" |
| 284 | |
| 285 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 286 | @patch("subprocess.run") |
| 287 | @patch("shutil.which") |
| 288 | def test_ytdlp_missing_brew_available_installs(self, mock_which, mock_subproc, mock_extract, monkeypatch): |
| 289 | """yt-dlp missing + brew available (non-Windows) -> installs via brew.""" |
| 290 | monkeypatch.setattr(setup_wizard, "os", _PosixOs()) |
| 291 | def which_side_effect(cmd): |
| 292 | if cmd == "yt-dlp": |
| 293 | return None |
| 294 | if cmd == "brew": |
| 295 | return "/opt/homebrew/bin/brew" |
| 296 | return None |
| 297 | mock_which.side_effect = which_side_effect |
| 298 | mock_subproc.return_value = MagicMock(returncode=0, stderr="") |
| 299 | |
| 300 | results = setup_wizard.run_auto_setup({}) |
| 301 | |
| 302 | mock_subproc.assert_called_once_with( |
| 303 | ["brew", "install", "yt-dlp"], |
| 304 | capture_output=True, text=True, timeout=120, |
| 305 | ) |
| 306 | assert results["ytdlp_installed"] is True |
| 307 | assert results["ytdlp_action"] == "installed" |
| 308 | |
| 309 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 310 | @patch("shutil.which") |
| 311 | def test_ytdlp_missing_brew_missing(self, mock_which, mock_extract, monkeypatch): |
| 312 | """yt-dlp missing + brew missing (non-Windows) -> no_homebrew.""" |
| 313 | monkeypatch.setattr(setup_wizard, "os", _PosixOs()) |
| 314 | mock_which.return_value = None |
| 315 | |
| 316 | results = setup_wizard.run_auto_setup({}) |
| 317 | |
| 318 | assert results["ytdlp_installed"] is False |
| 319 | assert results["ytdlp_action"] == "no_homebrew" |
| 320 | |
| 321 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 322 | @patch("shutil.which") |
| 323 | def test_ytdlp_missing_on_windows(self, mock_which, mock_extract, monkeypatch): |
| 324 | """Regression for #904: yt-dlp missing on Windows -> pip guidance, no |
| 325 | Homebrew attempt (Windows has no Homebrew and pip is the working path).""" |
| 326 | monkeypatch.setattr(setup_wizard, "os", _NtOs()) |
| 327 | mock_which.return_value = None |
| 328 | |
| 329 | with patch("subprocess.run") as mock_subproc: |
| 330 | results = setup_wizard.run_auto_setup({}) |
| 331 | mock_subproc.assert_not_called() |
| 332 | |
| 333 | assert results["ytdlp_installed"] is False |
| 334 | assert results["ytdlp_action"] == "no_pip_windows" |
| 335 | |
| 336 | text = setup_wizard.get_setup_status_text(results) |
| 337 | assert "pip install yt-dlp" in text |
| 338 | assert "Homebrew" not in text |
| 339 | assert "Scripts" in text |
| 340 | |
| 341 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 342 | @patch("shutil.which") |
| 343 | def test_ytdlp_already_installed(self, mock_which, mock_extract): |
| 344 | """yt-dlp already installed -> already_installed.""" |
| 345 | mock_which.return_value = "/usr/local/bin/yt-dlp" |
| 346 | |
| 347 | results = setup_wizard.run_auto_setup({}) |
| 348 | |
| 349 | assert results["ytdlp_installed"] is True |
| 350 | assert results["ytdlp_action"] == "already_installed" |
| 351 | |
| 352 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 353 | @patch("subprocess.run") |
| 354 | @patch("shutil.which") |
| 355 | def test_brew_install_fails(self, mock_which, mock_subproc, mock_extract, monkeypatch): |
| 356 | """brew install yt-dlp fails (non-Windows) -> install_failed with stderr.""" |
| 357 | monkeypatch.setattr(setup_wizard, "os", _PosixOs()) |
| 358 | def which_side_effect(cmd): |
| 359 | if cmd == "yt-dlp": |
| 360 | return None |
| 361 | if cmd == "brew": |
| 362 | return "/opt/homebrew/bin/brew" |
| 363 | return None |
| 364 | mock_which.side_effect = which_side_effect |
| 365 | mock_subproc.return_value = MagicMock(returncode=1, stderr="Error: something broke") |
| 366 | |
| 367 | results = setup_wizard.run_auto_setup({}) |
| 368 | |
| 369 | assert results["ytdlp_installed"] is False |
| 370 | assert results["ytdlp_action"] == "install_failed" |
| 371 | assert "something broke" in results["ytdlp_stderr"] |
| 372 | |
| 373 | |
| 374 | class TestDiggAutoInstall: |
| 375 | """Tests for digg-pp-cli auto-install via npx in run_auto_setup().""" |
| 376 | |
| 377 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 378 | @patch("shutil.which") |
| 379 | def test_digg_already_installed(self, mock_which, mock_extract): |
| 380 | """digg-pp-cli already on PATH -> already_installed, no subprocess.""" |
| 381 | # yt-dlp missing + brew missing keeps the yt-dlp path subprocess-free; |
| 382 | # digg-pp-cli present short-circuits before any npx call. |
| 383 | def which_side_effect(cmd): |
| 384 | return "/Users/me/go/bin/digg-pp-cli" if cmd == "digg-pp-cli" else None |
| 385 | mock_which.side_effect = which_side_effect |
| 386 | |
| 387 | with patch("subprocess.run") as mock_subproc: |
| 388 | results = setup_wizard.run_auto_setup({}) |
| 389 | mock_subproc.assert_not_called() |
| 390 | |
| 391 | assert results["digg_installed"] is True |
| 392 | assert results["digg_action"] == "already_installed" |
| 393 | |
| 394 | # Redirect HOME/GOPATH so real ~/.local/bin or ~/go/bin digg-pp-cli on the |
| 395 | # dev box does not make the binary look present during absence tests. |
| 396 | # USERPROFILE too: Path.home() reads it on Windows, and the two must agree. |
| 397 | @staticmethod |
| 398 | def _empty_home(tmp_path, monkeypatch): |
| 399 | monkeypatch.delenv("GOPATH", raising=False) |
| 400 | monkeypatch.setenv("HOME", str(tmp_path)) |
| 401 | monkeypatch.setenv("USERPROFILE", str(tmp_path)) |
| 402 | |
| 403 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 404 | @patch("shutil.which") |
| 405 | def test_digg_no_npx(self, mock_which, mock_extract, tmp_path, monkeypatch): |
| 406 | """digg-pp-cli missing + npx missing -> no_npx, no subprocess.""" |
| 407 | self._empty_home(tmp_path, monkeypatch) |
| 408 | mock_which.return_value = None |
| 409 | |
| 410 | with patch("subprocess.run") as mock_subproc: |
| 411 | results = setup_wizard.run_auto_setup({}) |
| 412 | mock_subproc.assert_not_called() |
| 413 | |
| 414 | assert results["digg_installed"] is False |
| 415 | assert results["digg_action"] == "no_npx" |
| 416 | |
| 417 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 418 | @patch("subprocess.run") |
| 419 | @patch("shutil.which") |
| 420 | def test_digg_install_succeeds(self, mock_which, mock_subproc, mock_extract, tmp_path, monkeypatch): |
| 421 | """npx present + install succeeds + binary verifiable -> installed.""" |
| 422 | self._empty_home(tmp_path, monkeypatch) |
| 423 | # First which("digg-pp-cli") (pre-install) -> None, npx -> present, |
| 424 | # then post-install which("digg-pp-cli") -> resolves. |
| 425 | calls = {"digg": 0} |
| 426 | |
| 427 | def which_side_effect(cmd): |
| 428 | if cmd == "digg-pp-cli": |
| 429 | calls["digg"] += 1 |
| 430 | return None if calls["digg"] == 1 else "/Users/me/go/bin/digg-pp-cli" |
| 431 | if cmd == "npx": |
| 432 | return "/opt/homebrew/bin/npx" |
| 433 | return None |
| 434 | mock_which.side_effect = which_side_effect |
| 435 | mock_subproc.return_value = MagicMock(returncode=0, stderr="") |
| 436 | |
| 437 | results = setup_wizard.run_auto_setup({}) |
| 438 | |
| 439 | # The wizard now also best-effort-installs the additional default-on |
| 440 | # Printing Press sources (arxiv/techmeme/trustpilot), so digg is one of |
| 441 | # several install calls rather than the only one. Argv[0] must be the |
| 442 | # *resolved* npx path (mirroring shutil.which's return value), not the |
| 443 | # bare "npx" string -- passing the bare name breaks Windows, where |
| 444 | # shutil.which resolves PATHEXT (npx.CMD) but subprocess.run does not. |
| 445 | mock_subproc.assert_any_call( |
| 446 | ["/opt/homebrew/bin/npx", "-y", setup_wizard.PRINTING_PRESS_NPM, "install", "digg", "--cli-only"], |
| 447 | capture_output=True, text=True, timeout=setup_wizard.DIGG_INSTALL_TIMEOUT, |
| 448 | ) |
| 449 | assert results["digg_installed"] is True |
| 450 | assert results["digg_action"] == "installed" |
| 451 | |
| 452 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 453 | @patch("subprocess.run") |
| 454 | @patch("shutil.which") |
| 455 | def test_digg_install_uses_resolved_windows_npx_path( |
| 456 | self, mock_which, mock_subproc, mock_extract, tmp_path, monkeypatch |
| 457 | ): |
| 458 | """Regression for #904: a Windows-style resolved npx path (PATHEXT |
| 459 | resolution, e.g. npx.CMD) must be passed to subprocess.run verbatim -- |
| 460 | not the bare string "npx", which fails with WinError 2 on Windows |
| 461 | because CreateProcess does not do PATHEXT resolution the way |
| 462 | shutil.which does.""" |
| 463 | self._empty_home(tmp_path, monkeypatch) |
| 464 | calls = {"digg": 0} |
| 465 | windows_npx = r"C:\Program Files\nodejs\npx.CMD" |
| 466 | |
| 467 | def which_side_effect(cmd): |
| 468 | if cmd == "digg-pp-cli": |
| 469 | calls["digg"] += 1 |
| 470 | return None if calls["digg"] == 1 else r"C:\Users\me\.local\bin\digg-pp-cli" |
| 471 | if cmd == "npx": |
| 472 | return windows_npx |
| 473 | return None |
| 474 | mock_which.side_effect = which_side_effect |
| 475 | mock_subproc.return_value = MagicMock(returncode=0, stderr="") |
| 476 | |
| 477 | results = setup_wizard.run_auto_setup({}) |
| 478 | |
| 479 | mock_subproc.assert_any_call( |
| 480 | [windows_npx, "-y", setup_wizard.PRINTING_PRESS_NPM, "install", "digg", "--cli-only"], |
| 481 | capture_output=True, text=True, timeout=setup_wizard.DIGG_INSTALL_TIMEOUT, |
| 482 | ) |
| 483 | assert results["digg_installed"] is True |
| 484 | assert results["digg_action"] == "installed" |
| 485 | |
| 486 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 487 | @patch("subprocess.run") |
| 488 | @patch("shutil.which") |
| 489 | def test_digg_install_fails_nonzero(self, mock_which, mock_subproc, mock_extract, tmp_path, monkeypatch): |
| 490 | """npx install returns non-zero -> install_failed with stderr.""" |
| 491 | self._empty_home(tmp_path, monkeypatch) |
| 492 | def which_side_effect(cmd): |
| 493 | return "/opt/homebrew/bin/npx" if cmd == "npx" else None |
| 494 | mock_which.side_effect = which_side_effect |
| 495 | mock_subproc.return_value = MagicMock(returncode=1, stderr="npm ERR! boom") |
| 496 | |
| 497 | results = setup_wizard.run_auto_setup({}) |
| 498 | |
| 499 | assert results["digg_installed"] is False |
| 500 | assert results["digg_action"] == "install_failed" |
| 501 | assert "boom" in results["digg_stderr"] |
| 502 | |
| 503 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 504 | @patch("shutil.which") |
| 505 | def test_digg_prior_install_off_path(self, mock_which, mock_extract, tmp_path, monkeypatch): |
| 506 | """pp-digg CLI at ~/.local/bin but not on PATH -> installed_off_path, no npx.""" |
| 507 | self._empty_home(tmp_path, monkeypatch) |
| 508 | local_bin = tmp_path / ".local" / "bin" |
| 509 | local_bin.mkdir(parents=True) |
| 510 | binary = local_bin / "digg-pp-cli" |
| 511 | binary.write_text("#!/bin/sh\n") |
| 512 | binary.chmod(0o755) |
| 513 | mock_which.return_value = None |
| 514 | |
| 515 | with patch("subprocess.run") as mock_subproc: |
| 516 | results = setup_wizard.run_auto_setup({}) |
| 517 | mock_subproc.assert_not_called() |
| 518 | |
| 519 | assert results["digg_installed"] is False |
| 520 | assert results["digg_action"] == "installed_off_path" |
| 521 | assert results["digg_path"] == str(binary) |
| 522 | |
| 523 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 524 | @patch("subprocess.run") |
| 525 | @patch("shutil.which") |
| 526 | def test_digg_install_zero_but_not_on_path(self, mock_which, mock_subproc, mock_extract, tmp_path, monkeypatch): |
| 527 | """rc=0, binary at $HOME/.local/bin but not on PATH -> installed_off_path.""" |
| 528 | self._empty_home(tmp_path, monkeypatch) |
| 529 | def which_side_effect(cmd): |
| 530 | return "/opt/homebrew/bin/npx" if cmd == "npx" else None |
| 531 | mock_which.side_effect = which_side_effect |
| 532 | |
| 533 | local_bin = tmp_path / ".local" / "bin" |
| 534 | |
| 535 | def fake_install(*args, **kwargs): |
| 536 | local_bin.mkdir(parents=True, exist_ok=True) |
| 537 | binary = local_bin / "digg-pp-cli" |
| 538 | binary.write_text("#!/bin/sh\n") |
| 539 | binary.chmod(0o755) |
| 540 | return MagicMock(returncode=0, stderr="") |
| 541 | mock_subproc.side_effect = fake_install |
| 542 | |
| 543 | results = setup_wizard.run_auto_setup({}) |
| 544 | |
| 545 | assert results["digg_installed"] is False |
| 546 | assert results["digg_action"] == "installed_off_path" |
| 547 | assert results["digg_path"] == str(local_bin / "digg-pp-cli") |
| 548 | |
| 549 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 550 | @patch("subprocess.run") |
| 551 | @patch("shutil.which") |
| 552 | def test_digg_install_timeout_does_not_raise(self, mock_which, mock_subproc, mock_extract, tmp_path, monkeypatch): |
| 553 | """subprocess raising (e.g. timeout) -> install_failed, no exception escapes.""" |
| 554 | self._empty_home(tmp_path, monkeypatch) |
| 555 | def which_side_effect(cmd): |
| 556 | return "/opt/homebrew/bin/npx" if cmd == "npx" else None |
| 557 | mock_which.side_effect = which_side_effect |
| 558 | mock_subproc.side_effect = subprocess.TimeoutExpired(cmd="npx", timeout=300) |
| 559 | |
| 560 | results = setup_wizard.run_auto_setup({}) |
| 561 | |
| 562 | assert results["digg_installed"] is False |
| 563 | assert results["digg_action"] == "install_failed" |
| 564 | |
| 565 | |
| 566 | class TestDiggUpgrade: |
| 567 | """A Digg helper already on PATH but older than the engine can call is |
| 568 | upgraded by re-running the pinned catalog install. No real npx runs: the |
| 569 | version exec and the install subprocess are both stubbed.""" |
| 570 | |
| 571 | DIGG = "/Users/me/.local/bin/digg-pp-cli" |
| 572 | NPX = "/opt/homebrew/bin/npx" |
| 573 | |
| 574 | def _run(self, monkeypatch, *, before, after=None, npx=True, rc=0, stderr=""): |
| 575 | from lib import health |
| 576 | |
| 577 | state = {"installed": False} |
| 578 | installs = [] |
| 579 | |
| 580 | def fake_which(name, *args, **kwargs): |
| 581 | if name == "digg-pp-cli": |
| 582 | return self.DIGG |
| 583 | if name == "npx": |
| 584 | return self.NPX if npx else None |
| 585 | return None |
| 586 | |
| 587 | def fake_version(cmd, **kwargs): |
| 588 | line = after if state["installed"] else before |
| 589 | return subprocess.CompletedProcess(args=cmd, returncode=0, stdout=line + "\n", stderr="") |
| 590 | |
| 591 | def fake_install(cmd, **kwargs): |
| 592 | installs.append(cmd) |
| 593 | if rc == 0: |
| 594 | state["installed"] = True |
| 595 | return MagicMock(returncode=rc, stderr=stderr) |
| 596 | |
| 597 | monkeypatch.setattr(setup_wizard.shutil, "which", fake_which) |
| 598 | monkeypatch.setattr(health.subproc, "run_with_timeout", fake_version) |
| 599 | monkeypatch.setattr(setup_wizard.subprocess, "run", fake_install) |
| 600 | return setup_wizard._install_digg_cli(), installs |
| 601 | |
| 602 | def test_old_digg_is_upgraded(self, monkeypatch): |
| 603 | (active, action, stderr, off_path), installs = self._run( |
| 604 | monkeypatch, before="digg-pp-cli 2026.7.1", after="digg-pp-cli 2026.11.1", |
| 605 | ) |
| 606 | assert (active, action, off_path) == (True, "upgraded", "") |
| 607 | assert installs == [ |
| 608 | [self.NPX, "-y", setup_wizard.PRINTING_PRESS_NPM, "install", "digg", "--cli-only"] |
| 609 | ] |
| 610 | |
| 611 | def test_digg_at_the_minimum_is_left_alone(self, monkeypatch): |
| 612 | from lib import health |
| 613 | |
| 614 | minimum = ".".join(str(n) for n in health.MIN_HELPER_VERSIONS["digg-pp-cli"]) |
| 615 | (active, action, _, _), installs = self._run(monkeypatch, before=f"digg-pp-cli {minimum}") |
| 616 | assert (active, action) == (True, "already_installed") |
| 617 | assert installs == [] |
| 618 | |
| 619 | def test_unreadable_digg_version_is_never_upgraded(self, monkeypatch): |
| 620 | (active, action, _, _), installs = self._run(monkeypatch, before="digg-pp-cli dev") |
| 621 | assert (active, action) == (True, "already_installed") |
| 622 | assert installs == [] |
| 623 | |
| 624 | def test_failed_upgrade_keeps_the_old_helper_present(self, monkeypatch): |
| 625 | (active, action, stderr, _), installs = self._run( |
| 626 | monkeypatch, before="digg-pp-cli 2026.7.1", rc=1, stderr="npm ERR! boom", |
| 627 | ) |
| 628 | assert active is True # the older helper is still on PATH |
| 629 | assert action == "install_failed" |
| 630 | assert "boom" in stderr |
| 631 | assert len(installs) == 1 |
| 632 | |
| 633 | def test_upgrade_that_leaves_an_old_copy_on_path_is_not_upgraded(self, monkeypatch): |
| 634 | (active, action, stderr, _), installs = self._run( |
| 635 | monkeypatch, before="digg-pp-cli 2026.7.1", after="digg-pp-cli 2026.7.1", |
| 636 | ) |
| 637 | assert (active, action) == (True, "install_failed") |
| 638 | assert "older" in stderr |
| 639 | |
| 640 | def test_upgrade_whose_new_version_cannot_be_read_is_not_upgraded(self, monkeypatch): |
| 641 | (active, action, stderr, _), installs = self._run( |
| 642 | monkeypatch, before="digg-pp-cli 2026.7.1", after="digg-pp-cli dev", |
| 643 | ) |
| 644 | assert (active, action) == (True, "install_failed") |
| 645 | assert "could not be read" in stderr |
| 646 | assert len(installs) == 1 |
| 647 | |
| 648 | def test_no_npx_reports_the_outdated_helper_with_the_manual_command(self, monkeypatch): |
| 649 | (active, action, _, _), installs = self._run( |
| 650 | monkeypatch, before="digg-pp-cli 2026.7.1", npx=False, |
| 651 | ) |
| 652 | assert (active, action) == (True, "no_npx") |
| 653 | assert installs == [] |
| 654 | text = setup_wizard.get_setup_status_text({ |
| 655 | "cookies_found": {}, "ytdlp_action": "already_installed", |
| 656 | "digg_installed": True, "digg_action": "no_npx", "env_written": False, |
| 657 | }) |
| 658 | assert setup_wizard.DIGG_INSTALL_CMD in text |
| 659 | assert "older" in text |
| 660 | assert "not installed" not in text |
| 661 | |
| 662 | def test_status_text_upgraded(self): |
| 663 | text = setup_wizard.get_setup_status_text({ |
| 664 | "cookies_found": {}, "ytdlp_action": "already_installed", |
| 665 | "digg_installed": True, "digg_action": "upgraded", "env_written": False, |
| 666 | }) |
| 667 | assert "Upgraded Digg CLI" in text |
| 668 | |
| 669 | def test_status_text_failed_upgrade_names_the_older_helper(self): |
| 670 | text = setup_wizard.get_setup_status_text({ |
| 671 | "cookies_found": {}, "ytdlp_action": "already_installed", |
| 672 | "digg_installed": True, "digg_action": "install_failed", "env_written": False, |
| 673 | }) |
| 674 | assert "upgrade failed" in text |
| 675 | assert setup_wizard.DIGG_INSTALL_CMD in text |
| 676 | |
| 677 | def test_digg_install_command_uses_the_shared_upgrade_command(self): |
| 678 | from lib import health |
| 679 | |
| 680 | assert setup_wizard.DIGG_INSTALL_CMD == health.helper_upgrade_cmd("digg") |
| 681 | assert setup_wizard.PRINTING_PRESS_NPM is health.PRINTING_PRESS_NPM |
| 682 | |
| 683 | |
| 684 | class TestWriteSetupConfig: |
| 685 | """Tests for write_setup_config().""" |
| 686 | |
| 687 | def test_creates_new_env_file(self): |
| 688 | """Creates .env with SETUP_COMPLETE; omits FROM_BROWSER when unspecified. |
| 689 | |
| 690 | With no detected browser we must NOT pin FROM_BROWSER=auto, because |
| 691 | that makes every later run probe Chrome and re-trigger the macOS |
| 692 | Keychain prompt. Leaving it unset applies the safe Firefox/Safari |
| 693 | default instead. |
| 694 | """ |
| 695 | with tempfile.TemporaryDirectory() as tmpdir: |
| 696 | env_path = Path(tmpdir) / "subdir" / ".env" |
| 697 | |
| 698 | result = setup_wizard.write_setup_config(env_path) |
| 699 | |
| 700 | assert result is True |
| 701 | assert env_path.exists() |
| 702 | content = env_path.read_text() |
| 703 | assert "SETUP_COMPLETE=true" in content |
| 704 | assert "FROM_BROWSER" not in content |
| 705 | |
| 706 | def test_appends_to_existing_file(self): |
| 707 | """Appends to existing .env without overwriting keys.""" |
| 708 | with tempfile.TemporaryDirectory() as tmpdir: |
| 709 | env_path = Path(tmpdir) / ".env" |
| 710 | env_path.write_text("XAI_API_KEY=my-key\nAUTH_TOKEN=tok123\n") |
| 711 | |
| 712 | result = setup_wizard.write_setup_config(env_path) |
| 713 | |
| 714 | assert result is True |
| 715 | content = env_path.read_text() |
| 716 | # Original keys preserved |
| 717 | assert "XAI_API_KEY=my-key" in content |
| 718 | assert "AUTH_TOKEN=tok123" in content |
| 719 | # SETUP_COMPLETE appended; FROM_BROWSER omitted (no browser detected) |
| 720 | assert "SETUP_COMPLETE=true" in content |
| 721 | assert "FROM_BROWSER" not in content |
| 722 | |
| 723 | def test_does_not_overwrite_existing_keys(self): |
| 724 | """If SETUP_COMPLETE or FROM_BROWSER already exist, don't duplicate.""" |
| 725 | with tempfile.TemporaryDirectory() as tmpdir: |
| 726 | env_path = Path(tmpdir) / ".env" |
| 727 | env_path.write_text("SETUP_COMPLETE=true\nFROM_BROWSER=firefox\n") |
| 728 | |
| 729 | result = setup_wizard.write_setup_config(env_path) |
| 730 | |
| 731 | assert result is True |
| 732 | content = env_path.read_text() |
| 733 | # Should only appear once |
| 734 | assert content.count("SETUP_COMPLETE") == 1 |
| 735 | assert content.count("FROM_BROWSER") == 1 |
| 736 | # Original value preserved |
| 737 | assert "FROM_BROWSER=firefox" in content |
| 738 | |
| 739 | def test_custom_from_browser_value(self): |
| 740 | """Custom from_browser value is written.""" |
| 741 | with tempfile.TemporaryDirectory() as tmpdir: |
| 742 | env_path = Path(tmpdir) / ".env" |
| 743 | |
| 744 | result = setup_wizard.write_setup_config(env_path, from_browser="chrome") |
| 745 | |
| 746 | assert result is True |
| 747 | content = env_path.read_text() |
| 748 | assert "FROM_BROWSER=chrome" in content |
| 749 | |
| 750 | def test_creates_parent_directories(self): |
| 751 | """Creates parent directories if they don't exist.""" |
| 752 | with tempfile.TemporaryDirectory() as tmpdir: |
| 753 | env_path = Path(tmpdir) / "a" / "b" / "c" / ".env" |
| 754 | |
| 755 | result = setup_wizard.write_setup_config(env_path) |
| 756 | |
| 757 | assert result is True |
| 758 | assert env_path.exists() |
| 759 | |
| 760 | def test_handles_file_without_trailing_newline(self): |
| 761 | """Appends correctly when existing file has no trailing newline.""" |
| 762 | with tempfile.TemporaryDirectory() as tmpdir: |
| 763 | env_path = Path(tmpdir) / ".env" |
| 764 | env_path.write_text("EXISTING_KEY=value") # no trailing newline |
| 765 | |
| 766 | result = setup_wizard.write_setup_config(env_path, from_browser="firefox") |
| 767 | |
| 768 | assert result is True |
| 769 | content = env_path.read_text() |
| 770 | # Should have newline separator |
| 771 | lines = content.strip().split("\n") |
| 772 | assert len(lines) == 3 |
| 773 | assert lines[0] == "EXISTING_KEY=value" |
| 774 | assert "SETUP_COMPLETE=true" in lines[1] |
| 775 | |
| 776 | |
| 777 | class TestWriteApiKey: |
| 778 | """Tests for write_api_key() — persisting the ScrapeCreators signup key.""" |
| 779 | |
| 780 | def test_writes_key_with_secret_permissions(self): |
| 781 | """Key is written and the file is 0o600 (owner read/write only).""" |
| 782 | with tempfile.TemporaryDirectory() as tmpdir: |
| 783 | env_path = Path(tmpdir) / "subdir" / ".env" |
| 784 | |
| 785 | result = setup_wizard.write_api_key(env_path, "sc_live_abcdef123456") |
| 786 | |
| 787 | assert result is True |
| 788 | assert env_path.exists() |
| 789 | assert "SCRAPECREATORS_API_KEY=sc_live_abcdef123456" in env_path.read_text() |
| 790 | assert (env_path.stat().st_mode & 0o777) == 0o600 |
| 791 | |
| 792 | def test_value_round_trips_through_env_loader(self): |
| 793 | """Persisted key reloads to the exact original value.""" |
| 794 | from lib import env as env_mod |
| 795 | with tempfile.TemporaryDirectory() as tmpdir: |
| 796 | env_path = Path(tmpdir) / ".env" |
| 797 | |
| 798 | setup_wizard.write_api_key(env_path, "sc_live_abcdef123456") |
| 799 | |
| 800 | loaded = env_mod.load_env_file(env_path) |
| 801 | assert loaded["SCRAPECREATORS_API_KEY"] == "sc_live_abcdef123456" |
| 802 | |
| 803 | def test_idempotent_when_key_already_present(self): |
| 804 | """If the key already exists, do not duplicate or overwrite it.""" |
| 805 | with tempfile.TemporaryDirectory() as tmpdir: |
| 806 | env_path = Path(tmpdir) / ".env" |
| 807 | env_path.write_text("SCRAPECREATORS_API_KEY=existing_key\n") |
| 808 | |
| 809 | result = setup_wizard.write_api_key(env_path, "sc_new_value") |
| 810 | |
| 811 | assert result is True |
| 812 | content = env_path.read_text() |
| 813 | assert content.count("SCRAPECREATORS_API_KEY") == 1 |
| 814 | assert "existing_key" in content |
| 815 | assert "sc_new_value" not in content |
| 816 | |
| 817 | def test_appends_without_clobbering_other_keys(self): |
| 818 | """Existing unrelated keys are preserved.""" |
| 819 | with tempfile.TemporaryDirectory() as tmpdir: |
| 820 | env_path = Path(tmpdir) / ".env" |
| 821 | env_path.write_text("SETUP_COMPLETE=true\nFROM_BROWSER=firefox\n") |
| 822 | |
| 823 | setup_wizard.write_api_key(env_path, "sc_key_xyz") |
| 824 | |
| 825 | content = env_path.read_text() |
| 826 | assert "SETUP_COMPLETE=true" in content |
| 827 | assert "FROM_BROWSER=firefox" in content |
| 828 | assert "SCRAPECREATORS_API_KEY=sc_key_xyz" in content |
| 829 | |
| 830 | def test_value_with_whitespace_is_quoted(self): |
| 831 | """A pathological value with whitespace is quoted so it round-trips.""" |
| 832 | from lib import env as env_mod |
| 833 | with tempfile.TemporaryDirectory() as tmpdir: |
| 834 | env_path = Path(tmpdir) / ".env" |
| 835 | |
| 836 | setup_wizard.write_api_key(env_path, "key with space") |
| 837 | |
| 838 | content = env_path.read_text() |
| 839 | assert 'SCRAPECREATORS_API_KEY="key with space"' in content |
| 840 | assert env_mod.load_env_file(env_path)["SCRAPECREATORS_API_KEY"] == "key with space" |
| 841 | |
| 842 | def test_empty_key_returns_false_and_writes_nothing(self): |
| 843 | """An empty api_key persists nothing and reports failure.""" |
| 844 | with tempfile.TemporaryDirectory() as tmpdir: |
| 845 | env_path = Path(tmpdir) / ".env" |
| 846 | |
| 847 | assert setup_wizard.write_api_key(env_path, "") is False |
| 848 | assert not env_path.exists() |
| 849 | |
| 850 | def test_unwritable_target_returns_false(self): |
| 851 | """Unwritable target dir -> False, no exception escapes.""" |
| 852 | with tempfile.TemporaryDirectory() as tmpdir: |
| 853 | ro_dir = Path(tmpdir) / "ro" |
| 854 | ro_dir.mkdir() |
| 855 | ro_dir.chmod(0o500) # no write |
| 856 | try: |
| 857 | result = setup_wizard.write_api_key(ro_dir / "sub" / ".env", "sc_key") |
| 858 | assert result is False |
| 859 | finally: |
| 860 | ro_dir.chmod(0o700) # restore so tempdir cleanup succeeds |
| 861 | |
| 862 | |
| 863 | class TestMaskApiKey: |
| 864 | """Tests for mask_api_key() — non-secret display form.""" |
| 865 | |
| 866 | def test_masks_long_key(self): |
| 867 | masked = setup_wizard.mask_api_key("sc_live_abcdef123456") |
| 868 | assert "abcdef" not in masked |
| 869 | assert masked.endswith("3456") |
| 870 | assert masked.startswith("sc_") |
| 871 | |
| 872 | def test_short_key_collapses_to_placeholder(self): |
| 873 | assert setup_wizard.mask_api_key("short") == "sc_…" |
| 874 | |
| 875 | def test_empty_key_collapses_to_placeholder(self): |
| 876 | assert setup_wizard.mask_api_key("") == "sc_…" |
| 877 | |
| 878 | |
| 879 | class TestCookieExtractionBrowsers: |
| 880 | """Tests for env.cookie_extraction_browsers() — the shared browser policy.""" |
| 881 | |
| 882 | def test_default_disables_extraction(self): |
| 883 | """FROM_BROWSER unset -> no browser-cookie reads.""" |
| 884 | from lib import env |
| 885 | browsers = env.cookie_extraction_browsers({}) |
| 886 | assert browsers == [] |
| 887 | |
| 888 | def test_off_disables_extraction(self): |
| 889 | from lib import env |
| 890 | assert env.cookie_extraction_browsers({"FROM_BROWSER": "off"}) == [] |
| 891 | |
| 892 | def test_auto_opts_into_chrome(self): |
| 893 | from lib import env |
| 894 | assert "chrome" in env.cookie_extraction_browsers({"FROM_BROWSER": "auto"}) |
| 895 | |
| 896 | def test_specific_browser(self): |
| 897 | from lib import env |
| 898 | assert env.cookie_extraction_browsers({"FROM_BROWSER": "chrome"}) == ["chrome"] |
| 899 | |
| 900 | |
| 901 | class TestWizardDoesNotProbeChromeByDefault: |
| 902 | """Regression: first-run setup must not silently read Chrome cookies.""" |
| 903 | |
| 904 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 905 | @patch("shutil.which", return_value=None) |
| 906 | def test_default_run_never_requests_chrome(self, _mock_which, mock_extract): |
| 907 | setup_wizard.run_auto_setup({}) |
| 908 | requested_browsers = {call.args[0] for call in mock_extract.call_args_list} |
| 909 | assert requested_browsers == set() |
| 910 | |
| 911 | @patch("lib.cookie_extract.extract_cookies_with_source", return_value=None) |
| 912 | @patch("shutil.which", return_value=None) |
| 913 | def test_from_browser_auto_does_request_chrome(self, _mock_which, mock_extract): |
| 914 | setup_wizard.run_auto_setup({"FROM_BROWSER": "auto"}, allow_browser_cookies=True) |
| 915 | requested_browsers = {call.args[0] for call in mock_extract.call_args_list} |
| 916 | assert "chrome" in requested_browsers |
| 917 | |
| 918 | @patch("lib.cookie_extract.extract_cookies_with_source") |
| 919 | @patch("shutil.which", return_value=None) |
| 920 | def test_from_browser_off_skips_extraction(self, _mock_which, mock_extract): |
| 921 | results = setup_wizard.run_auto_setup({"FROM_BROWSER": "off"}) |
| 922 | mock_extract.assert_not_called() |
| 923 | assert results["cookies_found"] == {} |
| 924 | |
| 925 | |
| 926 | class TestGetSetupStatusText: |
| 927 | """Tests for get_setup_status_text().""" |
| 928 | |
| 929 | def test_with_cookies_and_ytdlp(self): |
| 930 | """Status text mentions found cookies and yt-dlp.""" |
| 931 | results = { |
| 932 | "cookies_found": {"x": "chrome"}, |
| 933 | "browser_cookie_scan_attempted": True, |
| 934 | "ytdlp_installed": True, |
| 935 | "ytdlp_action": "already_installed", |
| 936 | "env_written": True, |
| 937 | } |
| 938 | text = setup_wizard.get_setup_status_text(results) |
| 939 | assert "X cookies found in chrome" in text |
| 940 | assert "yt-dlp already installed" in text |
| 941 | assert "Configuration saved" in text |
| 942 | |
| 943 | def test_skipped_cookie_scan_does_not_claim_x_is_missing(self): |
| 944 | """A consent-safe skip reports setup work without an X unlock nudge.""" |
| 945 | results = { |
| 946 | "cookies_found": {}, |
| 947 | "browser_cookie_scan_attempted": False, |
| 948 | "ytdlp_installed": False, |
| 949 | "ytdlp_action": "no_homebrew", |
| 950 | "env_written": False, |
| 951 | } |
| 952 | text = setup_wizard.get_setup_status_text(results) |
| 953 | assert "browser cookies" not in text.lower() |
| 954 | assert "X/Twitter" not in text |
| 955 | assert "Install Homebrew first" in text |
| 956 | |
| 957 | def test_consented_scan_with_no_match_shows_manual_alternative(self): |
| 958 | for firefox in (False, True): |
| 959 | results = {"cookies_found": {}, "browser_cookie_scan_attempted": True, |
| 960 | "firefox_scanned": firefox, "ytdlp_action": "already_installed"} |
| 961 | text = setup_wizard.get_setup_status_text(results) |
| 962 | assert "No complete X login" in text |
| 963 | assert "AUTH_TOKEN and CT0" in text |
| 964 | assert ("Firefox permanent private browsing" in text) == firefox |
| 965 | for changes in ({"browser_cookie_scan_attempted": False}, |
| 966 | {"cookies_found": {"x": "firefox"}}): |
| 967 | other = setup_wizard.get_setup_status_text({**results, **changes}) |
| 968 | assert "No complete X login" not in other |
| 969 | assert "AUTH_TOKEN and CT0" not in other |
| 970 | assert "Firefox permanent private browsing" not in other |
| 971 | |
| 972 | def test_consented_permission_denial_reports_x_and_safe_alternatives(self): |
| 973 | with patch( |
| 974 | "lib.cookie_extract.extract_cookies_with_source", |
| 975 | side_effect=PermissionError(1, "Operation not permitted", "/private/secret/Cookies"), |
| 976 | ), patch("shutil.which", return_value=None): |
| 977 | results = setup_wizard.run_auto_setup( |
| 978 | {"FROM_BROWSER": "edge"}, allow_browser_cookies=True |
| 979 | ) |
| 980 | assert results["cookies_found"] == {} |
| 981 | assert results["x_cookie_access_denied"] == ["edge"] |
| 982 | text = setup_wizard.get_setup_status_text(results) |
| 983 | assert "permission denied" in text.lower() |
| 984 | assert "edge" in text |
| 985 | assert "AUTH_TOKEN" in text and "CT0" in text |
| 986 | assert "XAI_API_KEY" in text |
| 987 | assert "/private/secret" not in text |
| 988 | |
| 989 | def test_missing_cookies_do_not_record_permission_denial(self): |
| 990 | with patch( |
| 991 | "lib.cookie_extract.extract_cookies_with_source", return_value=None |
| 992 | ), patch("shutil.which", return_value=None): |
| 993 | results = setup_wizard.run_auto_setup( |
| 994 | {"FROM_BROWSER": "edge"}, allow_browser_cookies=True |
| 995 | ) |
| 996 | assert results["x_cookie_access_denied"] == [] |
| 997 | |
| 998 | def test_complete_pair_from_another_browser_supersedes_denial(self): |
| 999 | def extract(browser, domain, _cookie_names): |
| 1000 | if browser == "edge": |
| 1001 | raise PermissionError(1, "Operation not permitted", "/private/Cookies") |
| 1002 | if browser == "firefox" and domain == ".x.com": |
| 1003 | return ({"auth_token": "dummy-auth", "ct0": "dummy-ct0"}, "firefox") |
| 1004 | return None |
| 1005 | |
| 1006 | with patch( |
| 1007 | "lib.cookie_extract.extract_cookies_with_source", side_effect=extract |
| 1008 | ), patch("shutil.which", return_value=None): |
| 1009 | results = setup_wizard.run_auto_setup( |
| 1010 | {"FROM_BROWSER": "edge,firefox"}, allow_browser_cookies=True |
| 1011 | ) |
| 1012 | assert results["cookies_found"]["x"] == "firefox" |
| 1013 | assert results["x_cookie_access_denied"] == [] |
| 1014 | |
| 1015 | def test_other_source_success_does_not_clear_x_denial(self): |
| 1016 | def extract(browser, domain, _cookie_names): |
| 1017 | if domain == ".x.com" and browser == "edge": |
| 1018 | raise PermissionError(1, "Operation not permitted", "/private/Cookies") |
| 1019 | if domain == ".truthsocial.com" and browser == "chrome": |
| 1020 | return ({"_session_id": "dummy-session"}, "chrome") |
| 1021 | return None |
| 1022 | |
| 1023 | with patch( |
| 1024 | "lib.cookie_extract.extract_cookies_with_source", side_effect=extract |
| 1025 | ), patch("shutil.which", return_value=None): |
| 1026 | results = setup_wizard.run_auto_setup({}, allow_browser_cookies=True) |
| 1027 | assert results["cookies_found"] == {"truthsocial": "chrome"} |
| 1028 | assert results["x_cookie_access_denied"] == ["edge"] |
| 1029 | |
| 1030 | def test_last_setup_denial_marker_is_replaced_after_success(self, tmp_path): |
| 1031 | env_path = tmp_path / ".env" |
| 1032 | assert setup_wizard.write_setup_config( |
| 1033 | env_path, browser_consent=True, x_cookie_access_denied="edge" |
| 1034 | ) |
| 1035 | assert setup_wizard.write_setup_config( |
| 1036 | env_path, browser_consent=True, x_cookie_access_denied="none" |
| 1037 | ) |
| 1038 | content = env_path.read_text() |
| 1039 | assert "LAST30DAYS_X_COOKIE_ACCESS_DENIED=none" in content |
| 1040 | assert "LAST30DAYS_X_COOKIE_ACCESS_DENIED=edge" not in content |
| 1041 | |
| 1042 | def test_status_text_installed(self): |
| 1043 | """Status text for freshly installed yt-dlp.""" |
| 1044 | results = { |
| 1045 | "cookies_found": {}, |
| 1046 | "ytdlp_installed": True, |
| 1047 | "ytdlp_action": "installed", |
| 1048 | "env_written": False, |
| 1049 | } |
| 1050 | text = setup_wizard.get_setup_status_text(results) |
| 1051 | assert "Installed yt-dlp via Homebrew" in text |
| 1052 | |
| 1053 | def test_status_text_install_failed(self): |
| 1054 | """Status text for failed yt-dlp install.""" |
| 1055 | results = { |
| 1056 | "cookies_found": {}, |
| 1057 | "ytdlp_installed": False, |
| 1058 | "ytdlp_action": "install_failed", |
| 1059 | "env_written": False, |
| 1060 | } |
| 1061 | text = setup_wizard.get_setup_status_text(results) |
| 1062 | assert "yt-dlp install failed" in text |
| 1063 | assert "manually" in text |
| 1064 | |
| 1065 | def test_status_text_digg_installed(self): |
| 1066 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1067 | "digg_action": "installed", "env_written": False} |
| 1068 | text = setup_wizard.get_setup_status_text(results) |
| 1069 | assert "Installed Digg CLI" in text |
| 1070 | assert "AI" not in text |
| 1071 | |
| 1072 | def test_status_text_digg_already_installed(self): |
| 1073 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1074 | "digg_action": "already_installed", "env_written": False} |
| 1075 | text = setup_wizard.get_setup_status_text(results) |
| 1076 | assert "Digg CLI already installed" in text |
| 1077 | assert "AI" not in text |
| 1078 | |
| 1079 | def test_status_text_digg_install_failed(self): |
| 1080 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1081 | "digg_action": "install_failed", "env_written": False} |
| 1082 | text = setup_wizard.get_setup_status_text(results) |
| 1083 | assert "Digg CLI install failed" in text |
| 1084 | assert "printing-press-library" in text |
| 1085 | |
| 1086 | def test_status_text_digg_installed_off_path(self): |
| 1087 | home = Path.home() |
| 1088 | digg_path = str(home / ".local" / "bin" / "digg-pp-cli") |
| 1089 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1090 | "digg_action": "installed_off_path", |
| 1091 | "digg_path": digg_path, |
| 1092 | "env_written": False} |
| 1093 | text = setup_wizard.get_setup_status_text(results) |
| 1094 | assert "not on PATH" in text |
| 1095 | expected = str(home / ".local" / "bin") if os.name == "nt" else "$HOME/.local/bin" |
| 1096 | assert f"add {expected} to PATH" in text |
| 1097 | assert "now active" not in text.lower() |
| 1098 | |
| 1099 | def test_status_text_digg_installed_off_path_legacy_go_bin(self): |
| 1100 | """The PATH hint names the Go installation directory.""" |
| 1101 | home = Path.home() |
| 1102 | digg_path = str(home / "go" / "bin" / "digg-pp-cli") |
| 1103 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1104 | "digg_action": "installed_off_path", |
| 1105 | "digg_path": digg_path, |
| 1106 | "env_written": False} |
| 1107 | text = setup_wizard.get_setup_status_text(results) |
| 1108 | expected = str(home / "go" / "bin") if os.name == "nt" else "$HOME/go/bin" |
| 1109 | assert f"add {expected} to PATH" in text |
| 1110 | assert ".local/bin" not in text |
| 1111 | |
| 1112 | def test_status_text_digg_installed_off_path_missing_path(self): |
| 1113 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1114 | "digg_action": "installed_off_path", |
| 1115 | "env_written": False} |
| 1116 | text = setup_wizard.get_setup_status_text(results) |
| 1117 | assert "not on PATH" in text |
| 1118 | assert "add its install directory to PATH" in text |
| 1119 | |
| 1120 | def test_status_text_digg_installed_off_path_empty_path(self): |
| 1121 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1122 | "digg_action": "installed_off_path", |
| 1123 | "digg_path": "", |
| 1124 | "env_written": False} |
| 1125 | text = setup_wizard.get_setup_status_text(results) |
| 1126 | assert "add its install directory to PATH" in text |
| 1127 | |
| 1128 | def test_digg_bin_dir_hint_windows_returns_absolute_parent(self): |
| 1129 | home = Path.home() |
| 1130 | digg_path = str(home / ".local" / "bin" / "digg-pp-cli") |
| 1131 | expected = str(home / ".local" / "bin") |
| 1132 | with patch.object(setup_wizard.os, "name", "nt"): |
| 1133 | assert setup_wizard._digg_bin_dir_hint(digg_path) == expected |
| 1134 | |
| 1135 | def test_status_text_digg_no_npx(self): |
| 1136 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1137 | "digg_action": "no_npx", "env_written": False} |
| 1138 | text = setup_wizard.get_setup_status_text(results) |
| 1139 | assert "Digg CLI not installed" in text |
| 1140 | |
| 1141 | def test_status_text_digg_absent_key_renders(self): |
| 1142 | """No digg_action key (defensive) -> no Digg line, no error.""" |
| 1143 | results = {"cookies_found": {}, "ytdlp_action": "already_installed", |
| 1144 | "env_written": False} |
| 1145 | text = setup_wizard.get_setup_status_text(results) |
| 1146 | assert "Digg" not in text |
| 1147 | |
| 1148 | |
| 1149 | class TestSetupSubcommand: |
| 1150 | """Tests for setup dispatch through the production entrypoint.""" |
| 1151 | |
| 1152 | def test_permission_denial_reaches_cli_and_saved_doctor_marker(self, tmp_path, capsys): |
| 1153 | env_path = tmp_path / ".env" |
| 1154 | results = { |
| 1155 | "cookies_found": {}, |
| 1156 | "x_cookie_access_denied": ["edge"], |
| 1157 | "browser_cookie_scan_attempted": True, |
| 1158 | "ytdlp_action": "already_installed", |
| 1159 | } |
| 1160 | with patch.object(sys, "argv", ["last30days", "setup", "--allow-browser-cookies"]), patch.object( |
| 1161 | cli.env, "get_config", return_value={"FROM_BROWSER": "edge"} |
| 1162 | ), patch.object(cli.env, "CONFIG_FILE", env_path), patch.object( |
| 1163 | setup_wizard, "run_auto_setup", return_value=results |
| 1164 | ): |
| 1165 | assert cli.main() == 0 |
| 1166 | notice = capsys.readouterr().err |
| 1167 | assert "permission denied" in notice.lower() |
| 1168 | assert "edge" in notice |
| 1169 | assert "LAST30DAYS_X_COOKIE_ACCESS_DENIED=edge" in env_path.read_text() |
| 1170 | |
| 1171 | def test_no_scan_preserves_last_consented_denial(self, tmp_path): |
| 1172 | env_path = tmp_path / ".env" |
| 1173 | env_path.write_text("LAST30DAYS_X_COOKIE_ACCESS_DENIED=edge\n") |
| 1174 | results = { |
| 1175 | "cookies_found": {}, |
| 1176 | "x_cookie_access_denied": [], |
| 1177 | "browser_cookie_scan_attempted": False, |
| 1178 | "ytdlp_action": "already_installed", |
| 1179 | } |
| 1180 | with patch.object(sys, "argv", ["last30days", "setup"]), patch.object( |
| 1181 | cli.env, "get_config", |
| 1182 | return_value={"LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge"}, |
| 1183 | ), patch.object(cli.env, "CONFIG_FILE", env_path), patch.object( |
| 1184 | setup_wizard, "run_auto_setup", return_value=results |
| 1185 | ): |
| 1186 | assert cli.main() == 0 |
| 1187 | assert "LAST30DAYS_X_COOKIE_ACCESS_DENIED=edge" in env_path.read_text() |
| 1188 | |
| 1189 | def test_explicit_browser_off_with_consent_does_not_clear_last_denial(self, tmp_path): |
| 1190 | env_path = tmp_path / ".env" |
| 1191 | env_path.write_text("LAST30DAYS_X_COOKIE_ACCESS_DENIED=edge\nFROM_BROWSER=off\n") |
| 1192 | with patch.object(sys, "argv", ["last30days", "setup", "--allow-browser-cookies"]), patch.object( |
| 1193 | cli.env, "get_config", |
| 1194 | return_value={"FROM_BROWSER": "off", "LAST30DAYS_X_COOKIE_ACCESS_DENIED": "edge"}, |
| 1195 | ), patch.object(cli.env, "CONFIG_FILE", env_path), patch( |
| 1196 | "lib.cookie_extract.extract_cookies_with_source", |
| 1197 | side_effect=AssertionError("browser read despite FROM_BROWSER=off"), |
| 1198 | ), patch.object(setup_wizard, "_install_digg_cli", return_value=(False, "no_npx", "", None)), patch.object( |
| 1199 | setup_wizard, "install_default_pp_sources", return_value={} |
| 1200 | ), patch("shutil.which", return_value=None): |
| 1201 | assert cli.main() == 0 |
| 1202 | content = env_path.read_text() |
| 1203 | assert "LAST30DAYS_X_COOKIE_ACCESS_DENIED=edge" in content |
| 1204 | assert "BROWSER_CONSENT=true" in content |
| 1205 | |
| 1206 | def test_setup_detected_as_topic(self, capsys): |
| 1207 | with patch.object(sys, "argv", ["last30days", "setup"]), patch.object( |
| 1208 | cli.env, "get_config", return_value={} |
| 1209 | ), patch.object(setup_wizard, "run_auto_setup", return_value={}) as setup, patch.object( |
| 1210 | setup_wizard, "write_setup_config", return_value=True |
| 1211 | ) as write_config, patch.object( |
| 1212 | setup_wizard, "get_setup_status_text", return_value="setup-completed-sentinel" |
| 1213 | ), patch.object(cli.pipeline, "run") as research: |
| 1214 | assert cli.main() == 0 |
| 1215 | setup.assert_called_once_with({}, allow_browser_cookies=False) |
| 1216 | write_config.assert_called_once() |
| 1217 | research.assert_not_called() |
| 1218 | assert "setup-completed-sentinel" in capsys.readouterr().err |
| 1219 | |
| 1220 | def test_normal_topic_not_setup(self): |
| 1221 | with patch.object(sys, "argv", ["last30days", "AI", "setup", "tools", "--mock"]), patch.object( |
| 1222 | cli.env, "get_config", return_value={} |
| 1223 | ), patch.object(setup_wizard, "run_auto_setup", return_value={}) as setup, patch.object( |
| 1224 | setup_wizard, "write_setup_config", return_value=True |
| 1225 | ), patch.object(setup_wizard, "get_setup_status_text", return_value="setup-sentinel"), patch.object( |
| 1226 | cli.pipeline, "diagnose", side_effect=RuntimeError("research-path-sentinel") |
| 1227 | ) as research: |
| 1228 | with pytest.raises(RuntimeError, match="research-path-sentinel"): |
| 1229 | cli.main() |
| 1230 | research.assert_called_once() |
| 1231 | setup.assert_not_called() |
| 1232 | |
| 1233 | |
| 1234 | class TestBrightDataStatusHonesty: |
| 1235 | """U5/R11: setup must never claim active unless the engine gate passes.""" |
| 1236 | |
| 1237 | def _patched(self, *, installed, credentialed, off_path=None): |
| 1238 | available = installed and credentialed |
| 1239 | return ( |
| 1240 | patch.object(setup_wizard.brightdata, "is_installed", return_value=installed), |
| 1241 | patch.object(setup_wizard.brightdata, "has_credentials", return_value=credentialed), |
| 1242 | patch.object(setup_wizard.brightdata, "is_available", return_value=available), |
| 1243 | patch.object(setup_wizard, "_brightdata_off_path_binary", return_value=off_path), |
| 1244 | ) |
| 1245 | |
| 1246 | def test_on_path_and_credentialed_reports_engine_active(self): |
| 1247 | a, b, c, d = self._patched(installed=True, credentialed=True) |
| 1248 | with a, b, c, d: |
| 1249 | status = setup_wizard.brightdata_status({}) |
| 1250 | assert status["action"] == "already_installed" |
| 1251 | assert status["authenticated"] is True |
| 1252 | assert status["engine_active"] is True |
| 1253 | |
| 1254 | def test_on_path_without_credentials_is_not_active_and_names_login(self): |
| 1255 | a, b, c, d = self._patched(installed=True, credentialed=False) |
| 1256 | with a, b, c, d: |
| 1257 | status = setup_wizard.brightdata_status({}) |
| 1258 | assert status["action"] == "already_installed" |
| 1259 | assert status["authenticated"] is False |
| 1260 | assert status["engine_active"] is False |
| 1261 | assert "brightdata login" in status["hint"] |
| 1262 | |
| 1263 | def test_off_path_binary_is_reported_with_its_path(self): |
| 1264 | """The Hermes/OpenClaw failure mode: on disk, invisible to the engine.""" |
| 1265 | a, b, c, d = self._patched( |
| 1266 | installed=False, credentialed=True, off_path="/Users/x/.npm-global/bin/brightdata" |
| 1267 | ) |
| 1268 | with a, b, c, d: |
| 1269 | status = setup_wizard.brightdata_status({}) |
| 1270 | assert status["action"] == "installed_off_path" |
| 1271 | assert status["engine_active"] is False |
| 1272 | assert status["path"] == "/Users/x/.npm-global/bin/brightdata" |
| 1273 | assert "PATH" in status["hint"] |
| 1274 | |
| 1275 | def test_absent_binary_recommends_but_never_installs(self): |
| 1276 | a, b, c, d = self._patched(installed=False, credentialed=False) |
| 1277 | with a, b, c, d, patch.object(setup_wizard.subprocess, "run") as run: |
| 1278 | status = setup_wizard.brightdata_status({}) |
| 1279 | assert status["action"] == "not_installed" |
| 1280 | assert status["engine_active"] is False |
| 1281 | run.assert_not_called() |
| 1282 | |
| 1283 | def test_brightdata_is_excluded_from_auto_installed_pp_sources(self): |
| 1284 | slugs = {slug for _, slug, _ in setup_wizard.PP_DEFAULT_SOURCES} |
| 1285 | assert "brightdata" not in slugs |
| 1286 | |
| 1287 | |
| 1288 | class TestBrightDataSetupSurface: |
| 1289 | """The three states must be visible somewhere, or the honesty is moot.""" |
| 1290 | |
| 1291 | def _text(self, status): |
| 1292 | return setup_wizard.get_setup_status_text({ |
| 1293 | "cookies_found": {}, "ytdlp_installed": True, |
| 1294 | "ytdlp_action": "already_installed", "digg_installed": True, |
| 1295 | "digg_action": "already_installed", "pp_sources": {}, |
| 1296 | "brightdata": status, "env_written": False, |
| 1297 | }) |
| 1298 | |
| 1299 | def test_active_state_is_reported(self): |
| 1300 | text = self._text({"action": "already_installed", "engine_active": True}) |
| 1301 | assert "Bright Data CLI ready" in text |
| 1302 | |
| 1303 | def test_installed_but_not_logged_in_names_the_fix(self): |
| 1304 | text = self._text({"action": "already_installed", "engine_active": False}) |
| 1305 | assert "brightdata login" in text |
| 1306 | |
| 1307 | def test_off_path_reports_the_path_and_the_fix(self): |
| 1308 | text = self._text({ |
| 1309 | "action": "installed_off_path", "engine_active": False, |
| 1310 | "path": "/Users/x/.npm-global/bin/brightdata", |
| 1311 | }) |
| 1312 | assert "/Users/x/.npm-global/bin/brightdata" in text |
| 1313 | assert "PATH" in text |
| 1314 | |
| 1315 | def test_absent_offers_the_install_command_without_running_it(self): |
| 1316 | text = self._text({"action": "not_installed", "engine_active": False}) |
| 1317 | assert "npm i -g @brightdata/cli" in text |
| 1318 | |
| 1319 | |
| 1320 | def _device_code_response(interval): |
| 1321 | """Build a mocked urlopen context manager yielding a device/code payload.""" |
| 1322 | resp_data = { |
| 1323 | "device_code": "dc-123", |
| 1324 | "user_code": "ABCD-1234", |
| 1325 | "verification_uri": "https://github.com/login/device", |
| 1326 | "interval": interval, |
| 1327 | } |
| 1328 | mock_resp = MagicMock() |
| 1329 | mock_resp.read.return_value = json.dumps(resp_data).encode() |
| 1330 | mock_resp.__enter__ = lambda s: s |
| 1331 | mock_resp.__exit__ = MagicMock(return_value=False) |
| 1332 | return mock_resp |
| 1333 | |
| 1334 | |
| 1335 | @pytest.mark.skipif(os.name != "posix", reason="POSIX file permissions") |
| 1336 | @pytest.mark.parametrize("existing", [False, True]) |
| 1337 | def test_github_device_handle_is_private_before_writing(tmp_path, existing): |
| 1338 | path = tmp_path / ".github-device-handle.json" |
| 1339 | if existing: |
| 1340 | path.write_text("old handle " * 100) |
| 1341 | path.chmod(0o644) |
| 1342 | public = {"status": "awaiting_authorization", "user_code": "ABCD-1234"} |
| 1343 | handle = {"device_code": "dummy-device-code", "interval": 5} |
| 1344 | modes_at_open = [] |
| 1345 | real_open = io.open |
| 1346 | |
| 1347 | def observe_open(*args, **kwargs): |
| 1348 | stream = real_open(*args, **kwargs) |
| 1349 | if "w" in stream.mode: |
| 1350 | modes_at_open.append(os.fstat(stream.fileno()).st_mode & 0o777) |
| 1351 | return stream |
| 1352 | |
| 1353 | old_umask = os.umask(0o022) |
| 1354 | try: |
| 1355 | with patch.object(setup_wizard, "_start_device_flow", return_value=(public, handle)), \ |
| 1356 | patch.object(setup_wizard, "_device_handle_path", return_value=path), \ |
| 1357 | patch("io.open", side_effect=observe_open): |
| 1358 | result = setup_wizard.run_github_start() |
| 1359 | finally: |
| 1360 | os.umask(old_umask) |
| 1361 | |
| 1362 | assert result == public |
| 1363 | assert modes_at_open == [0o600] |
| 1364 | assert path.stat().st_mode & 0o777 == 0o600 |
| 1365 | assert json.loads(path.read_text()) == handle |
| 1366 | |
| 1367 | |
| 1368 | class TestDeviceIntervalClamp: |
| 1369 | """Server-controlled poll intervals are clamped to [1, 30] before use.""" |
| 1370 | |
| 1371 | @pytest.mark.parametrize("server,expected", [ |
| 1372 | (0, 5), |
| 1373 | (-5, 1), |
| 1374 | (3600, 30), |
| 1375 | ("abc", 5), |
| 1376 | (None, 5), |
| 1377 | ("7", 7), |
| 1378 | ]) |
| 1379 | @patch("lib.setup_wizard.urlopen") |
| 1380 | def test_run_device_auth_clamps_server_interval( |
| 1381 | self, mock_urlopen, server, expected |
| 1382 | ): |
| 1383 | """run_device_auth never returns 0/negative/huge/non-numeric intervals.""" |
| 1384 | mock_urlopen.return_value = _device_code_response(server) |
| 1385 | |
| 1386 | result = setup_wizard.run_device_auth() |
| 1387 | |
| 1388 | assert result is not None |
| 1389 | assert result[3] == expected |
| 1390 | |
| 1391 | @pytest.mark.parametrize("stored,expected", [ |
| 1392 | (0, 5), |
| 1393 | (-10, 1), |
| 1394 | (9999, 30), |
| 1395 | ("junk", 5), |
| 1396 | ]) |
| 1397 | @patch("lib.setup_wizard._device_handle_path") |
| 1398 | @patch("lib.setup_wizard.fetch_api_key") |
| 1399 | @patch("lib.setup_wizard.poll_device_auth") |
| 1400 | def test_run_github_poll_clamps_stored_interval( |
| 1401 | self, mock_poll, mock_fetch, mock_handle, tmp_path, stored, expected |
| 1402 | ): |
| 1403 | """A poisoned persisted handle (or server value) cannot hot-loop, |
| 1404 | crash, or sail past the timeout via time.sleep(interval).""" |
| 1405 | handle = tmp_path / "h.json" |
| 1406 | handle.write_text(json.dumps( |
| 1407 | {"device_code": "dc", "interval": stored, "user_code": "ABCD-1234"} |
| 1408 | )) |
| 1409 | mock_handle.return_value = handle |
| 1410 | mock_poll.return_value = "tok" |
| 1411 | mock_fetch.return_value = {"ok": True, "api_key": "sc_k"} |
| 1412 | |
| 1413 | result = setup_wizard.run_github_poll(timeout=1) |
| 1414 | |
| 1415 | assert result["status"] == "success" |
| 1416 | assert mock_poll.call_args[0][1] == expected |
| 1417 | |
| 1418 | @pytest.mark.parametrize("raw,expected", [ |
| 1419 | (0, 5), |
| 1420 | (-5, 1), |
| 1421 | (3600, 30), |
| 1422 | ]) |
| 1423 | @patch("lib.setup_wizard.urlopen") |
| 1424 | @patch("lib.setup_wizard.time.sleep") |
| 1425 | def test_poll_device_auth_clamps_own_interval( |
| 1426 | self, mock_sleep, mock_urlopen, raw, expected |
| 1427 | ): |
| 1428 | """poll_device_auth validates its own interval even when a caller |
| 1429 | passes 0/negative/huge straight through.""" |
| 1430 | mock_resp = MagicMock() |
| 1431 | mock_resp.read.return_value = json.dumps({"access_token": "tok"}).encode() |
| 1432 | mock_resp.__enter__ = lambda s: s |
| 1433 | mock_resp.__exit__ = MagicMock(return_value=False) |
| 1434 | mock_urlopen.return_value = mock_resp |
| 1435 | |
| 1436 | assert setup_wizard.poll_device_auth("dc", raw, timeout=30) == "tok" |
| 1437 | mock_sleep.assert_called_once_with(expected) |
| 1438 |