"""Query uses current browser-fetch and public plugin contracts; no live I/O.""" import unittest from datetime import date from types import SimpleNamespace from unittest.mock import Mock, patch from plugins import ita_plugin as ita from test.ita.test_ita_compact import Response, day, encoded, route_config from vs_types import AppointmentType, AvailabilityStatus, VSAccount, VSPlgConfig class CalendarQueryTests(unittest.TestCase): def setUp(self): self.context = {"path": ita.CALENDAR_PATH, "service": "7002", "day": "2026-08-31"} self.page = SimpleNamespace(url="https://prenotami.esteri.it/BookingCalendar", tab_id="query-tab", run_js=Mock(side_effect=self.dom)) self.months = {} self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch", side_effect=self.response)) self.sleep = self.enterContext(patch.object(ita.time, "sleep")) def dom(self, script, *args): if script == "return 1;": return 1 self.assertEqual(script, ita.CALENDAR_DOM_SCRIPT) self.assertEqual(args[0], "context") return dict(self.context) def response(self, page, method, path, **kwargs): self.assertIs(page, self.page) self.assertEqual((method, path), ("POST", ita.AVAILABILITY_PATH)) payload = kwargs["json_data"] self.assertEqual(payload["_Servizio"], self.context["service"]) self.assertEqual(set(payload), {"_Servizio", "selectedDay"}) return Response(200, encoded(self.months.get(payload["selectedDay"], [])), "https://prenotami.esteri.it" + path) def scan(self, count=12): return ita.scan_until_first_available_month(self.page, lookahead_months=count, month_click_interval_seconds=0) def requested_months(self): return [call.kwargs["json_data"]["selectedDay"] for call in self.fetch.call_args_list] def plugin(self, *, service=7002, horizon=12): plugin = object.__new__(ita.ItaPlugin) config = route_config(service) config["calendar_scan"]["lookahead_months"] = horizon plugin.config = VSPlgConfig(account=VSAccount(username="pool@example.test", password="fixture"), session_max_life=0, free_config={"query_mode": "calendar", "otp_mode": "cloud", "apt_configs": {"route": config}}) plugin.free_config = plugin.config.free_config plugin.page, plugin.is_healthy = self.page, True plugin._log = Mock() plugin._prepared_calendar = None route = plugin._resolve_route(AppointmentType(routing_key="route")) plugin._record_calendar_prepared_route(route, role="query") return plugin def test_initial_positive_month_stops_and_sorts_last_slot_correctly(self): self.months["01/08/2026"] = [day("20/08/2026 00:00:00", 8, 7), day("12/08/2026 00:00:00")] scans = self.scan() self.assertEqual(self.requested_months(), ["01/08/2026"]) self.assertEqual([item.day for item in ita.available_calendar_days(scans[0])], [date(2026, 8, 12), date(2026, 8, 20)]) def test_sequential_months_stop_before_later_inventory(self): self.months.update({"01/08/2026": [day("31/08/2026 00:00:00", 0, -1)], "01/10/2026": [day("20/10/2026 00:00:00", 8, 7), day("12/10/2026 00:00:00")], "01/11/2026": [day("02/11/2026 00:00:00", 10, 9)]}) scans = self.scan() self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026", "01/10/2026"]) self.assertEqual(ita.available_calendar_days(scans[-1])[0].day, date(2026, 10, 12)) def test_empty_requires_complete_configured_horizon(self): self.assertEqual(self.scan(3), ((), (), ())) self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026", "01/10/2026"]) def test_cross_year_requests_exact_next_month(self): self.context["day"] = "2026-12-20" self.months["01/01/2027"] = [day("04/01/2027 00:00:00")] self.assertEqual(ita.available_calendar_days(self.scan(2)[-1])[0].day, date(2027, 1, 4)) self.assertEqual(self.requested_months(), ["01/12/2026", "01/01/2027"]) def test_response_for_skipped_or_previous_month_is_not_availability(self): for wrong_day in ("01/10/2026 00:00:00", "01/08/2026 00:00:00"): with self.subTest(wrong_day=wrong_day): self.fetch.reset_mock() self.months["01/09/2026"] = [day(wrong_day)] with self.assertRaisesRegex(ita.BizLogicError, "another month"): self.scan(3) self.assertEqual(len(self.fetch.call_args_list), 2) def test_wrong_month_is_rejected_even_when_all_its_days_are_sold_out(self): self.months["01/08/2026"] = [day("01/09/2026 00:00:00", 0, -1)] with self.assertRaisesRegex(ita.BizLogicError, "another month"): self.scan() self.fetch.assert_called_once() def test_transport_failure_mid_horizon_is_not_no_availability(self): self.fetch.side_effect = [self.response(self.page, "POST", ita.AVAILABILITY_PATH, json_data={"_Servizio": "7002", "selectedDay": "01/08/2026"}), ita.RateLimiteddError("synthetic rate limit")] with self.assertRaises(ita.RateLimiteddError): self.scan(3) self.assertEqual(len(self.fetch.call_args_list), 2) def test_html_or_malformed_json_is_not_an_empty_month(self): for body in ("unavailable", "[]", '"not-json"'): with self.subTest(body=body): self.fetch.side_effect = None self.fetch.return_value = Response(200, body, "https://prenotami.esteri.it" + ita.AVAILABILITY_PATH) with self.assertRaises(ita.BizLogicError): self.scan() def test_invalid_scan_horizons_never_make_network_requests(self): for value in (True, 0, -1, 121): with self.subTest(value=value), self.assertRaises(ita.ItaProtocolError): self.scan(value) self.fetch.assert_not_called() def test_interval_applies_between_months_only(self): ita.scan_until_first_available_month(self.page, lookahead_months=3, month_click_interval_seconds=1.5) self.assertEqual([call.args for call in self.sleep.call_args_list], [(1.5,), (1.5,)]) def test_wrong_calendar_path_or_runtime_id_prevents_requests(self): for service in ("", None, True, "0"): with self.subTest(service=service), self.assertRaises(ita.BizLogicError): self.context["service"] = service self.scan() self.page.url = "https://prenotami.esteri.it/UserArea" with self.assertRaises(ita.BizLogicError): self.scan() self.fetch.assert_not_called() def test_public_query_returns_earliest_date_without_slot_ids_or_times(self): self.months["01/09/2026"] = [day("20/09/2026 00:00:00", 8, 7), day("12/09/2026 00:00:00")] result = self.plugin().query(AppointmentType(routing_key="route")) self.assertTrue(result.success) self.assertEqual(result.availability_status, AvailabilityStatus.Available) self.assertEqual(result.earliest_date.date(), date(2026, 9, 12)) self.assertEqual(len(result.availability), 1) self.assertEqual(result.availability[0].times, []) self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026"]) def test_repeated_public_query_reuses_calendar_but_reads_fresh_inventory(self): plugin = self.plugin() self.months["01/08/2026"] = [day("31/08/2026 00:00:00")] first = plugin.query(AppointmentType(routing_key="route")) self.months["01/08/2026"] = [] self.months["01/09/2026"] = [day("12/09/2026 00:00:00")] second = plugin.query(AppointmentType(routing_key="route")) self.assertNotEqual(first.earliest_date, second.earliest_date) self.assertEqual(self.requested_months(), ["01/08/2026", "01/08/2026", "01/09/2026"]) def test_public_query_empty_horizon_returns_false_not_success(self): result = self.plugin(horizon=3).query(AppointmentType(routing_key="route")) self.assertFalse(result.success) self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable) self.assertEqual(len(self.fetch.call_args_list), 3) def test_region_uses_its_own_runtime_service(self): self.context["service"] = "9012" self.months["01/08/2026"] = [day("31/08/2026 00:00:00")] result = self.plugin(service=9012).query(AppointmentType(routing_key="route")) self.assertTrue(result.success) self.assertEqual(self.fetch.call_args.kwargs["json_data"]["_Servizio"], "9012") def test_identity_drift_during_request_never_publishes_a_result(self): self.months["01/08/2026"] = [day("31/08/2026 00:00:00")] for drift in ("account", "tab", "service", "unhealthy"): with self.subTest(drift=drift): self.context["service"], self.page.tab_id = "7002", "query-tab" plugin = self.plugin() self.fetch.reset_mock() def response(*args, **kwargs): reply = self.response(*args, **kwargs) if drift == "account": plugin.config.account.username = "other@example.test" elif drift == "tab": self.page.tab_id = "other-tab" elif drift == "service": self.context["service"] = "9012" else: plugin.is_healthy = False return reply self.fetch.side_effect = response with self.assertRaises(ita.BizLogicError): plugin.query(AppointmentType(routing_key="route")) self.fetch.assert_called_once() if __name__ == "__main__": unittest.main()