"""Offline recovery contracts; no browser, credentials, or website requests.""" import json import sys import threading import time import types import unittest from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock, patch from DrissionPage.errors import PageDisconnectedError from plugins.ita_plugin import RUNTIME_SERVICE_SCRIPT from plugins.ita_plugin import ( AVAILABILITY_PATH, CalendarAccessDeniedError, CalendarAuthenticationExpiredError, CalendarGateError, CalendarRateLimitedError, CalendarTransientError, parse_availability_packet, ) from plugins.ita_plugin import ( ItaCalendarTransientError, ItaPlugin, ) from test.ita.test_debug_ita_production_query_gate import ( FakeProductionPage, gate_env, make_plugin, ) from vs_types import ( BizLogicError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, ) class RecoveryPage(FakeProductionPage): """Real Query and audit mechanics run against deterministic page responses.""" def __init__(self, outcomes=("available",), *, restore_outcome="calendar"): plans = [[(2026, 8, [12])]] * 100 super().__init__(plans) self.outcomes = list(outcomes) self.attempts = 0 self.tab_id = "offline-tab" self.runtime_service = "offline-runtime-service" self.restore_outcome = restore_outcome self.get_calls = [] def run_js(self, script, *args): if script == RUNTIME_SERVICE_SCRIPT: return {"path": "/BookingCalendar", "count": 1, "value": self.runtime_service} if script == "return 1;": if not self.driver.is_running: raise PageDisconnectedError("offline disconnected") return 1 return super().run_js(script, *args) def get(self, url): self.get_calls.append(url) if self.restore_outcome == "form": self.url = "https://prenotami.esteri.it/Services/Booking/9001" elif self.restore_outcome == "expired": self.url = "https://iam.esteri.it/signin/" else: self.url = url if self.restore_outcome == "wrong-service": self.runtime_service = "different-runtime-service" def refresh(self): outcome = self.outcomes[min(self.attempts, len(self.outcomes) - 1)] self.attempts += 1 if outcome == "disconnect": self.driver.is_running = False raise PageDisconnectedError("offline private@example.test secret-token") if outcome == "cancel": raise KeyboardInterrupt if outcome in {"expired", "timeout"}: if outcome == "expired": self.url = "https://iam.esteri.it/signin/" self.packet = None return if outcome == "none": self.plans[self.refresh_calls] = [(2026, month, []) for month in (8, 9, 10)] super().refresh() if outcome in {"rate", "denied"}: self.packet.response.status = 429 if outcome == "rate" else 403 if outcome == "malformed": self.packet.response.raw_body = "private@example.test secret-token" if outcome == "unexpected-otp": self.emit("/BookingCalendar/GenerateOTP?ServiceID=9001", "GET") self.emit("/BookingCalendar/RetrieveTimeSlots") # native auto-load, not a Query fanout def prepared_plugin(page=None): page = page or RecoveryPage() plugin, route = make_plugin(page) plugin.free_config["query_mode"] = "calendar" plugin.is_healthy = True plugin.session_create_time = time.time() plugin._reset_calendar_state() plugin._record_calendar_prepared_route(plugin._resolve_route(route.appointment_type()), role="query") return plugin, route def availability_packet(status=200, *, response_url=None): response = SimpleNamespace(status=status, raw_body=json.dumps(json.dumps([]))) if response_url is not None: response.url = response_url return SimpleNamespace( url="https://prenotami.esteri.it" + AVAILABILITY_PATH, method="POST", request=SimpleNamespace(postData={"_Servizio": "test-runtime", "selectedDay": "01/08/2026"}), response=response, ) class CalendarFailureClassificationTests(unittest.TestCase): def test_distinguishes_http_failure_categories(self): cases = { 401: CalendarAuthenticationExpiredError, 403: CalendarAccessDeniedError, 429: CalendarRateLimitedError, 408: CalendarTransientError, 502: CalendarTransientError, 503: CalendarTransientError, 504: CalendarTransientError, 418: CalendarGateError, } for status, expected in cases.items(): with self.subTest(status=status): packet = availability_packet(status) packet.response.raw_body = "private@example.test secret-token" with self.assertRaises(expected) as caught: parse_availability_packet(packet) self.assertNotIn("private@example.test", str(caught.exception)) self.assertNotIn("secret-token", str(caught.exception)) def test_followed_login_redirect_is_not_schema_or_no_inventory(self): with self.assertRaises(CalendarAuthenticationExpiredError): parse_availability_packet(availability_packet(response_url="https://iam.esteri.it/signin/")) def test_direct_login_redirect_is_classified_without_exposing_oauth_values(self): packet = availability_packet(302) packet.response.headers = {"Location": "https://iam.esteri.it/signin/?state=secret-token"} with self.assertRaises(CalendarAuthenticationExpiredError) as caught: parse_availability_packet(packet) self.assertNotIn("secret-token", str(caught.exception)) def test_invalid_http_status_is_not_a_retryable_network_failure(self): for value in (False, "200", None): with self.subTest(value=value), self.assertRaises(CalendarGateError) as caught: parse_availability_packet(availability_packet(value)) self.assertNotIsInstance(caught.exception, CalendarTransientError) def test_foreign_or_unexpected_response_never_becomes_inventory(self): for url in ("https://foreign.example" + AVAILABILITY_PATH, "https://prenotami.esteri.it/Services"): with self.subTest(url=url), self.assertRaises(CalendarGateError): parse_availability_packet(availability_packet(response_url=url)) def test_auth_rate_and_permission_errors_invalidate_health_and_scan(self): for outcome, expected in (("expired", SessionExpiredOrInvalidError), ("rate", RateLimiteddError), ("denied", PermissionDeniedError)): with self.subTest(outcome=outcome): plugin, route = prepared_plugin(RecoveryPage([outcome])) with self.assertRaises(expected): plugin.query(route.appointment_type()) self.assertFalse(plugin.is_healthy) self.assertFalse(plugin.health_check()) self.assertFalse(hasattr(plugin, "last_calendar_query_scan")) self.assertIsNone(plugin._prepared_calendar) with self.assertRaises(SessionExpiredOrInvalidError): plugin.query(route.appointment_type()) self.assertEqual(plugin.page.attempts, 1) def test_transient_error_keeps_valid_session_without_old_scan(self): plugin, route = prepared_plugin(RecoveryPage(["timeout", "available"])) with self.assertRaises(ItaCalendarTransientError): plugin.query(route.appointment_type()) self.assertTrue(plugin.is_healthy) self.assertFalse(hasattr(plugin, "last_calendar_query_scan")) self.assertTrue(plugin.query(route.appointment_type()).success) def test_browser_disconnection_invalidates_health_without_hiding_type(self): plugin, route = prepared_plugin(RecoveryPage(["disconnect"])) with self.assertRaises(PageDisconnectedError): plugin.query(route.appointment_type()) self.assertFalse(plugin.health_check()) self.assertIsNone(plugin._prepared_calendar) def test_configured_lifetime_and_health_probe_clear_preparation(self): plugin, route = prepared_plugin() plugin.session_create_time = 1 self.assertFalse(plugin.health_check()) self.assertFalse(plugin.is_healthy) self.assertIsNone(plugin._prepared_calendar) def test_health_probe_does_not_turn_operator_cancel_into_disconnection(self): plugin, _ = prepared_plugin() plugin.page.run_js = Mock(side_effect=KeyboardInterrupt) with self.assertRaises(KeyboardInterrupt): plugin.health_check() self.assertTrue(plugin.is_healthy) class CalendarSessionOwnershipTests(unittest.TestCase): def test_ordinary_query_checks_identity_without_exporting_a_checkpoint(self): for mutation in ("account", "page", "generation", "service", "tab", "route"): with self.subTest(mutation=mutation): plugin, route = prepared_plugin() original = plugin.page if mutation == "account": plugin.config.account.username = "other@example.test" elif mutation == "page": plugin.page = RecoveryPage() elif mutation == "generation": plugin.session_create_time += 1 elif mutation == "service": plugin.page.runtime_service = "different-runtime" elif mutation == "tab": plugin.page.tab_id = "different-tab" elif mutation == "route": plugin.free_config["apt_configs"][route.routing_key]["service_id"] = 9002 with self.assertRaises(BizLogicError): plugin.query(route.appointment_type()) self.assertEqual(original.refresh_calls, 0) self.assertEqual(plugin.page.refresh_calls, 0) def test_query_proof_cannot_be_copied_to_another_page(self): first, route = prepared_plugin() second, _ = prepared_plugin() second.session_create_time = first.session_create_time second._prepared_calendar = first._prepared_calendar with self.assertRaises(BizLogicError): second.query(route.appointment_type()) self.assertEqual(second.page.refresh_calls, 0) def test_preparation_cannot_attest_a_replaced_page_after_reading_the_old_one(self): plugin, route = prepared_plugin() old_page = plugin.page read = old_page.run_js def replace_page_during_read(script, *args): result = read(script, *args) plugin.page = RecoveryPage() return result old_page.run_js = replace_page_during_read with self.assertRaises(BizLogicError): plugin._record_calendar_prepared_route(plugin._resolve_route(route.appointment_type()), role="query") self.assertIsNone(plugin._prepared_calendar) self.assertEqual(old_page.refresh_calls, 0) self.assertEqual(plugin.page.refresh_calls, 0) def test_query_rechecks_ownership_before_publishing_inventory(self): plugin, route = prepared_plugin() publish = plugin.page._publish_month def change_account_during_response(): publish() plugin.config.account.username = "other@example.test" plugin.page._publish_month = change_account_during_response with self.assertRaises(BizLogicError): plugin.query(route.appointment_type()) self.assertEqual(plugin.page.refresh_calls, 1) self.assertFalse(hasattr(plugin, "last_calendar_query_scan")) self.assertEqual(plugin.page.final_requests, 0) def test_changed_runtime_tab_or_generation_rejects_next_query(self): for mutation in ("service", "tab", "generation"): with self.subTest(mutation=mutation): plugin, route = prepared_plugin() if mutation == "service": plugin.page.runtime_service = "changed" elif mutation == "tab": plugin.page.tab_id = "changed" else: plugin.session_create_time += 1 with self.assertRaises(BizLogicError): plugin.query(route.appointment_type()) self.assertEqual(plugin.page.refresh_calls, 0) def test_real_cleanup_uses_shared_best_effort_contract(self): plugin, _route = prepared_plugin() plugin.__dict__.pop("cleanup") plugin.root_workspace = "/nonexistent/ita-offline-cleanup-test" plugin.tunnel = SimpleNamespace(stop=Mock()) page = plugin.page page.quit = Mock(side_effect=RuntimeError("private@example.test secret-token")) plugin.cleanup() self.assertIsNone(plugin.page) self.assertFalse(plugin.is_healthy) plugin.__del__() page.quit.assert_called_once() class ExistingSentinelLifecycleTests(unittest.TestCase): def test_real_monitor_retires_failed_italy_session_once_without_publishing(self): # Import from the same already-stubbed dependency environment as other # repository tests. Neither __init__ nor live API/Redis is invoked. from test.ita.test_ita_plugin import GroupConfig, Task try: from sentinel import SentinelGCO except ModuleNotFoundError as exc: if exc.name != "redis": raise redis_stub = types.ModuleType("redis") redis_stub.Redis = Mock with patch.dict(sys.modules, {"redis": redis_stub}): from sentinel import SentinelGCO from vs_types import QueryWaitConfig, QueryWaitMode plugin, route = prepared_plugin(RecoveryPage(["expired"])) config = GroupConfig(identifier="offline-italy") config.appointment_types = [route.appointment_type()] config.appointment_types[0].weight = 1 config.sentinel.query_wait = QueryWaitConfig(mode=QueryWaitMode.Fixed, fixed_wait=60) sentinel = SentinelGCO.__new__(SentinelGCO) sentinel.m_cfg = config sentinel.m_logger = Mock() sentinel.redis_client = Mock() sentinel.m_lock = threading.RLock() sentinel.m_tasks = [Task(instance=plugin, qw_cfg=config.sentinel.query_wait, next_run=0)] sentinel.m_stop_event = Mock() sentinel.m_stop_event.is_set.side_effect = [False, False, True] # Patch the loaded method's dependencies directly. patch.dict(sys.modules) # removes temporary modules on exit, so string-based patch would import # Sentinel again and require an installed/live Redis dependency. isolated = { "time": SimpleNamespace(sleep=lambda _delay: None, time=lambda: 1000), "VSCloudApi": SimpleNamespace(Instance=Mock(return_value=Mock())), } with patch.dict(SentinelGCO._monitor_loop.__globals__, isolated): sentinel._monitor_loop() self.assertEqual(sentinel.m_tasks, []) plugin.cleanup.assert_called_once() sentinel.redis_client.setex.assert_not_called() self.assertEqual(plugin.page.attempts, 1) if __name__ == "__main__": unittest.main()