| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198 |
- """Offline single-artifact install, factory loading and hot-reload contracts."""
- import ast
- import builtins
- from contextlib import ExitStack, redirect_stdout
- import hashlib
- 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_calendar_book import FakePage
- from test.ita.test_ita_protocol import live_route
- from tools import ita_query_book_local as local
- from utils import plugin_updater
- from vs_plg_factory import VSPlgFactory
- from vs_plg import IVSPlg
- from vs_types import AppointmentType, 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, "1.0.1")
- 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", "submit_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"], "1.0.1")
- 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())
- plugin.free_config = {"otp_mode": "cloud", "query_mode": "calendar"}
- negative = VSQueryResult(success=False)
- runtime = type(plugin).book.__globals__
- with patch.dict(runtime, prepare_query_if_needed=Mock(return_value=negative)):
- self.assertIs(plugin.query(AppointmentType(routing_key="fixture")), negative)
- runtime["prepare_query_if_needed"].assert_called_once()
- key = "slot.fixture.it.tourist"
- 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
- plugin.page = FakePage()
- plugin.page.tab_id = "fixture-tab"
- plugin.page.quit = Mock()
- route = runtime["resolve_route_config"](plugin.free_config["apt_configs"], key)
- 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))
- approval = object()
- with patch.dict(runtime, _submit_final_once=adapter):
- self.assertIs(runtime["submit_final"](plugin, route, approval), expected)
- adapter.assert_called_once_with(plugin, route, approval)
- def test_local_observer_preserves_standard_false_book_result(self):
- plugin = self.create()
- observer = local.ObservedPlugin(plugin, "book")
- result = VSBookResult(success=False, label="retryable")
- plugin.book = Mock(return_value=result)
- self.assertIs(observer.book(VSQueryResult(), {}), result)
- self.assertIsNone(observer.error)
- 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('version = "1.0.1"', '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", "submit_final"):
- 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()
|