test_debug_ita_monitor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import ast
  2. import io
  3. import subprocess
  4. import sys
  5. import unittest
  6. from contextlib import redirect_stderr, redirect_stdout
  7. from pathlib import Path
  8. from unittest.mock import Mock, patch
  9. from tools.debug_ita_monitor import (
  10. DEFAULT_MAX_PROBES,
  11. DEFAULT_MAX_WAIT_SECONDS,
  12. MIN_SAFE_WAIT_SECONDS,
  13. run_monitor,
  14. )
  15. from tools.debug_ita_session import DebugConfigurationError
  16. from vs_types import AvailabilityStatus, VSQueryResult
  17. class FakeMonitorPage:
  18. def __init__(self):
  19. self.url = "https://prenotami.esteri.it/Services"
  20. self.form_structure = None
  21. def ele(self, _selector, timeout=None):
  22. del timeout
  23. return None
  24. def run_js(self, _script):
  25. return self.form_structure
  26. class FakeMonitorPlugin:
  27. sequence = ["none"]
  28. last_instance = None
  29. def __init__(self, group_id):
  30. self.group_id = group_id
  31. self.page = FakeMonitorPage()
  32. self.create_session_calls = 0
  33. self.query_calls = 0
  34. self.cleanup_calls = 0
  35. FakeMonitorPlugin.last_instance = self
  36. def set_log(self, logger):
  37. self.logger = logger
  38. def set_config(self, config):
  39. self.config = config
  40. def create_session(self):
  41. self.create_session_calls += 1
  42. def query(self, apt_type):
  43. behavior = self.sequence[min(self.query_calls, len(self.sequence) - 1)]
  44. self.query_calls += 1
  45. if behavior == "weak":
  46. self.page.form_structure = {
  47. "path": "/Services/Booking/1321",
  48. "form": {
  49. "method": "POST",
  50. "action_path": "/Services/Booking/1321",
  51. "secret": "must-not-appear",
  52. },
  53. "fields": [
  54. {
  55. "tag": "input",
  56. "type": "hidden",
  57. "id": "RequestToken",
  58. "name": "__RequestVerificationToken",
  59. "required": False,
  60. "value": "private@example.test",
  61. }
  62. ],
  63. "buttons": [],
  64. }
  65. return VSQueryResult(
  66. success=True,
  67. apt_type=apt_type,
  68. availability_status=AvailabilityStatus.NoneAvailable,
  69. )
  70. if behavior == "unexpected":
  71. return VSQueryResult(
  72. success=True,
  73. apt_type=apt_type,
  74. availability_status=AvailabilityStatus.Available,
  75. )
  76. if behavior == "error":
  77. raise RuntimeError(
  78. "private@example.test failed with token "
  79. "abcdefghijklmnopqrstuvwxyz123456"
  80. )
  81. return VSQueryResult(
  82. success=False,
  83. apt_type=apt_type,
  84. availability_status=AvailabilityStatus.NoneAvailable,
  85. )
  86. def cleanup(self):
  87. self.cleanup_calls += 1
  88. class DebugItaMonitorTests(unittest.TestCase):
  89. def setUp(self):
  90. FakeMonitorPlugin.sequence = ["none"]
  91. FakeMonitorPlugin.last_instance = None
  92. @staticmethod
  93. def _run(
  94. *,
  95. apply=True,
  96. max_probes=3,
  97. randint=lambda _minimum, _maximum: 60,
  98. sleep=lambda _seconds: None,
  99. ):
  100. stdout = io.StringIO()
  101. stderr = io.StringIO()
  102. with (
  103. patch(
  104. "tools.debug_ita_monitor.resolve_chrome_path",
  105. return_value=Path("/test/chrome"),
  106. ),
  107. patch(
  108. "tools.debug_ita_monitor._get_query_credentials",
  109. return_value=("offline@example.test", "offline-password"),
  110. ) as credential_reader,
  111. patch(
  112. "tools.debug_ita_monitor._prepare_query_profile",
  113. return_value=Path("/offline/ita-query-profile"),
  114. ) as profile_preparer,
  115. patch("tools.debug_ita_monitor.ItaPlugin", FakeMonitorPlugin),
  116. patch.dict("tools.debug_ita_monitor.os.environ", {}, clear=False),
  117. redirect_stdout(stdout),
  118. redirect_stderr(stderr),
  119. ):
  120. exit_code = run_monitor(
  121. {},
  122. apply=apply,
  123. non_interactive=True,
  124. min_wait=MIN_SAFE_WAIT_SECONDS,
  125. max_wait=DEFAULT_MAX_WAIT_SECONDS,
  126. max_probes=max_probes,
  127. randint=randint,
  128. sleep=sleep,
  129. )
  130. return (
  131. exit_code,
  132. stdout.getvalue(),
  133. stderr.getvalue(),
  134. credential_reader,
  135. profile_preparer,
  136. )
  137. def test_default_preflight_requires_no_credentials_or_plugin(self):
  138. exit_code, stdout, stderr, credential_reader, profile_preparer = self._run(
  139. apply=False
  140. )
  141. self.assertEqual(exit_code, 0)
  142. credential_reader.assert_not_called()
  143. profile_preparer.assert_not_called()
  144. self.assertIsNone(FakeMonitorPlugin.last_instance)
  145. self.assertIn("ITA_MONITOR_PREFLIGHT_OK", stdout)
  146. self.assertIn("external_request=false", stdout)
  147. self.assertEqual(stderr, "")
  148. def test_no_slot_monitor_reuses_one_session_and_stops_at_max_probes(self):
  149. FakeMonitorPlugin.sequence = ["none", "none", "none"]
  150. waits = []
  151. random_values = iter([60, 300])
  152. exit_code, stdout, stderr, _, _ = self._run(
  153. max_probes=3,
  154. randint=lambda _minimum, _maximum: next(random_values),
  155. sleep=waits.append,
  156. )
  157. plugin = FakeMonitorPlugin.last_instance
  158. self.assertEqual(exit_code, 0)
  159. self.assertEqual(plugin.create_session_calls, 1)
  160. self.assertEqual(plugin.query_calls, 3)
  161. self.assertEqual(plugin.cleanup_calls, 1)
  162. self.assertEqual(waits, [60, 300])
  163. self.assertIn("probe=3", stdout)
  164. self.assertIn("ITA_MONITOR_MAX_PROBES_REACHED", stdout)
  165. self.assertEqual(stderr, "")
  166. def test_weak_signal_stops_immediately_and_prints_sanitized_alert(self):
  167. FakeMonitorPlugin.sequence = ["none", "weak", "none"]
  168. waits = []
  169. exit_code, stdout, stderr, _, _ = self._run(
  170. max_probes=3,
  171. sleep=waits.append,
  172. )
  173. plugin = FakeMonitorPlugin.last_instance
  174. self.assertEqual(exit_code, 4)
  175. self.assertEqual(plugin.create_session_calls, 1)
  176. self.assertEqual(plugin.query_calls, 2)
  177. self.assertEqual(plugin.cleanup_calls, 1)
  178. self.assertEqual(waits, [60])
  179. self.assertIn("\aITA_MONITOR_WEAK_SIGNAL", stdout)
  180. self.assertIn("action=start-user-book-recheck-now", stdout)
  181. self.assertIn("ITA_BOOKING_FORM_STRUCTURE=", stdout)
  182. self.assertNotIn("private@example.test", stdout)
  183. self.assertNotIn("must-not-appear", stdout)
  184. self.assertEqual(stderr, "")
  185. def test_weak_signal_publishes_one_local_handoff_only_when_enabled(self):
  186. FakeMonitorPlugin.sequence = ["weak"]
  187. published = []
  188. stdout = io.StringIO()
  189. stderr = io.StringIO()
  190. with (
  191. patch(
  192. "tools.debug_ita_monitor.resolve_chrome_path",
  193. return_value=Path("/test/chrome"),
  194. ),
  195. patch(
  196. "tools.debug_ita_monitor._get_query_credentials",
  197. return_value=("offline@example.test", "offline-password"),
  198. ),
  199. patch(
  200. "tools.debug_ita_monitor._prepare_query_profile",
  201. return_value=Path("/offline/ita-query-profile"),
  202. ),
  203. patch("tools.debug_ita_monitor.ItaPlugin", FakeMonitorPlugin),
  204. patch.dict("tools.debug_ita_monitor.os.environ", {}, clear=False),
  205. redirect_stdout(stdout),
  206. redirect_stderr(stderr),
  207. ):
  208. exit_code = run_monitor(
  209. {},
  210. apply=True,
  211. non_interactive=True,
  212. min_wait=MIN_SAFE_WAIT_SECONDS,
  213. max_wait=DEFAULT_MAX_WAIT_SECONDS,
  214. max_probes=3,
  215. publish_local_signal=True,
  216. signal_publisher=lambda: published.append("weak"),
  217. )
  218. self.assertEqual(exit_code, 4)
  219. self.assertEqual(published, ["weak"])
  220. self.assertIn("ITA_MONITOR_HANDOFF_PUBLISHED", stdout.getvalue())
  221. self.assertEqual(stderr.getvalue(), "")
  222. def test_unexpected_result_stops_without_another_probe(self):
  223. FakeMonitorPlugin.sequence = ["unexpected", "none"]
  224. exit_code, stdout, _stderr, _, _ = self._run(max_probes=3)
  225. plugin = FakeMonitorPlugin.last_instance
  226. self.assertEqual(exit_code, 4)
  227. self.assertEqual(plugin.query_calls, 1)
  228. self.assertEqual(plugin.cleanup_calls, 1)
  229. self.assertIn("ITA_MONITOR_SAFE_STOP", stdout)
  230. def test_query_error_stops_without_retry_and_redacts_diagnostics(self):
  231. FakeMonitorPlugin.sequence = ["error", "none"]
  232. exit_code, stdout, stderr, _, _ = self._run(max_probes=3)
  233. plugin = FakeMonitorPlugin.last_instance
  234. self.assertEqual(exit_code, 1)
  235. self.assertEqual(plugin.query_calls, 1)
  236. self.assertEqual(plugin.cleanup_calls, 1)
  237. self.assertIn("ITA_MONITOR_FAILED type=RuntimeError", stdout)
  238. self.assertNotIn("private@example.test", stdout)
  239. self.assertNotIn("abcdefghijklmnopqrstuvwxyz123456", stdout)
  240. self.assertEqual(stderr, "")
  241. def test_ctrl_c_during_wait_cleans_up_without_traceback(self):
  242. def interrupted_sleep(_seconds):
  243. raise KeyboardInterrupt
  244. exit_code, stdout, stderr, _, _ = self._run(
  245. max_probes=3,
  246. sleep=interrupted_sleep,
  247. )
  248. plugin = FakeMonitorPlugin.last_instance
  249. self.assertEqual(exit_code, 130)
  250. self.assertEqual(plugin.query_calls, 1)
  251. self.assertEqual(plugin.cleanup_calls, 1)
  252. self.assertIn("ITA_MONITOR_CANCELLED", stdout)
  253. self.assertIn("ITA_MONITOR_CLEANUP_OK", stdout)
  254. self.assertNotIn("Traceback", stdout + stderr)
  255. def test_unsafe_limits_fail_before_credentials_or_plugin(self):
  256. with (
  257. patch(
  258. "tools.debug_ita_monitor._get_query_credentials",
  259. side_effect=AssertionError("credentials must not be read"),
  260. ),
  261. patch(
  262. "tools.debug_ita_monitor.ItaPlugin",
  263. side_effect=AssertionError("plugin must not be created"),
  264. ),
  265. self.assertRaises(DebugConfigurationError),
  266. ):
  267. run_monitor(
  268. {},
  269. apply=True,
  270. non_interactive=True,
  271. min_wait=59,
  272. max_wait=300,
  273. max_probes=1,
  274. )
  275. def test_cli_default_is_a_real_zero_network_preflight(self):
  276. repo_root = Path(__file__).resolve().parents[1]
  277. completed = subprocess.run(
  278. [sys.executable, str(repo_root / "tools" / "debug_ita_monitor.py")],
  279. cwd=repo_root,
  280. check=False,
  281. capture_output=True,
  282. text=True,
  283. )
  284. self.assertEqual(completed.returncode, 0)
  285. self.assertIn("ITA_MONITOR_PREFLIGHT_OK", completed.stdout)
  286. self.assertIn("external_request=false", completed.stdout)
  287. self.assertEqual(completed.stderr, "")
  288. def test_source_has_one_query_call_and_no_book_or_redis_dependency(self):
  289. source_path = (
  290. Path(__file__).resolve().parents[1]
  291. / "tools"
  292. / "debug_ita_monitor.py"
  293. )
  294. source = source_path.read_text(encoding="utf-8")
  295. tree = ast.parse(source)
  296. query_calls = [
  297. node
  298. for node in ast.walk(tree)
  299. if isinstance(node, ast.Call)
  300. and isinstance(node.func, ast.Attribute)
  301. and node.func.attr == "query"
  302. ]
  303. book_calls = [
  304. node
  305. for node in ast.walk(tree)
  306. if isinstance(node, ast.Call)
  307. and isinstance(node.func, ast.Attribute)
  308. and node.func.attr == "book"
  309. ]
  310. self.assertEqual(len(query_calls), 1)
  311. self.assertEqual(book_calls, [])
  312. self.assertNotIn("redis", source.lower())
  313. def test_defaults_match_the_existing_italy_sentinel_cadence(self):
  314. self.assertEqual(MIN_SAFE_WAIT_SECONDS, 60)
  315. self.assertEqual(DEFAULT_MAX_WAIT_SECONDS, 300)
  316. self.assertEqual(DEFAULT_MAX_PROBES, 10)
  317. if __name__ == "__main__":
  318. unittest.main()