| 1 | import os |
| 2 | import shutil |
| 3 | import subprocess |
| 4 | import sys |
| 5 | import tempfile |
| 6 | from pathlib import Path |
| 7 | from unittest import mock |
| 8 | |
| 9 | import pytest |
| 10 | |
| 11 | pytest_plugins = ["tests.network_guard"] |
| 12 | |
| 13 | sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "skills" / "last30days" / "scripts")) |
| 14 | |
| 15 | |
| 16 | _CONFIG_ENV_NAMES = { |
| 17 | "AUTH_TOKEN", "CT0", "TWITTER_CT0", "SESSION_ID", |
| 18 | "FROM_BROWSER", "BROWSER_CONSENT", "BROWSER_CDP_URL", "SETUP_COMPLETE", |
| 19 | "AGENTCOOKIE", "AGENTCOOKIE_CONFIG", "INCLUDE_SOURCES", "EXCLUDE_SOURCES", |
| 20 | "FUN_LEVEL", "ELI5_MODE", "DEGRADED_TRANSCRIPT_THRESHOLD", "TELEGRAM_SOURCES", |
| 21 | "OPENAI_MODEL_PIN", "XAI_MODEL_PIN", "OPENAI_BASE_URL", "XAI_BASE_URL", |
| 22 | "OPENROUTER_BASE_URL", "XIAOHONGSHU_API_BASE", |
| 23 | "REDDIT_BROWSER_CONSENT", "REDDIT_FROM_BROWSER", "REDDIT_SESSION_OFFERED", |
| 24 | } |
| 25 | _CREDENTIAL_SUFFIXES = ("_API_KEY", "_TOKEN", "_KEY", "_SECRET", "_PASSWORD", "_COOKIE") |
| 26 | _HARNESS_ENGINE = (os.environ.get("LAST30DAYS_ENGINE") or "").strip() |
| 27 | _system_which = shutil.which |
| 28 | _system_popen = subprocess.Popen |
| 29 | |
| 30 | |
| 31 | def _without_credential_tools(command, *args, **kwargs): |
| 32 | if Path(command).name in {"security", "pass"}: |
| 33 | return None |
| 34 | return _system_which(command, *args, **kwargs) |
| 35 | |
| 36 | |
| 37 | def _isolate_environment(monkeypatch, home): |
| 38 | for name in list(os.environ): |
| 39 | if ( |
| 40 | name in _CONFIG_ENV_NAMES |
| 41 | or name.startswith(("LAST30DAYS_", "BSKY_", "BIRD_")) |
| 42 | or name.endswith(_CREDENTIAL_SUFFIXES) |
| 43 | ): |
| 44 | monkeypatch.delenv(name, raising=False) |
| 45 | if _HARNESS_ENGINE: |
| 46 | monkeypatch.setenv("LAST30DAYS_ENGINE", _HARNESS_ENGINE) |
| 47 | config_dir = home / ".config" / "last30days" |
| 48 | config_dir.mkdir(parents=True) |
| 49 | for name, value in { |
| 50 | "HOME": home, |
| 51 | "USERPROFILE": home, |
| 52 | "XDG_CONFIG_HOME": home / ".config", |
| 53 | "APPDATA": home / "AppData" / "Roaming", |
| 54 | "LOCALAPPDATA": home / "AppData" / "Local", |
| 55 | "PASSWORD_STORE_DIR": home / ".password-store", |
| 56 | "LAST30DAYS_CONFIG_DIR": config_dir, |
| 57 | }.items(): |
| 58 | monkeypatch.setenv(name, str(value)) |
| 59 | |
| 60 | class IsolatedPopen(_system_popen): |
| 61 | def __init__(self, *args, **kwargs): |
| 62 | child_env = dict(os.environ if kwargs.get("env") is None else kwargs["env"]) |
| 63 | # Python mocks do not cross process boundaries; Keychain ignores HOME. |
| 64 | child_env.setdefault("LAST30DAYS_SKIP_KEYCHAIN", "1") |
| 65 | child_env.setdefault("HOME", str(home)) |
| 66 | child_env.setdefault("USERPROFILE", child_env["HOME"]) |
| 67 | child_env.setdefault("PASSWORD_STORE_DIR", str(Path(child_env["HOME"]) / ".password-store")) |
| 68 | kwargs["env"] = child_env |
| 69 | super().__init__(*args, **kwargs) |
| 70 | |
| 71 | monkeypatch.setattr(shutil, "which", _without_credential_tools) |
| 72 | monkeypatch.setattr(subprocess, "Popen", IsolatedPopen) |
| 73 | return config_dir |
| 74 | |
| 75 | |
| 76 | def pytest_configure(config): |
| 77 | # CONFIG_FILE and other home-relative constants are frozen during collection. |
| 78 | home = tempfile.TemporaryDirectory(prefix="last30days-tests-") |
| 79 | config.add_cleanup(home.cleanup) |
| 80 | patch = pytest.MonkeyPatch() |
| 81 | config.add_cleanup(patch.undo) |
| 82 | _isolate_environment(patch, Path(home.name)) |
| 83 | |
| 84 | |
| 85 | @pytest.fixture(autouse=True) |
| 86 | def _isolated_config(tmp_path_factory, monkeypatch): |
| 87 | """Start each test with empty config, stores, and project discovery inputs. |
| 88 | |
| 89 | Redirect HOME rather than stubbing store lookups: xurl and grok resolve |
| 90 | auth from plain files under HOME (``~/.xurl/auth.yml``), and |
| 91 | ``backends._xurl_finding`` calls ``stored_auth_status()`` directly, so a |
| 92 | stubbed ``has_stored_auth`` still reads a developer's real store. Tests |
| 93 | that need a populated store write one under the redirected home.""" |
| 94 | from lib import agentcookie, env |
| 95 | |
| 96 | home = tmp_path_factory.mktemp("home") |
| 97 | config_dir = _isolate_environment(monkeypatch, home) |
| 98 | monkeypatch.chdir(home) |
| 99 | monkeypatch.setattr(env, "_config_override", str(config_dir)) |
| 100 | monkeypatch.setattr(env, "CONFIG_DIR", config_dir) |
| 101 | monkeypatch.setattr(env, "CONFIG_FILE", config_dir / ".env") |
| 102 | # The sidecar role path is captured at import; keep every test on its own |
| 103 | # synthetic home even when admission starts consulting that role file. |
| 104 | monkeypatch.setattr( |
| 105 | agentcookie, "_DEFAULT_CONFIG_PATH", home / ".config" / "agentcookie" / "config.json" |
| 106 | ) |
| 107 | |
| 108 | |
| 109 | @pytest.fixture(autouse=True) |
| 110 | def _unthrottled_reddit_keyless(monkeypatch): |
| 111 | """The real limiter is process-global, so tests inherited a drained bucket and slept. |
| 112 | Only burst changes (rate stays real for wait-allowance math); throttle tests install their own.""" |
| 113 | from lib import http |
| 114 | |
| 115 | monkeypatch.setattr( |
| 116 | http, |
| 117 | "REDDIT_KEYLESS_LIMITER", |
| 118 | http.RateLimiter(rate_per_sec=http.DEFAULT_REDDIT_KEYLESS_RATE, burst=10_000), |
| 119 | ) |
| 120 | |
| 121 | |
| 122 | @pytest.fixture(autouse=True) |
| 123 | def _no_arctic_network(): |
| 124 | """Default Arctic transport collaborators to no-ops outside adapter tests.""" |
| 125 | with mock.patch("lib.reddit_arctic.fetch_scores", return_value={}), \ |
| 126 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]), \ |
| 127 | mock.patch("lib.reddit_arctic.fetch_post_comments", return_value=[]): |
| 128 | yield |
| 129 | |
| 130 | |
| 131 | @pytest.fixture(autouse=True) |
| 132 | def _no_rust_core_download(): |
| 133 | """Prevent offline unit tests from hitting GitHub Releases for last30days-core.""" |
| 134 | with mock.patch( |
| 135 | "lib.rust_accel._https_fetch_bytes", |
| 136 | side_effect=OSError("offline test: release binary download disabled"), |
| 137 | ): |
| 138 | yield |
| 139 | |
| 140 | |
| 141 | @pytest.fixture(autouse=True) |
| 142 | def _no_reddit_web_floor(): |
| 143 | """The Reddit lane's web floor searches the web for every run, so any |
| 144 | in-process Reddit run would reach the network. Default it to finding |
| 145 | nothing, with fresh per-run state; its own tests override this fixture.""" |
| 146 | from lib import reddit_discover, web_search_keyless |
| 147 | |
| 148 | reddit_discover.reset_run_state() |
| 149 | web_search_keyless.reset_rung_health() |
| 150 | with mock.patch( |
| 151 | "lib.reddit_discover.web_refs", side_effect=lambda *_a, **_k: reddit_discover.WebFloor(), |
| 152 | ): |
| 153 | yield |
| 154 | reddit_discover.reset_run_state() |
| 155 | web_search_keyless.reset_rung_health() |
| 156 | |
| 157 | |
| 158 | @pytest.fixture(autouse=True) |
| 159 | def _isolated_reddit_health(): |
| 160 | """Reddit path health persists to reddit-health.json in the config dir, |
| 161 | which _isolated_config already points at this test's own tmp home, and |
| 162 | keeps per-run states in module memory. Start and end every test with |
| 163 | neither, so a skip one test records never steers another.""" |
| 164 | from lib import reddit_health |
| 165 | |
| 166 | reddit_health.reset_run_state() |
| 167 | yield |
| 168 | reddit_health.reset_run_state() |
| 169 | |
| 170 | |
| 171 | @pytest.fixture(autouse=True) |
| 172 | def _isolated_reddit_session(monkeypatch): |
| 173 | """The logged-in Reddit session is resolved once per run in module memory, |
| 174 | and its limiter is process-global. Start every test with no session and a |
| 175 | bucket deep enough that no test waits; pacing tests build their own.""" |
| 176 | from lib import http, reddit_session |
| 177 | |
| 178 | reddit_session.reset_run_state() |
| 179 | monkeypatch.setattr( |
| 180 | http, "REDDIT_SESSION_LIMITER", http.RateLimiter(http.REDDIT_SESSION_RATE, burst=10_000), |
| 181 | ) |
| 182 | yield |
| 183 | reddit_session.reset_run_state() |
| 184 | |
| 185 | |
| 186 | @pytest.fixture(autouse=True) |
| 187 | def _no_reddit_kept_thread_comments(): |
| 188 | """The post-ranking comment pass fetches reddit.com for every kept Reddit |
| 189 | thread, so any in-process run that keeps one would reach the network. |
| 190 | Default it to a no-op; its own tests override this fixture.""" |
| 191 | with mock.patch( |
| 192 | "lib.reddit_keyless.enrich_source_items", side_effect=lambda items, **_kwargs: items, |
| 193 | ): |
| 194 | yield |
| 195 | |
| 196 | |
| 197 | @pytest.fixture(autouse=True) |
| 198 | def _no_company_lookup_network(monkeypatch): |
| 199 | """The company lookup needs no key and runs for every company-shaped topic, |
| 200 | so any in-process engine run would reach Wikidata. Default its HTTP seam to |
| 201 | "no match"; the resolver's own tests replace ``get`` on the same seam.""" |
| 202 | from types import SimpleNamespace |
| 203 | |
| 204 | from lib import company_resolve |
| 205 | |
| 206 | monkeypatch.setattr( |
| 207 | company_resolve, "http", SimpleNamespace(get=lambda *_args, **_kwargs: {"search": []}), |
| 208 | ) |
| 209 | |
| 210 | |
| 211 | @pytest.fixture(autouse=True) |
| 212 | def _no_patent_search_network(monkeypatch): |
| 213 | """The patent lane needs no key either, so a company run would reach USPTO. |
| 214 | Default its HTTP seam to a session whose searches find nothing; the lane's |
| 215 | own tests replace the seam.""" |
| 216 | from types import SimpleNamespace |
| 217 | |
| 218 | from lib import http, patents |
| 219 | |
| 220 | def post(url, *_args, **_kwargs): |
| 221 | if url.endswith("/session"): |
| 222 | return {"userCase": {"caseId": 1}}, {"x-access-token": "test-token"} |
| 223 | return {"numFound": 0, "patents": []} |
| 224 | |
| 225 | monkeypatch.setattr( |
| 226 | patents, "http", SimpleNamespace( |
| 227 | post=post, get=post, HTTPError=http.HTTPError, |
| 228 | classify_failure=http.classify_failure, |
| 229 | ), |
| 230 | ) |
| 231 | |
| 232 | |
| 233 | @pytest.fixture(autouse=True) |
| 234 | def _no_ambient_grok_cli(): |
| 235 | """Default the grok CLI to absent so no test resolves it from the developer's |
| 236 | own machine. grok is a new X-chain backend whose availability is a plain |
| 237 | filesystem check, so a machine with it installed and signed in would |
| 238 | otherwise silently change chain resolution in every existing X test. |
| 239 | Tests that exercise grok stub these themselves (test_grok_x, |
| 240 | test_backend_descriptors._x_env) and override this by patching inside the |
| 241 | test body.""" |
| 242 | # Stub the input (PATH resolution), not the logic: has_stored_auth and |
| 243 | # _is_available_uncached then both resolve absent on their own, leaving the |
| 244 | # module's real control flow intact for tests that exercise it. |
| 245 | with mock.patch("lib.grok_x.binary_path", return_value=None): |
| 246 | yield |
| 247 | |
| 248 | |
| 249 | @pytest.fixture(autouse=True) |
| 250 | def _grok_audit_passes(): |
| 251 | """Tests that fake the grok subprocess fake a build, not a binary on disk, |
| 252 | so the per-build tool-boundary audit cannot run against it. Default the |
| 253 | verdict to pass; tests/test_grok_audit.py and the boundary tests exercise |
| 254 | the real audit and verdict cache themselves.""" |
| 255 | from lib import grok_audit |
| 256 | |
| 257 | with mock.patch("lib.grok_audit.verdict_for", return_value=grok_audit.Verdict(grok_audit.PASS)): |
| 258 | yield |
| 259 | |
| 260 | |
| 261 | @pytest.fixture(autouse=True) |
| 262 | def _reset_probe_caches(): |
| 263 | """The doctor stack memoizes probe results in module-level dicts (safe for |
| 264 | the one-shot CLI process, wrong across tests). Clear them around every test |
| 265 | so a probe cached by one test can never leak into another. The jobs |
| 266 | lane's robots.txt rules are kept per host for a run the same way.""" |
| 267 | from lib import grok_x, health, xurl_x |
| 268 | from lib.job_boards import robots |
| 269 | |
| 270 | health.clear_dependency_probe_cache() |
| 271 | xurl_x.clear_availability_cache() |
| 272 | grok_x.clear_availability_cache() |
| 273 | robots.clear_cache() |
| 274 | yield |
| 275 | health.clear_dependency_probe_cache() |
| 276 | xurl_x.clear_availability_cache() |
| 277 | grok_x.clear_availability_cache() |
| 278 | robots.clear_cache() |
| 279 | |
| 280 | @pytest.fixture(autouse=True) |
| 281 | def _reset_reddit_keyless_memo(): |
| 282 | """The run memos (Reddit keyless and ScrapeCreators, source fetches) live for one command; tests are their own commands.""" |
| 283 | from lib import fetch_memo as _fetch_memo |
| 284 | from lib import http as _http |
| 285 | from lib import reddit as _reddit |
| 286 | |
| 287 | from lib import reddit_arctic as _reddit_arctic |
| 288 | from lib import reddit_search as _reddit_search |
| 289 | |
| 290 | def _reset(): |
| 291 | _http.reset_reddit_keyless_memo() |
| 292 | _reddit.reset_scrapecreators_memo() |
| 293 | _reddit_arctic.reset_memo() |
| 294 | _reddit_search.reset_run_state() |
| 295 | _fetch_memo.reset() |
| 296 | |
| 297 | _reset() |
| 298 | yield |
| 299 | _reset() |
| 300 | |
| 301 | |
| 302 | @pytest.fixture(autouse=True) |
| 303 | def _no_ambient_agent_host(monkeypatch): |
| 304 | """Strip agent-host markers so the LAW 7 host-plan gate stays off. |
| 305 | |
| 306 | Contributors mostly run this suite from inside Claude Code or Codex, whose |
| 307 | shells export CLAUDECODE / CODEX_* markers that CI never has. Tests that |
| 308 | exercise the gate set these themselves. |
| 309 | """ |
| 310 | from lib import env as _env |
| 311 | |
| 312 | for name in ( |
| 313 | *_env.AGENT_HOST_ENV_VARS, |
| 314 | _env.HOST_AGENT_VAR, |
| 315 | _env.X_HOST_VAR, |
| 316 | _env.ALLOW_ENGINE_PLAN_VAR, |
| 317 | ): |
| 318 | monkeypatch.delenv(name, raising=False) |
| 319 | yield |
| 320 |