"""Bootstrap tests use temporary config files, not operator or production settings.""" from contextlib import closing import importlib.util import io import json import os from pathlib import Path import sqlite3 import subprocess import sys import tempfile import unittest from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] spec = importlib.util.spec_from_file_location("runtime_launcher", ROOT / "scripts/run.py") assert spec is not None and spec.loader is not None launcher = importlib.util.module_from_spec(spec) spec.loader.exec_module(launcher) sys.path.insert(0, str(ROOT / "bot")) runtime_config = __import__("runtime_config") class BootstrapTests(unittest.TestCase): def setUp(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) self.root = Path(tmp.name) (self.root / "bot").mkdir() (self.root / "gateway").mkdir() (self.root / "bot/webapp").mkdir() self.config = {"bot_token": "123456:offline-token", "main_key": "offline-main", "newapi_pass": "offline-password", "channel_username": "offline_channel", "bot_db": "./bot.db", "newapi_db": "./one-api.db", "newapi_url": "http://127.0.0.1:49100"} (self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8") with closing(sqlite3.connect(self.root / "one-api.db")) as con: con.execute("CREATE TABLE tokens(id INTEGER PRIMARY KEY)") con.commit() (self.root / ".env").write_text("IISHKO_SKIN_DB=./skin.db\n", encoding="utf-8") def test_explicit_root_dotenv_loads_without_shell_or_interpolation(self): (self.root / ".env").write_text( '\ufeffGROK_BOT_CFG=./bot/config.json\nIISHKO_SKIN_DB="./skin with space.db"\n' 'IISHKO_ENTRY_AUTOBAN=0 # comment\nOPAQUE="${SHELL_SECRET} $(nothing-executed)"\n', encoding="utf-8") env = launcher.prepare_environment(self.root, process={"SHELL_SECRET": "must-not-expand"}) self.assertEqual(env["GROK_BOT_CFG"], str(self.root / "bot/config.json")) self.assertEqual(env["IISHKO_ENTRY_AUTOBAN"], "0") self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "skin with space.db")) self.assertEqual(env["GATE_TG_DB"], env["IISHKO_SKIN_DB"]) self.assertEqual(env["OPAQUE"], "${SHELL_SECRET} $(nothing-executed)") self.assertEqual(launcher.check_configuration(env), []) def test_real_environment_including_legacy_alias_beats_file(self): (self.root / ".env").write_text("IISHKO_SKIN_DB=./file.db\nIISHKO_NOTIFICATIONS_ENABLED=1\n", encoding="utf-8") env = launcher.prepare_environment(self.root, process={"GATE_TG_DB": "./service.db", "IISHKO_NOTIFICATIONS_ENABLED": "0"}) self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "service.db")) self.assertEqual(env["IISHKO_NOTIFICATIONS_ENABLED"], "0") env = launcher.prepare_environment(self.root, process={"IISHKO_SKIN_DB": "./canonical.db", "GATE_TG_DB": "./old.db"}) self.assertEqual(env["GATE_TG_DB"], str(self.root / "canonical.db")) def test_legacy_config_and_db_aliases_are_shared_across_components(self): env = launcher.prepare_environment(self.root, process={"GROK_BOT_CONFIG": "./bot/config.json", "GATE_NEWAPI_DB": "./one-api.db"}) with patch.dict(os.environ, env, clear=True): self.assertEqual(runtime_config.bot_config_path(), env["GROK_BOT_CFG"]) self.assertEqual(runtime_config.gateway_db_path(), env["IISHKO_GW_DB"]) self.assertEqual(runtime_config.skin_db_path(), env["IISHKO_SKIN_DB"]) self.assertEqual(env["GATE_BOT_CONFIG"], env["GROK_BOT_CFG"]) self.assertEqual(env["GATE_NEWAPI_DB"], env["IISHKO_GW_DB"]) def test_no_parent_dotenv_discovery_and_explicit_missing_file_fails(self): (self.root / ".env").write_text("PARENT_ONLY=not-loaded\n", encoding="utf-8") child = self.root / "child" child.mkdir() self.assertNotIn("PARENT_ONLY", launcher.prepare_environment(child, process={})) with self.assertRaises(ValueError): launcher.prepare_environment(self.root, env_file="missing.env", process={}) def test_real_platform_module_separator_and_direct_legacy_fallback(self): env = launcher.prepare_environment(self.root, process={}) self.assertIn(str(self.root / "bot"), env["PYTHONPATH"].split(os.pathsep)) self.assertIn(str(self.root / "gateway"), env["PYTHONPATH"].split(os.pathsep)) with patch.dict(os.environ, {}, clear=True): self.assertEqual(runtime_config.skin_db_path(), "/opt/grok-web-skin-tg.db") self.assertFalse(runtime_config.notifications_enabled()) with patch.dict(os.environ, {"GATE_TG_DB": "legacy.db"}, clear=True): self.assertEqual(runtime_config.skin_db_path(), "legacy.db") def test_check_is_offline_and_never_starts_application(self): with patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=launcher.prepare_environment(self.root, process={})), patch.object(launcher.runpy, "run_path") as run, patch("sys.stdout", new_callable=io.StringIO) as out: self.assertEqual(launcher.main(["bot", "--check"]), 0) run.assert_not_called() self.assertIn("no app started", out.getvalue()) def test_normal_launch_receives_dotenv_paths_and_selected_entrypoint(self): env = launcher.prepare_environment(self.root, process={}) old_cwd, old_path, old_argv = Path.cwd(), list(sys.path), list(sys.argv) try: with patch.dict(os.environ, {}, clear=True), patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=env), patch.object(launcher.runpy, "run_path") as run: self.assertEqual(launcher.main(["miniapp"]), 0) run.assert_called_once_with(str(self.root / "bot/webapp/server.py"), run_name="__main__") self.assertEqual(os.environ["GROK_BOT_CONFIG"], str(self.root / "bot/config.json")) self.assertEqual(Path.cwd(), self.root) self.assertIn(str(self.root / "bot"), sys.path) finally: os.chdir(old_cwd) sys.path[:] = old_path sys.argv[:] = old_argv def test_missing_config_and_placeholders_fail_without_leaking_values(self): config_path = self.root / "bot/config.json" config_path.write_text('{"bot_token":"REPLACE_ME_PRIVATE_VALUE"}', encoding="utf-8") errors = launcher.check_configuration(launcher.prepare_environment(self.root, process={})) self.assertTrue(errors) self.assertNotIn("PRIVATE_VALUE", str(errors)) config_path.unlink() self.assertIn("missing", launcher.check_configuration(launcher.prepare_environment(self.root, process={}))[0]) def test_config_upstream_and_db_survive_without_explicit_env_overrides(self): env = launcher.prepare_environment(self.root, process={}) self.assertEqual(env["IISHKO_UPSTREAM"], self.config["newapi_url"]) self.assertEqual(env["NEWAPI_URL"], self.config["newapi_url"]) self.assertEqual(env["IISHKO_GW_DB"], str(self.root / "one-api.db")) self.assertNotIn("TG_SID_SECRET_FILE", env) with patch.dict(os.environ, env, clear=True): resolved = runtime_config.effective_bot_config(self.config) self.assertEqual(resolved["newapi_url"], env["IISHKO_UPSTREAM"]) self.assertEqual(resolved["newapi_db"], env["IISHKO_GW_DB"]) def test_env_secrets_override_config_for_validation_and_all_consumers(self): for key in ("bot_token", "newapi_pass"): self.config[key] = "REPLACE_ME_PRIVATE_VALUE" (self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8") process = {"GROK_BOT_TOKEN": "123456:env-offline-token", "NEWAPI_PASS": "env-offline-password", "NEWAPI_URL": "http://127.0.0.1:49101", "TG_SID_SECRET_FILE": "./existing-secret"} env = launcher.prepare_environment(self.root, process=process) self.assertEqual(launcher.check_configuration(env), []) self.assertEqual(env["TG_SID_SECRET_FILE"], str(self.root / "existing-secret")) with patch.dict(os.environ, env, clear=True): resolved = runtime_config.effective_bot_config(self.config) self.assertEqual(resolved["bot_token"], process["GROK_BOT_TOKEN"]) self.assertEqual(resolved["newapi_pass"], process["NEWAPI_PASS"]) self.assertEqual(resolved["newapi_url"], process["NEWAPI_URL"]) def test_preflight_rejects_invalid_data_directories_without_creating_db(self): env = launcher.prepare_environment(self.root, process={}) for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"): with self.subTest(key=key): changed = {**env, key: str(self.root / "missing-directory/new.db")} self.assertTrue(any(key in problem for problem in launcher.check_configuration(changed))) self.assertFalse(Path(changed[key]).exists()) def test_real_cli_reads_explicit_env_outside_repository_cwd(self): env_file = self.root / "runtime.env" env_file.write_text("\n".join(( "GROK_BOT_CFG=" + (self.root / "bot/config.json").as_posix(), "IISHKO_GW_DB=" + (self.root / "one-api.db").as_posix(), "IISHKO_APP_ROOT=" + (self.root / "bot").as_posix(), "IISHKO_BOT_DB=" + (self.root / "bot.db").as_posix(), "IISHKO_SKIN_DB=" + (self.root / "skin.db").as_posix(), )), encoding="utf-8") process = {key: value for key, value in os.environ.items() if not key.startswith(("IISHKO_", "GATE_", "GROK_", "NEWAPI_", "TG_SID_"))} for component in launcher.COMPONENTS: with self.subTest(component=component): result = subprocess.run([sys.executable, str(ROOT / "scripts/run.py"), component, "--env-file", str(env_file), "--check"], cwd=self.root, env=process, capture_output=True, text=True, timeout=15) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("preflight passed", result.stdout) def test_selfcheck_accepts_the_same_utf8_bom_config_as_entrypoints(self): sc_spec = importlib.util.spec_from_file_location("iishko_selfcheck", ROOT / "scripts/selfcheck.py") assert sc_spec is not None and sc_spec.loader is not None selfcheck = importlib.util.module_from_spec(sc_spec) sc_spec.loader.exec_module(selfcheck) config_path = self.root / "bot/config.json" config_path.write_text(json.dumps(self.config), encoding="utf-8-sig") self.assertEqual(config_path.read_bytes()[:3], b"\xef\xbb\xbf") problems, notes = [], [] with patch.object(selfcheck, "ROOT", str(self.root)), \ patch.dict(os.environ, {"GROK_BOT_CFG": str(config_path)}): selfcheck.check_config_templates(problems, notes) self.assertEqual(problems, []) self.assertFalse(any("bot config not found" in note for note in notes)) if __name__ == "__main__": unittest.main()