import ast import io import subprocess import sys import unittest from contextlib import redirect_stderr, redirect_stdout from pathlib import Path from unittest.mock import Mock, patch from tools.debug_ita_monitor import ( DEFAULT_MAX_PROBES, DEFAULT_MAX_WAIT_SECONDS, MIN_SAFE_WAIT_SECONDS, run_monitor, ) from tools.debug_ita_session import DebugConfigurationError from vs_types import AvailabilityStatus, VSQueryResult class FakeMonitorPage: def __init__(self): self.url = "https://prenotami.esteri.it/Services" self.form_structure = None def ele(self, _selector, timeout=None): del timeout return None def run_js(self, _script): return self.form_structure class FakeMonitorPlugin: sequence = ["none"] last_instance = None def __init__(self, group_id): self.group_id = group_id self.page = FakeMonitorPage() self.create_session_calls = 0 self.query_calls = 0 self.cleanup_calls = 0 FakeMonitorPlugin.last_instance = self def set_log(self, logger): self.logger = logger def set_config(self, config): self.config = config def create_session(self): self.create_session_calls += 1 def query(self, apt_type): behavior = self.sequence[min(self.query_calls, len(self.sequence) - 1)] self.query_calls += 1 if behavior == "weak": self.page.form_structure = { "path": "/Services/Booking/1321", "form": { "method": "POST", "action_path": "/Services/Booking/1321", "secret": "must-not-appear", }, "fields": [ { "tag": "input", "type": "hidden", "id": "RequestToken", "name": "__RequestVerificationToken", "required": False, "value": "private@example.test", } ], "buttons": [], } return VSQueryResult( success=True, apt_type=apt_type, availability_status=AvailabilityStatus.NoneAvailable, ) if behavior == "unexpected": return VSQueryResult( success=True, apt_type=apt_type, availability_status=AvailabilityStatus.Available, ) if behavior == "error": raise RuntimeError( "private@example.test failed with token " "abcdefghijklmnopqrstuvwxyz123456" ) return VSQueryResult( success=False, apt_type=apt_type, availability_status=AvailabilityStatus.NoneAvailable, ) def cleanup(self): self.cleanup_calls += 1 class DebugItaMonitorTests(unittest.TestCase): def setUp(self): FakeMonitorPlugin.sequence = ["none"] FakeMonitorPlugin.last_instance = None @staticmethod def _run( *, apply=True, max_probes=3, randint=lambda _minimum, _maximum: 60, sleep=lambda _seconds: None, ): stdout = io.StringIO() stderr = io.StringIO() with ( patch( "tools.debug_ita_monitor.resolve_chrome_path", return_value=Path("/test/chrome"), ), patch( "tools.debug_ita_monitor._get_query_credentials", return_value=("offline@example.test", "offline-password"), ) as credential_reader, patch( "tools.debug_ita_monitor._prepare_query_profile", return_value=Path("/offline/ita-query-profile"), ) as profile_preparer, patch( "tools.debug_ita_monitor._bind_query_profile", return_value=Mock(), ), patch("tools.debug_ita_monitor.ItaPlugin", FakeMonitorPlugin), patch.dict("tools.debug_ita_monitor.os.environ", {}, clear=False), redirect_stdout(stdout), redirect_stderr(stderr), ): exit_code = run_monitor( {}, apply=apply, non_interactive=True, min_wait=MIN_SAFE_WAIT_SECONDS, max_wait=DEFAULT_MAX_WAIT_SECONDS, max_probes=max_probes, randint=randint, sleep=sleep, ) return ( exit_code, stdout.getvalue(), stderr.getvalue(), credential_reader, profile_preparer, ) def test_default_preflight_requires_no_credentials_or_plugin(self): exit_code, stdout, stderr, credential_reader, profile_preparer = self._run( apply=False ) self.assertEqual(exit_code, 0) credential_reader.assert_not_called() profile_preparer.assert_not_called() self.assertIsNone(FakeMonitorPlugin.last_instance) self.assertIn("ITA_MONITOR_PREFLIGHT_OK", stdout) self.assertIn("external_request=false", stdout) self.assertEqual(stderr, "") def test_no_slot_monitor_reuses_one_session_and_stops_at_max_probes(self): FakeMonitorPlugin.sequence = ["none", "none", "none"] waits = [] random_values = iter([60, 300]) exit_code, stdout, stderr, _, _ = self._run( max_probes=3, randint=lambda _minimum, _maximum: next(random_values), sleep=waits.append, ) plugin = FakeMonitorPlugin.last_instance self.assertEqual(exit_code, 0) self.assertEqual(plugin.create_session_calls, 1) self.assertEqual(plugin.query_calls, 3) self.assertEqual(plugin.cleanup_calls, 1) self.assertEqual(waits, [60, 300]) self.assertIn("probe=3", stdout) self.assertIn("ITA_MONITOR_MAX_PROBES_REACHED", stdout) self.assertEqual(stderr, "") def test_weak_signal_stops_immediately_and_prints_sanitized_alert(self): FakeMonitorPlugin.sequence = ["none", "weak", "none"] waits = [] exit_code, stdout, stderr, _, _ = self._run( max_probes=3, sleep=waits.append, ) plugin = FakeMonitorPlugin.last_instance self.assertEqual(exit_code, 4) self.assertEqual(plugin.create_session_calls, 1) self.assertEqual(plugin.query_calls, 2) self.assertEqual(plugin.cleanup_calls, 1) self.assertEqual(waits, [60]) self.assertIn("\aITA_MONITOR_WEAK_SIGNAL", stdout) self.assertIn("action=start-user-book-recheck-now", stdout) self.assertIn("ITA_BOOKING_FORM_STRUCTURE=", stdout) self.assertNotIn("private@example.test", stdout) self.assertNotIn("must-not-appear", stdout) self.assertEqual(stderr, "") def test_weak_signal_publishes_one_local_handoff_only_when_enabled(self): FakeMonitorPlugin.sequence = ["weak"] published = [] stdout = io.StringIO() stderr = io.StringIO() with ( patch( "tools.debug_ita_monitor.resolve_chrome_path", return_value=Path("/test/chrome"), ), patch( "tools.debug_ita_monitor._get_query_credentials", return_value=("offline@example.test", "offline-password"), ), patch( "tools.debug_ita_monitor._prepare_query_profile", return_value=Path("/offline/ita-query-profile"), ), patch( "tools.debug_ita_monitor._bind_query_profile", return_value=Mock(), ), patch("tools.debug_ita_monitor.ItaPlugin", FakeMonitorPlugin), patch.dict("tools.debug_ita_monitor.os.environ", {}, clear=False), redirect_stdout(stdout), redirect_stderr(stderr), ): exit_code = run_monitor( {}, apply=True, non_interactive=True, min_wait=MIN_SAFE_WAIT_SECONDS, max_wait=DEFAULT_MAX_WAIT_SECONDS, max_probes=3, publish_local_signal=True, signal_publisher=lambda: published.append("weak"), ) self.assertEqual(exit_code, 4) self.assertEqual(published, ["weak"]) self.assertIn("ITA_MONITOR_HANDOFF_PUBLISHED", stdout.getvalue()) self.assertEqual(stderr.getvalue(), "") def test_unexpected_result_stops_without_another_probe(self): FakeMonitorPlugin.sequence = ["unexpected", "none"] exit_code, stdout, _stderr, _, _ = self._run(max_probes=3) plugin = FakeMonitorPlugin.last_instance self.assertEqual(exit_code, 4) self.assertEqual(plugin.query_calls, 1) self.assertEqual(plugin.cleanup_calls, 1) self.assertIn("ITA_MONITOR_SAFE_STOP", stdout) def test_query_error_stops_without_retry_and_redacts_diagnostics(self): FakeMonitorPlugin.sequence = ["error", "none"] exit_code, stdout, stderr, _, _ = self._run(max_probes=3) plugin = FakeMonitorPlugin.last_instance self.assertEqual(exit_code, 1) self.assertEqual(plugin.query_calls, 1) self.assertEqual(plugin.cleanup_calls, 1) self.assertIn("ITA_MONITOR_FAILED type=RuntimeError", stdout) self.assertNotIn("private@example.test", stdout) self.assertNotIn("abcdefghijklmnopqrstuvwxyz123456", stdout) self.assertEqual(stderr, "") def test_ctrl_c_during_wait_cleans_up_without_traceback(self): def interrupted_sleep(_seconds): raise KeyboardInterrupt exit_code, stdout, stderr, _, _ = self._run( max_probes=3, sleep=interrupted_sleep, ) plugin = FakeMonitorPlugin.last_instance self.assertEqual(exit_code, 130) self.assertEqual(plugin.query_calls, 1) self.assertEqual(plugin.cleanup_calls, 1) self.assertIn("ITA_MONITOR_CANCELLED", stdout) self.assertIn("ITA_MONITOR_CLEANUP_OK", stdout) self.assertNotIn("Traceback", stdout + stderr) def test_unsafe_limits_fail_before_credentials_or_plugin(self): with ( patch( "tools.debug_ita_monitor._get_query_credentials", side_effect=AssertionError("credentials must not be read"), ), patch( "tools.debug_ita_monitor.ItaPlugin", side_effect=AssertionError("plugin must not be created"), ), self.assertRaises(DebugConfigurationError), ): run_monitor( {}, apply=True, non_interactive=True, min_wait=59, max_wait=300, max_probes=1, ) def test_cli_default_is_a_real_zero_network_preflight(self): repo_root = Path(__file__).resolve().parents[2] completed = subprocess.run( [sys.executable, str(repo_root / "tools" / "debug_ita_monitor.py")], cwd=repo_root, check=False, capture_output=True, text=True, ) self.assertEqual(completed.returncode, 0) self.assertIn("ITA_MONITOR_PREFLIGHT_OK", completed.stdout) self.assertIn("external_request=false", completed.stdout) self.assertEqual(completed.stderr, "") def test_source_has_one_query_call_and_no_book_or_redis_dependency(self): source_path = ( Path(__file__).resolve().parents[2] / "tools" / "debug_ita_monitor.py" ) source = source_path.read_text(encoding="utf-8") tree = ast.parse(source) query_calls = [ node for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "query" ] book_calls = [ node for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "book" ] self.assertEqual(len(query_calls), 1) self.assertEqual(book_calls, []) self.assertNotIn("redis", source.lower()) def test_defaults_match_the_existing_italy_sentinel_cadence(self): self.assertEqual(MIN_SAFE_WAIT_SECONDS, 60) self.assertEqual(DEFAULT_MAX_WAIT_SECONDS, 300) self.assertEqual(DEFAULT_MAX_PROBES, 10) if __name__ == "__main__": unittest.main()