test_ita_single_file.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """Offline single-artifact install, factory loading and hot-reload contracts."""
  2. import ast
  3. import builtins
  4. from contextlib import ExitStack, redirect_stdout
  5. import hashlib
  6. import json
  7. from io import StringIO
  8. import os
  9. from pathlib import Path
  10. import sys
  11. from tempfile import TemporaryDirectory
  12. from types import SimpleNamespace
  13. import unittest
  14. from unittest.mock import Mock, patch
  15. from plugins import ita_plugin # Preload shared host dependencies, not a loader substitute.
  16. from test.ita.test_ita_protocol import live_route
  17. from utils import plugin_updater
  18. from vs_plg_factory import VSPlgFactory
  19. from vs_plg import IVSPlg
  20. from vs_types import AppointmentType, RateLimiteddError, VSBookResult, VSQueryResult
  21. ROOT = Path(__file__).resolve().parents[2]
  22. class SingleFileSourceContractTests(unittest.TestCase):
  23. def test_runtime_compiles_and_implements_the_host_interface(self):
  24. source = (ROOT / "plugins/ita_plugin.py").read_text()
  25. compile(source, "ita_plugin.py", "exec")
  26. tree = ast.parse(source)
  27. plugins = [node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "ItaPlugin"]
  28. self.assertEqual(len(plugins), 1)
  29. methods = {node.name for node in plugins[0].body if isinstance(node, ast.FunctionDef)}
  30. self.assertTrue(IVSPlg.__abstractmethods__ <= methods)
  31. self.assertTrue(issubclass(ita_plugin.ItaPlugin, IVSPlg))
  32. def test_browser_lifecycle_reuses_the_installed_host_helpers(self):
  33. from utils import plugin_utils
  34. for name in ("init_chromium_options", "cleanup_browser_workspace", "filter_dates_in_range"):
  35. self.assertIs(getattr(ita_plugin, name), getattr(plugin_utils, name))
  36. def test_runtime_has_no_private_italy_or_tool_imports_or_dynamic_packaging(self):
  37. tree = ast.parse((ROOT / "plugins/ita_plugin.py").read_text())
  38. for node in ast.walk(tree):
  39. if isinstance(node, (ast.Import, ast.ImportFrom)):
  40. names = [node.module or ""] if isinstance(node, ast.ImportFrom) else [a.name for a in node.names]
  41. self.assertFalse(any(name == "plugins" or name.startswith(("plugins.", "tools.")) for name in names), names)
  42. if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
  43. self.assertNotIn(node.func.id, {"exec", "eval", "__import__"})
  44. self.assertEqual(sorted(p.name for p in (ROOT / "plugins").glob("ita_*.py")), ["ita_plugin.py"])
  45. class SingleFileInstallationTests(unittest.TestCase):
  46. def setUp(self):
  47. self.stack = ExitStack()
  48. self.addCleanup(self.stack.close)
  49. self.directory = Path(self.stack.enter_context(TemporaryDirectory()))
  50. self.source = (ROOT / "plugins/ita_plugin.py").read_text()
  51. self.path = self.directory / "ita_plugin.py"
  52. old_cwd = Path.cwd()
  53. os.chdir(self.directory)
  54. self.stack.callback(os.chdir, old_cwd)
  55. self.stack.enter_context(redirect_stdout(StringIO()))
  56. old_module = sys.modules.get("ita_plugin")
  57. def restore_module():
  58. sys.modules.pop("ita_plugin", None)
  59. if old_module is not None:
  60. sys.modules["ita_plugin"] = old_module
  61. self.stack.callback(restore_module)
  62. original_import = builtins.__import__
  63. def guarded_import(name, *args, **kwargs):
  64. if name == "plugins" or name.startswith(("plugins.", "tools.")):
  65. raise AssertionError("Single artifact attempted a private runtime import: " + name)
  66. return original_import(name, *args, **kwargs)
  67. self.stack.enter_context(patch("builtins.__import__", side_effect=guarded_import))
  68. for target in ("socket.socket.connect", "socket.create_connection", "requests.sessions.Session.request",
  69. "subprocess.Popen"):
  70. self.stack.enter_context(patch(target, side_effect=AssertionError("Unexpected external I/O")))
  71. self.stack.enter_context(patch.object(sys, "dont_write_bytecode", True))
  72. self.factory = VSPlgFactory()
  73. self.factory.register_plugin("ita_plugin", str(self.path), "ItaPlugin")
  74. self.install(self.source, ita_plugin.ItaPlugin.version)
  75. def install(self, source, version):
  76. self.assertTrue(plugin_updater.download_and_install_plugin(
  77. "ita_plugin", version, code_content=source, plugins_dir=str(self.directory),
  78. expected_sha256=hashlib.sha256(source.encode()).hexdigest()))
  79. def create(self):
  80. plugin = self.factory.create("offline-single-file", "ita_plugin")
  81. self.stack.callback(plugin.cleanup)
  82. return plugin
  83. def test_only_one_uploaded_file_loads_all_runtime_sections(self):
  84. self.assertEqual([p.name for p in self.directory.glob("*.py")], ["ita_plugin.py"])
  85. plugin = self.create()
  86. runtime = type(plugin).book.__globals__
  87. for name in ("ItaRouteConfig", "_submit_final_once",
  88. "parse_otp_body", "prepare_calendar", "recheck_calendar_before_final"):
  89. self.assertEqual(runtime[name].__module__, "ita_plugin", name)
  90. self.assertEqual(runtime["parse_otp_body"]("OTP Code:001234"), "001234")
  91. self.assertEqual(plugin_updater.get_installed_plugins(str(self.directory))["ita_plugin"],
  92. ita_plugin.ItaPlugin.version)
  93. self.assertIsNot(runtime["ItaCapability"], ita_plugin.ItaCapability)
  94. def test_public_query_and_book_bind_the_loaded_file_not_canonical_import(self):
  95. plugin = self.create()
  96. plugin.page = SimpleNamespace(url="https://prenotami.esteri.it/UserArea", quit=Mock())
  97. key = "slot.fixture.it.tourist"
  98. plugin.free_config = {"otp_mode": "cloud", "query_mode": "calendar",
  99. "apt_configs": {key: live_route()}}
  100. negative = VSQueryResult(success=False)
  101. runtime = type(plugin).book.__globals__
  102. with patch.object(plugin, "health_check", return_value=True), \
  103. patch.object(plugin, "_enter_service", return_value=negative), \
  104. patch.dict(runtime, prepare_calendar=Mock()):
  105. self.assertIs(plugin.query(AppointmentType(routing_key=key)), negative)
  106. runtime["prepare_calendar"].assert_not_called()
  107. plugin.free_config = {"otp_mode": "cloud", "query_mode": "services_probe",
  108. "final_submit_enabled": False, "apt_configs": {key: live_route()}}
  109. plugin.config = SimpleNamespace(account=SimpleNamespace(username="fixture@example.test"))
  110. plugin.session_create_time = 1
  111. route = runtime["resolve_route_config"](plugin.free_config["apt_configs"], key)
  112. plugin.page = SimpleNamespace(tab_id="fixture-tab", quit=Mock(),
  113. url="https://prenotami.esteri.it/BookingCalendar",
  114. run_js=Mock(return_value={"path": "/BookingCalendar", "service": str(route.service_id),
  115. "day": "2026-10-02"}))
  116. plugin._record_calendar_prepared_route(route, role="book")
  117. trigger = VSQueryResult(success=True, apt_type=AppointmentType(routing_key=key))
  118. with patch.dict(runtime, recheck_calendar_before_final=Mock(return_value=None)), \
  119. patch.object(ita_plugin, "recheck_calendar_before_final", side_effect=AssertionError("canonical runtime used")):
  120. result = plugin.book(trigger, {"username": "fixture@example.test"})
  121. self.assertFalse(result.success)
  122. self.assertEqual(result.label, runtime["BOOKING_RECHECK_NONE_AVAILABLE_LABEL"])
  123. runtime["recheck_calendar_before_final"].assert_called_once()
  124. def test_loaded_final_adapter_uses_the_instance_runtime_after_cache_replacement(self):
  125. plugin = self.create()
  126. runtime = type(plugin).book.__globals__
  127. key = "slot.fixture.it.tourist"
  128. config = {key: live_route()}
  129. route = runtime["resolve_route_config"](config, key)
  130. configured_route = ita_plugin.resolve_route_config(config, key)
  131. self.assertNotEqual(route, configured_route) # Distinct loaded dataclass types.
  132. self.assertEqual(route.routing_key, configured_route.routing_key)
  133. expected = VSBookResult(success=False, label="synthetic")
  134. adapter = Mock(return_value=expected)
  135. self.create() # The host overwrites sys.modules['ita_plugin'] for Query.
  136. self.assertIsNot(sys.modules["ita_plugin"].ItaPlugin, type(plugin))
  137. plugin.page = object()
  138. plugin.config = SimpleNamespace(account=SimpleNamespace(username="fixture@example.test"))
  139. plugin.free_config = {"apt_configs": config, "final_submit_enabled": True}
  140. plugin._prepared_calendar = object()
  141. candidate = SimpleNamespace(day="2026-10-02", time_label="10:05 - 11:05")
  142. with patch.dict(runtime, _submit_final_once=adapter,
  143. recheck_calendar_before_final=Mock(return_value=candidate)), \
  144. patch.object(plugin, "_log"):
  145. signal = VSQueryResult(success=True, apt_type=AppointmentType(routing_key=key))
  146. self.assertIs(plugin.book(signal, {"username": "fixture@example.test"}), expected)
  147. adapter.assert_called_once_with(plugin, route, candidate)
  148. plugin.page = None
  149. def test_loaded_adapter_uses_the_host_exception_classes(self):
  150. plugin = self.create()
  151. runtime = type(plugin).book.__globals__
  152. with patch.dict(runtime, perform_browser_fetch=Mock(return_value=SimpleNamespace(
  153. status_code=429, url="https://prenotami.esteri.it/BookingCalendar/RetrieveTimeSlots"))), \
  154. self.assertRaises(RateLimiteddError):
  155. runtime["_calendar_post"](object(), runtime["TIME_SLOTS_PATH"], {}, json.loads)
  156. def test_real_reload_replaces_code_and_preserves_process_wide_otp_lock(self):
  157. first = self.create()
  158. old = type(first).book.__globals__
  159. updated = self.source.replace(f'version = "{ita_plugin.ItaPlugin.version}"', 'version = "1.0.200"')
  160. self.install(updated, "1.0.200")
  161. owner = self
  162. events = []
  163. cfg = SimpleNamespace(plugin_config=SimpleNamespace(plugin_name="ita_plugin"))
  164. previous = SimpleNamespace(m_cfg=cfg, stop=lambda: events.append("stop"))
  165. class Wrapper:
  166. def __init__(self, cls, config, redis):
  167. self.m_cfg = config
  168. def load(self):
  169. events.append("load")
  170. self.plugin = owner.create()
  171. def start(self):
  172. events.append("start")
  173. # Execute the unmodified host function without importing/starting main.
  174. node = next(n for n in ast.parse((ROOT / "main.py").read_text()).body
  175. if isinstance(n, ast.FunctionDef) and n.name == "reload_wrappers_for_plugin")
  176. namespace = {"Dict": dict, "GCOWrapper": Wrapper, "sys": sys, "REDIS_CFG": {}}
  177. exec(compile(ast.Module(body=[node], type_ignores=[]), str(ROOT / "main.py"), "exec"), namespace)
  178. wrappers = {"fixture": previous}
  179. namespace["reload_wrappers_for_plugin"]("ita_plugin", wrappers, {"fixture": object}, Mock())
  180. new = type(wrappers["fixture"].plugin).book.__globals__
  181. self.assertEqual(events, ["stop", "load", "start"])
  182. self.assertEqual(wrappers["fixture"].plugin.version, "1.0.200")
  183. for name in ("ItaPlugin", "ItaCapability", "OtpMailConfig", "_submit_final_once",
  184. "fetch_otp_from_cloud", "prepare_calendar"):
  185. self.assertIsNot(new[name], old[name], name)
  186. self.assertIsNot(new["ItaPlugin"].book, old["ItaPlugin"].book)
  187. self.assertIs(new["_OTP_INPUT_LOCK"], old["_OTP_INPUT_LOCK"])
  188. self.assertIs(new["_OTP_INPUT_LOCK"], ita_plugin._OTP_INPUT_LOCK)
  189. with old["_OTP_INPUT_LOCK"]:
  190. self.assertFalse(new["_OTP_INPUT_LOCK"].acquire(blocking=False))
  191. self.assertIs(type(first).book.__globals__, old)
  192. if __name__ == "__main__":
  193. unittest.main()