"""Offline single-artifact install, factory loading and hot-reload contracts.""" import ast import builtins from contextlib import ExitStack, redirect_stdout import hashlib import json from io import StringIO import os from pathlib import Path import sys from tempfile import TemporaryDirectory from types import SimpleNamespace import unittest from unittest.mock import Mock, patch from plugins import ita_plugin # Preload shared host dependencies, not a loader substitute. from test.ita.test_ita_protocol import live_route from utils import plugin_updater from vs_plg_factory import VSPlgFactory from vs_plg import IVSPlg from vs_types import AppointmentType, RateLimiteddError, VSBookResult, VSQueryResult ROOT = Path(__file__).resolve().parents[2] class SingleFileSourceContractTests(unittest.TestCase): def test_runtime_compiles_and_implements_the_host_interface(self): source = (ROOT / "plugins/ita_plugin.py").read_text() compile(source, "ita_plugin.py", "exec") tree = ast.parse(source) plugins = [node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "ItaPlugin"] self.assertEqual(len(plugins), 1) methods = {node.name for node in plugins[0].body if isinstance(node, ast.FunctionDef)} self.assertTrue(IVSPlg.__abstractmethods__ <= methods) self.assertTrue(issubclass(ita_plugin.ItaPlugin, IVSPlg)) def test_browser_lifecycle_reuses_the_installed_host_helpers(self): from utils import plugin_utils for name in ("init_chromium_options", "cleanup_browser_workspace", "filter_dates_in_range"): self.assertIs(getattr(ita_plugin, name), getattr(plugin_utils, name)) def test_runtime_has_no_private_italy_or_tool_imports_or_dynamic_packaging(self): tree = ast.parse((ROOT / "plugins/ita_plugin.py").read_text()) for node in ast.walk(tree): if isinstance(node, (ast.Import, ast.ImportFrom)): names = [node.module or ""] if isinstance(node, ast.ImportFrom) else [a.name for a in node.names] self.assertFalse(any(name == "plugins" or name.startswith(("plugins.", "tools.")) for name in names), names) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): self.assertNotIn(node.func.id, {"exec", "eval", "__import__"}) self.assertEqual(sorted(p.name for p in (ROOT / "plugins").glob("ita_*.py")), ["ita_plugin.py"]) class SingleFileInstallationTests(unittest.TestCase): def setUp(self): self.stack = ExitStack() self.addCleanup(self.stack.close) self.directory = Path(self.stack.enter_context(TemporaryDirectory())) self.source = (ROOT / "plugins/ita_plugin.py").read_text() self.path = self.directory / "ita_plugin.py" old_cwd = Path.cwd() os.chdir(self.directory) self.stack.callback(os.chdir, old_cwd) self.stack.enter_context(redirect_stdout(StringIO())) old_module = sys.modules.get("ita_plugin") def restore_module(): sys.modules.pop("ita_plugin", None) if old_module is not None: sys.modules["ita_plugin"] = old_module self.stack.callback(restore_module) original_import = builtins.__import__ def guarded_import(name, *args, **kwargs): if name == "plugins" or name.startswith(("plugins.", "tools.")): raise AssertionError("Single artifact attempted a private runtime import: " + name) return original_import(name, *args, **kwargs) self.stack.enter_context(patch("builtins.__import__", side_effect=guarded_import)) for target in ("socket.socket.connect", "socket.create_connection", "requests.sessions.Session.request", "subprocess.Popen"): self.stack.enter_context(patch(target, side_effect=AssertionError("Unexpected external I/O"))) self.stack.enter_context(patch.object(sys, "dont_write_bytecode", True)) self.factory = VSPlgFactory() self.factory.register_plugin("ita_plugin", str(self.path), "ItaPlugin") self.install(self.source, ita_plugin.ItaPlugin.version) def install(self, source, version): self.assertTrue(plugin_updater.download_and_install_plugin( "ita_plugin", version, code_content=source, plugins_dir=str(self.directory), expected_sha256=hashlib.sha256(source.encode()).hexdigest())) def create(self): plugin = self.factory.create("offline-single-file", "ita_plugin") self.stack.callback(plugin.cleanup) return plugin def test_only_one_uploaded_file_loads_all_runtime_sections(self): self.assertEqual([p.name for p in self.directory.glob("*.py")], ["ita_plugin.py"]) plugin = self.create() runtime = type(plugin).book.__globals__ for name in ("ItaRouteConfig", "_submit_final_once", "parse_otp_body", "prepare_calendar", "recheck_calendar_before_final"): self.assertEqual(runtime[name].__module__, "ita_plugin", name) self.assertEqual(runtime["parse_otp_body"]("OTP Code:001234"), "001234") self.assertEqual(plugin_updater.get_installed_plugins(str(self.directory))["ita_plugin"], ita_plugin.ItaPlugin.version) self.assertIsNot(runtime["ItaCapability"], ita_plugin.ItaCapability) def test_public_query_and_book_bind_the_loaded_file_not_canonical_import(self): plugin = self.create() plugin.page = SimpleNamespace(url="https://prenotami.esteri.it/UserArea", quit=Mock()) key = "slot.fixture.it.tourist" plugin.free_config = {"otp_mode": "cloud", "query_mode": "calendar", "apt_configs": {key: live_route()}} negative = VSQueryResult(success=False) runtime = type(plugin).book.__globals__ with patch.object(plugin, "health_check", return_value=True), \ patch.object(plugin, "_enter_service", return_value=negative), \ patch.dict(runtime, prepare_calendar=Mock()): self.assertIs(plugin.query(AppointmentType(routing_key=key)), negative) runtime["prepare_calendar"].assert_not_called() plugin.free_config = {"otp_mode": "cloud", "query_mode": "services_probe", "final_submit_enabled": False, "apt_configs": {key: live_route()}} plugin.config = SimpleNamespace(account=SimpleNamespace(username="fixture@example.test")) plugin.session_create_time = 1 route = runtime["resolve_route_config"](plugin.free_config["apt_configs"], key) plugin.page = SimpleNamespace(tab_id="fixture-tab", quit=Mock(), url="https://prenotami.esteri.it/BookingCalendar", run_js=Mock(return_value={"path": "/BookingCalendar", "service": str(route.service_id), "day": "2026-10-02"})) plugin._record_calendar_prepared_route(route, role="book") trigger = VSQueryResult(success=True, apt_type=AppointmentType(routing_key=key)) with patch.dict(runtime, recheck_calendar_before_final=Mock(return_value=None)), \ patch.object(ita_plugin, "recheck_calendar_before_final", side_effect=AssertionError("canonical runtime used")): result = plugin.book(trigger, {"username": "fixture@example.test"}) self.assertFalse(result.success) self.assertEqual(result.label, runtime["BOOKING_RECHECK_NONE_AVAILABLE_LABEL"]) runtime["recheck_calendar_before_final"].assert_called_once() def test_loaded_final_adapter_uses_the_instance_runtime_after_cache_replacement(self): plugin = self.create() runtime = type(plugin).book.__globals__ key = "slot.fixture.it.tourist" config = {key: live_route()} route = runtime["resolve_route_config"](config, key) configured_route = ita_plugin.resolve_route_config(config, key) self.assertNotEqual(route, configured_route) # Distinct loaded dataclass types. self.assertEqual(route.routing_key, configured_route.routing_key) expected = VSBookResult(success=False, label="synthetic") adapter = Mock(return_value=expected) self.create() # The host overwrites sys.modules['ita_plugin'] for Query. self.assertIsNot(sys.modules["ita_plugin"].ItaPlugin, type(plugin)) plugin.page = object() plugin.config = SimpleNamespace(account=SimpleNamespace(username="fixture@example.test")) plugin.free_config = {"apt_configs": config, "final_submit_enabled": True} plugin._prepared_calendar = object() candidate = SimpleNamespace(day="2026-10-02", time_label="10:05 - 11:05") with patch.dict(runtime, _submit_final_once=adapter, recheck_calendar_before_final=Mock(return_value=candidate)), \ patch.object(plugin, "_log"): signal = VSQueryResult(success=True, apt_type=AppointmentType(routing_key=key)) self.assertIs(plugin.book(signal, {"username": "fixture@example.test"}), expected) adapter.assert_called_once_with(plugin, route, candidate) plugin.page = None def test_loaded_adapter_uses_the_host_exception_classes(self): plugin = self.create() runtime = type(plugin).book.__globals__ with patch.dict(runtime, perform_browser_fetch=Mock(return_value=SimpleNamespace( status_code=429, url="https://prenotami.esteri.it/BookingCalendar/RetrieveTimeSlots"))), \ self.assertRaises(RateLimiteddError): runtime["_calendar_post"](object(), runtime["TIME_SLOTS_PATH"], {}, json.loads) def test_real_reload_replaces_code_and_preserves_process_wide_otp_lock(self): first = self.create() old = type(first).book.__globals__ updated = self.source.replace(f'version = "{ita_plugin.ItaPlugin.version}"', 'version = "1.0.200"') self.install(updated, "1.0.200") owner = self events = [] cfg = SimpleNamespace(plugin_config=SimpleNamespace(plugin_name="ita_plugin")) previous = SimpleNamespace(m_cfg=cfg, stop=lambda: events.append("stop")) class Wrapper: def __init__(self, cls, config, redis): self.m_cfg = config def load(self): events.append("load") self.plugin = owner.create() def start(self): events.append("start") # Execute the unmodified host function without importing/starting main. node = next(n for n in ast.parse((ROOT / "main.py").read_text()).body if isinstance(n, ast.FunctionDef) and n.name == "reload_wrappers_for_plugin") namespace = {"Dict": dict, "GCOWrapper": Wrapper, "sys": sys, "REDIS_CFG": {}} exec(compile(ast.Module(body=[node], type_ignores=[]), str(ROOT / "main.py"), "exec"), namespace) wrappers = {"fixture": previous} namespace["reload_wrappers_for_plugin"]("ita_plugin", wrappers, {"fixture": object}, Mock()) new = type(wrappers["fixture"].plugin).book.__globals__ self.assertEqual(events, ["stop", "load", "start"]) self.assertEqual(wrappers["fixture"].plugin.version, "1.0.200") for name in ("ItaPlugin", "ItaCapability", "OtpMailConfig", "_submit_final_once", "fetch_otp_from_cloud", "prepare_calendar"): self.assertIsNot(new[name], old[name], name) self.assertIsNot(new["ItaPlugin"].book, old["ItaPlugin"].book) self.assertIs(new["_OTP_INPUT_LOCK"], old["_OTP_INPUT_LOCK"]) self.assertIs(new["_OTP_INPUT_LOCK"], ita_plugin._OTP_INPUT_LOCK) with old["_OTP_INPUT_LOCK"]: self.assertFalse(new["_OTP_INPUT_LOCK"].acquire(blocking=False)) self.assertIs(type(first).book.__globals__, old) if __name__ == "__main__": unittest.main()