AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
test: isolate the suite from the developer's last30days config (#1265)
Ilia Alshanetsky715f7fde7260
diff --git a/tests/conftest.py b/tests/conftest.pyindex 98f5909c..4e2f4636 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,5 +1,8 @@import os+import shutil+import subprocessimport sys+import tempfilefrom pathlib import Pathfrom unittest import mock@@ -10,6 +13,90 @@ pytest_plugins = ["tests.network_guard"]sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "skills" / "last30days" / "scripts"))+_CONFIG_ENV_NAMES = {+ "AUTH_TOKEN", "CT0", "TWITTER_CT0", "SESSION_ID",+ "FROM_BROWSER", "BROWSER_CONSENT", "BROWSER_CDP_URL", "SETUP_COMPLETE",+ "AGENTCOOKIE", "AGENTCOOKIE_CONFIG", "INCLUDE_SOURCES", "EXCLUDE_SOURCES",+ "FUN_LEVEL", "ELI5_MODE", "DEGRADED_TRANSCRIPT_THRESHOLD", "TELEGRAM_SOURCES",+ "OPENAI_MODEL_PIN", "XAI_MODEL_PIN", "OPENAI_BASE_URL", "XAI_BASE_URL",+ "OPENROUTER_BASE_URL", "XIAOHONGSHU_API_BASE",+}+_CREDENTIAL_SUFFIXES = ("_API_KEY", "_TOKEN", "_KEY", "_SECRET", "_PASSWORD", "_COOKIE")+_system_which = shutil.which+_system_popen = subprocess.Popen+++def _without_credential_tools(command, *args, **kwargs):+ if Path(command).name in {"security", "pass"}:+ return None+ return _system_which(command, *args, **kwargs)+++def _isolate_environment(monkeypatch, home):+ for name in list(os.environ):+ if (+ name in _CONFIG_ENV_NAMES+ or name.startswith(("LAST30DAYS_", "BSKY_", "BIRD_"))+ or name.endswith(_CREDENTIAL_SUFFIXES)+ ):+ monkeypatch.delenv(name, raising=False)+ config_dir = home / ".config" / "last30days"+ config_dir.mkdir(parents=True)+ for name, value in {+ "HOME": home,+ "USERPROFILE": home,+ "XDG_CONFIG_HOME": home / ".config",+ "APPDATA": home / "AppData" / "Roaming",+ "LOCALAPPDATA": home / "AppData" / "Local",+ "PASSWORD_STORE_DIR": home / ".password-store",+ "LAST30DAYS_CONFIG_DIR": config_dir,+ }.items():+ monkeypatch.setenv(name, str(value))++ class IsolatedPopen(_system_popen):+ def __init__(self, *args, **kwargs):+ child_env = dict(os.environ if kwargs.get("env") is None else kwargs["env"])+ # Python mocks do not cross process boundaries; Keychain ignores HOME.+ child_env.setdefault("LAST30DAYS_SKIP_KEYCHAIN", "1")+ child_env.setdefault("HOME", str(home))+ child_env.setdefault("USERPROFILE", child_env["HOME"])+ child_env.setdefault("PASSWORD_STORE_DIR", str(Path(child_env["HOME"]) / ".password-store"))+ kwargs["env"] = child_env+ super().__init__(*args, **kwargs)++ monkeypatch.setattr(shutil, "which", _without_credential_tools)+ monkeypatch.setattr(subprocess, "Popen", IsolatedPopen)+ return config_dir+++def pytest_configure(config):+ # CONFIG_FILE and other home-relative constants are frozen during collection.+ home = tempfile.TemporaryDirectory(prefix="last30days-tests-")+ config.add_cleanup(home.cleanup)+ patch = pytest.MonkeyPatch()+ config.add_cleanup(patch.undo)+ _isolate_environment(patch, Path(home.name))++[email protected](autouse=True)+def _isolated_config(tmp_path_factory, monkeypatch):+ """Start each test with empty config, stores, and project discovery inputs.++ Redirect HOME rather than stubbing store lookups: xurl and grok resolve+ auth from plain files under HOME (``~/.xurl/auth.yml``), and+ ``backends._xurl_finding`` calls ``stored_auth_status()`` directly, so a+ stubbed ``has_stored_auth`` still reads a developer's real store. Tests+ that need a populated store write one under the redirected home."""+ from lib import env++ home = tmp_path_factory.mktemp("home")+ config_dir = _isolate_environment(monkeypatch, home)+ monkeypatch.chdir(home)+ monkeypatch.setattr(env, "_config_override", str(config_dir))+ monkeypatch.setattr(env, "CONFIG_DIR", config_dir)+ monkeypatch.setattr(env, "CONFIG_FILE", config_dir / ".env")++@pytest.fixture(autouse=True)def _no_arctic_network():"""Default Arctic transport collaborators to no-ops outside adapter tests."""@@ -34,37 +121,6 @@ def _no_ambient_grok_cli():yield[email protected](autouse=True)-def _no_ambient_xurl_store(tmp_path_factory, monkeypatch):- """Point HOME at an empty directory so no test resolves the developer's own- xurl token store, for the same reason as the grok fixture above. xurl is an- X-chain backend whose auth evidence is a plain filesystem check, so anyone- who has ever run xurl has a populated ``~/.xurl`` and silently resolves- xurl as a configured backend in tests that assume none is present.-- Observed with a populated store: three test_grok_surfacing doctor cases- report ``status == "ok"`` instead of ``"unconfigured"``, and- test_backend_descriptors.TestGetXSourceStatusGrokPin- .test_unpinned_with_store_does_not_return_grok_source fails- ``assert status["source"] is None`` with ``'xurl'``.-- Stubbing ``xurl_x.has_stored_auth`` is not enough, and three of those tests- already do it: ``backends._xurl_finding`` calls ``stored_auth_status()``- directly, so the real store is still read. Stubbing ``token_store_path``- instead breaks the tests that assert on it.-- Stub the input (where HOME points), not the logic: ``token_store_path``,- ``stored_auth_status`` and ``has_stored_auth`` all run their real code and- resolve absent on their own, and a test asserting- ``Path.home() / ".xurl" / "auth.yml"`` still agrees with them because both- sides move together. Tests that want a populated store write one under the- redirected home, as they already do."""- home = tmp_path_factory.mktemp("home")- monkeypatch.setenv("HOME", str(home))- monkeypatch.setenv("USERPROFILE", str(home))- yield--@pytest.fixture(autouse=True)def _reset_probe_caches():"""The doctor stack memoizes probe results in module-level dicts (safe for@@ -111,20 +167,3 @@ def _no_ambient_agent_host(monkeypatch):):monkeypatch.delenv(name, raising=False)yield--[email protected](autouse=True)-def _no_ambient_credentials(monkeypatch):- """Strip credential-shaped variables from the process environment.-- ``env.get_config()`` reads API keys and cookies straight from os.environ, so- a developer machine with real credentials exported resolves config the CI- box never would (upstream CI is a clean Linux runner). Tests that need a- credential set it themselves; nothing should depend on the ambient one.- """- suffixes = ("_API_KEY", "_TOKEN", "_KEY", "_SECRET", "_PASSWORD", "_COOKIE")- exact = {"AUTH_TOKEN", "CT0", "SESSION_ID"}- for name in list(os.environ):- if name in exact or name.endswith(suffixes):- monkeypatch.delenv(name, raising=False)- yielddiff --git a/tests/test_config_isolation.py b/tests/test_config_isolation.pynew file mode 100644index 00000000..895aaa3e--- /dev/null+++ b/tests/test_config_isolation.py@@ -0,0 +1,134 @@+"""Exercise the suite's isolation in fresh pytest processes with dirty config."""++import os+import subprocess+import sys+import textwrap+from pathlib import Path++import pytest+++ROOT = Path(__file__).resolve().parents[1]++[email protected]("config_override", [None, "", "custom"])+def test_conftest_isolates_config_before_collection_and_between_tests(tmp_path, config_override):+ developer_home = tmp_path / "developer"+ global_dir = developer_home / ".config" / "last30days"+ custom_dir = tmp_path / "custom"+ project = tmp_path / "project"+ suite = project / "tests"+ suite.mkdir(parents=True)+ (project / ".git").mkdir()+ project_config = project / ".claude"+ project_config.mkdir()+ dummy_config = (+ "FROM_BROWSER=chrome\nBROWSER_CONSENT=1\nSETUP_COMPLETE=1\n"+ "OPENAI_API_KEY=dummy-file-key\nLAST30DAYS_TRUST_PROJECT_CONFIG=1\n"+ )+ for directory in (global_dir, custom_dir):+ directory.mkdir(parents=True)+ (directory / ".env").write_text(dummy_config, encoding="utf-8")+ (project_config / "last30days.env").write_text(dummy_config, encoding="utf-8")+ (suite / "conftest.py").write_text((ROOT / "tests" / "conftest.py").read_text(), encoding="utf-8")+ (suite / "pytest.ini").write_text("[pytest]\n", encoding="utf-8")+ child = textwrap.dedent(f"""+ import os+ import platform+ import shutil+ import subprocess+ from lib import env+ platform.system = lambda: 'Darwin'+ shutil.which = lambda name: name if name in ('security', 'pass') else None+ def store_lookup(command, **kwargs):+ assert command[0] != 'security', 'child read the macOS Keychain'+ assert os.environ['PASSWORD_STORE_DIR'] != {str(developer_home / '.password-store')!r}+ return subprocess.CompletedProcess(command, 1, '', '')+ subprocess.run = store_lookup+ assert env.get_config()['OPENAI_API_KEY'] is None+ """)+ (suite / "test_probe.py").write_text(textwrap.dedent(f"""+ import os+ import platform+ import shutil+ import subprocess+ import sys+ from pathlib import Path+ from unittest import mock+ from lib import env++ imported_config_file = env.CONFIG_FILE+ imported_browser = os.environ.get('FROM_BROWSER')+ imported_key = os.environ.get('OPENAI_API_KEY')++ def test_collection_was_isolated():+ assert imported_config_file not in {{+ Path({str(global_dir / '.env')!r}), Path({str(custom_dir / '.env')!r})+ }}+ assert imported_browser is None+ assert imported_key is None++ def test_defaults_and_explicit_config():+ config = env.get_config(env.ConfigLoadPolicy(allow_project_config=True))+ assert config['FROM_BROWSER'] is None+ assert config['OPENAI_API_KEY'] is None+ assert config['SETUP_COMPLETE'] is None+ assert config['INCLUDE_SOURCES'] == ''+ assert config['LAST30DAYS_X_BACKEND'] is None+ assert 'LAST30DAYS_SKIP_KEYCHAIN' not in os.environ+ env.CONFIG_FILE.write_text('OPENAI_API_KEY=dummy-test-key\\n')+ assert env.get_config()['OPENAI_API_KEY'] == 'dummy-test-key'+ local = Path.cwd() / '.claude'+ local.mkdir()+ (local / 'last30days.env').write_text('OPENAI_API_KEY=dummy-project-key\\n')+ assert env.get_config(env.ConfigLoadPolicy(allow_project_config=True))['OPENAI_API_KEY'] == 'dummy-project-key'+ os.environ['FROM_BROWSER'] = 'firefox'+ os.environ['LAST30DAYS_X_BACKEND'] = 'grok'++ def test_next_test_starts_clean():+ config = env.get_config(env.ConfigLoadPolicy(allow_project_config=True))+ assert config['FROM_BROWSER'] is None+ assert config['OPENAI_API_KEY'] is None+ assert config['LAST30DAYS_X_BACKEND'] is None+ with mock.patch.object(platform, 'system', return_value='Darwin'), mock.patch.object(+ subprocess, 'run', side_effect=AssertionError('ambient credential lookup')+ ):+ assert env._load_keychain(['OPENAI_API_KEY']) == {{}}+ assert env._load_pass(['OPENAI_API_KEY'], 'last30days/') == {{}}++ def test_cli_child_cannot_read_ambient_stores():+ result = subprocess.run([sys.executable, '-c', {child!r}], capture_output=True, text=True)+ assert result.returncode == 0, result.stdout + result.stderr+ expected_home = str(Path.home())+ with mock.patch.dict(os.environ, {{}}, clear=True):+ result = subprocess.run(+ [sys.executable, '-c', "import os; print(os.environ['HOME'])"],+ capture_output=True, text=True,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout.strip() == expected_home+ """), encoding="utf-8")+ environment = dict(os.environ)+ environment.update({+ "HOME": str(developer_home),+ "USERPROFILE": str(developer_home),+ "PASSWORD_STORE_DIR": str(developer_home / ".password-store"),+ "FROM_BROWSER": "chrome",+ "BROWSER_CONSENT": "1",+ "OPENAI_API_KEY": "dummy-ambient-key",+ "LAST30DAYS_X_BACKEND": "grok",+ "LAST30DAYS_TRUST_PROJECT_CONFIG": "1",+ "LAST30DAYS_SKIP_KEYCHAIN": "1",+ "INCLUDE_SOURCES": "threads",+ "PYTHONPATH": os.pathsep.join([str(ROOT), str(ROOT / "skills" / "last30days" / "scripts")]),+ })+ environment.pop("LAST30DAYS_CONFIG_DIR", None)+ if config_override is not None:+ environment["LAST30DAYS_CONFIG_DIR"] = str(custom_dir) if config_override else ""+ result = subprocess.run(+ [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "--confcutdir", str(suite), str(suite)],+ cwd=project, env=environment, capture_output=True, text=True, timeout=30,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert "4 passed" in result.stdout