import copy import json import shutil import subprocess import traceback import unittest from contextlib import contextmanager from datetime import date, datetime from unittest.mock import Mock, patch from plugins import ita_plugin as book_calendar from plugins.ita_plugin import ( DATE_SELECTION_SCRIPT, SLOT_SELECTION_SCRIPT, TIME_SLOTS_PATH, CalendarBookError, book_date_preferences, recheck_calendar_before_final, ) from plugins.ita_plugin import AVAILABILITY_PATH, CalendarNextMonthUnavailableError from plugins.ita_plugin import ( BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL, ItaPlugin, ) from test.ita.test_ita_calendar_book import FakePage, SERVICE, packet from test.ita import test_ita_plugin as plugin_fixtures from test.ita.test_ita_protocol import availability_item, slot_item from vs_types import ( AppointmentType, BizLogicError, DateAvailability, RateLimiteddError, SessionExpiredOrInvalidError, TimeSlot, VSAccount, VSPlgConfig, VSQueryResult, ) def month(value, inventory, *, automatic_day=None, slots=None): """Synthetic inventory only; IDs and accounts below never leave the tests.""" return {"month": value, "inventory": inventory, "automatic_day": automatic_day, "slots": slots or {}} def positive_month(): return month("2026-10", {13: 1}) class FakeListener: def __init__(self, page): self.page = page self.queue = [] self.listening = False self.starts = 0 self.stops = 0 self.target = None def start(self, targets, method): self.starts += 1 self.target = targets self.queue.clear() # Matches the installed Listener.start contract. self.listening = True self.page.events.append("listen-start") if method != "POST": raise AssertionError("Unexpected listener method") def wait(self, timeout, raise_err=False): if not self.listening: raise AssertionError("Wait without listener") if self.page.wait_hook: self.page.wait_hook() if not self.queue: return False result = self.queue.pop(0) if result.url.endswith(TIME_SLOTS_PATH): self.page.selected_day = getattr(result, "fixture_day", None) self.page.content_day = self.page.render_day or self.page.selected_day self.page.current_slots = getattr(result, "fixture_slots", []) self.page.active = False return result def stop(self): self.stops += 1 self.queue.clear() self.listening = False self.page.events.append("listen-stop") class FlowPage(FakePage): def __init__(self, months=None, *, passes=None): super().__init__() self.tab_id = "book-tab" self.listen = FakeListener(self) self.wait = Mock() self.quit = Mock() self.passes = passes or [months or [positive_month()]] self.refreshes = 0 self.month_index = 0 self.month_spec = self.passes[0][0] self.selected_day = None self.content_day = None self.current_slots = [] self.date_clicks = [] self.month_clicks = 0 self.requests = [] self.request_mutator = None self.wait_hook = None self.render_day = None self.reverse_responses = False self.drop_automatic = False self.duplicate_availability = False self.date_ack = True self.date_candidate_count = None self.date_enabled = True self.date_runtime_matches = True def response_packet(self, path, body, items, day=None): result = packet(path, body, items) result.tab_id = self.tab_id result.is_failed = False result.fixture_day = day result.fixture_slots = items if self.request_mutator: self.request_mutator(result) self.requests.append(result) return result def times_packet(self, day): number = int(day[-2:]) free = self.month_spec["slots"].get(number, self.month_spec["inventory"].get(number, 0)) day_value = date.fromisoformat(day) items = [slot_item(day_value.strftime("%d/%m/%Y 00:00:00"), (10, 5), (11, 5), free, free - 1, 80000000 + self.refreshes * 100 + number)] return self.response_packet(TIME_SLOTS_PATH, {"selectedDay": day, "idService": SERVICE}, items, day) def load_month(self): self.selected_day = self.content_day = None value = self.month_spec["month"] inventory = self.month_spec["inventory"] items = [availability_item(date.fromisoformat(f"{value}-{day:02d}").strftime("%d/%m/%Y 00:00:00"), free, free - 1) for day, free in inventory.items()] availability = self.response_packet( AVAILABILITY_PATH, {"_Servizio": "calendar-runtime-key", "selectedDay": f"{value}-01"}, items, ) responses = [availability] if self.duplicate_availability: responses.append(availability) elif inventory and not self.drop_automatic: auto = self.month_spec["automatic_day"] or min(inventory) responses.append(self.times_packet(f"{value}-{auto:02d}")) if self.reverse_responses: responses.reverse() self.listen.queue.extend(responses) def refresh(self): self.refreshes += 1 self.month_index = 0 self.month_spec = self.passes[min(self.refreshes - 1, len(self.passes) - 1)][0] self.events.append("refresh") self.load_month() def next_month(self): self.month_clicks += 1 self.month_index += 1 sequence = self.passes[min(self.refreshes - 1, len(self.passes) - 1)] if self.month_index >= len(sequence): raise CalendarNextMonthUnavailableError("No next month in fixture") self.month_spec = sequence[self.month_index] self.events.append("next-month") self.load_month() def run_js(self, script, *args): if script == DATE_SELECTION_SCRIPT: service, day, click = args count = int(day[:7] == self.month_spec["month"] and int(day[-2:]) in self.month_spec["inventory"]) if self.date_candidate_count is not None: count = self.date_candidate_count selected = day == self.selected_day == self.content_day context = self.date_runtime_matches and service == self.service ready = context and count == 1 and self.date_enabled clicked = bool(click and self.date_ack and ready and not selected) raw = {"contextReady": context, "candidateCount": count, "candidateReady": ready, "selected": context and count == 1 and selected, "clicked": clicked} if clicked: self.date_clicks.append(day) self.events.append("date-click") self.listen.queue.append(self.times_packet(day)) return raw raw = super().run_js(script, *args) if script == SLOT_SELECTION_SCRIPT: _, day, daily_id, label, free, _ = args matching = [item for item in self.current_slots if str(item["IDCalendarioServizioGiornaliero"]) == daily_id] raw["contextReady"] = raw["contextReady"] and day == self.selected_day == self.content_day raw["candidateCount"] = len(matching) raw["candidateReady"] = (raw["contextReady"] and len(matching) == 1 and matching[0]["SlotLiberi"] == free) raw["selected"] = raw["candidateReady"] and self.active raw.update(self.after_overrides if self.clicks else {}) return raw @contextmanager def browser_navigation(page): original_click = book_calendar.click_next_month # Query and Book now share this function's module. Only intercept the # synthetic Book page; concurrent Query keeps its own native adapter. with patch.object(book_calendar, "click_next_month", side_effect=lambda actual: page.next_month() if actual is page else original_click(actual)), \ patch.object(book_calendar.time, "sleep"): yield def book_with_approval(plugin, trigger, inputs, *, call=None): captured = [] original = book_calendar.recheck_calendar_before_final def observe(*args, **kwargs): approval = original(*args, **kwargs) captured.append(approval) return approval with patch.object(book_calendar, "recheck_calendar_before_final", side_effect=observe): result = (call or plugin.book)(trigger, inputs) return result, captured[0] if captured else None def run_flow(page, **kwargs): options = dict(lookahead_months=3, start_day=date(2026, 8, 1), end_day=date(2026, 12, 31), session_is_current=lambda: True, month_click_interval_seconds=0, dom_timeout=0) options.update(kwargs) with browser_navigation(page): return recheck_calendar_before_final(page, **options) class BookCalendarFlowTests(unittest.TestCase): def assert_stopped(self, page): self.assertFalse(page.listen.listening) self.assertEqual(page.listen.starts, page.listen.stops) def test_refresh_waits_for_runtime_reassignment_without_repeating_refresh(self): page = FlowPage() original_run_js = page.run_js pending_reads = [] def delayed(script, *args): result = original_run_js(script, *args) if script == book_calendar.RUNTIME_SERVICE_SCRIPT and page.refreshes: pending_reads.append(True) if len(pending_reads) == 1: return {**result, "value": ""} return result page.run_js = delayed self.assertIsNotNone(run_flow(page, dom_timeout=1)) self.assertEqual(page.refreshes, 1) self.assertEqual(page.clicks, 1) self.assertEqual(len(page.requests), 2) self.assert_stopped(page) def test_empty_after_refresh_times_out_without_selecting_or_refreshing_again(self): page = FlowPage() original_refresh = page.refresh def empty_refresh(): original_refresh() page.service = "" page.refresh = empty_refresh with self.assertRaises(book_calendar.CalendarServiceNotReadyError): run_flow(page) self.assertEqual(page.refreshes, 1) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_automatic_positive_day_uses_fresh_response_without_date_click(self): page = FlowPage() result = run_flow(page) self.assertEqual(result.candidate.day, date(2026, 10, 13)) self.assertEqual(result.candidate.daily_calendar_id, "80000113") self.assertEqual(page.refreshes, 1) self.assertEqual(page.date_clicks, []) self.assertEqual(page.clicks, 1) self.assertEqual(len(page.requests), 2) self.assert_stopped(page) def test_native_date_click_is_followed_by_current_time_slots(self): page = FlowPage([month("2026-10", {1: 0, 13: 1})]) result = run_flow(page) self.assertEqual(result.candidate.day, date(2026, 10, 13)) self.assertEqual(page.date_clicks, ["2026-10-13"]) self.assertEqual(page.listen.starts, 2) self.assertEqual(len(page.requests), 3) self.assert_stopped(page) def test_each_captured_inventory_response_is_parsed_once(self): for inventory in ({13: 1}, {1: 0, 13: 1}): with self.subTest(inventory=inventory): page = FlowPage([month("2026-10", inventory)]) with patch.object(book_calendar, "parse_availability_packet", wraps=book_calendar.parse_availability_packet) as availability_parser, \ patch.object(book_calendar, "parse_book_time_slots", wraps=book_calendar.parse_book_time_slots) as slots_parser: self.assertIsNotNone(run_flow(page)) self.assertEqual(availability_parser.call_count, sum(p.url.endswith(AVAILABILITY_PATH) for p in page.requests)) self.assertEqual(slots_parser.call_count, sum(p.url.endswith(TIME_SLOTS_PATH) for p in page.requests)) self.assertEqual(page.clicks, 1) self.assert_stopped(page) def test_candidate_is_filtered_once_while_waiting_for_delayed_dom(self): page = FlowPage() original = page.run_js slot_reads = [] clock = [0.0] def delayed(script, *args): raw = original(script, *args) if script == SLOT_SELECTION_SCRIPT: slot_reads.append(args[-1]) if len(slot_reads) <= 2: raw.update(candidateReady=False, candidateCount=0) return raw page.run_js = delayed with browser_navigation(page), \ patch.object(book_calendar.time, "monotonic", side_effect=lambda: clock[0]), \ patch.object(book_calendar.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)), \ patch.object(book_calendar, "available_slot_candidates", wraps=book_calendar.available_slot_candidates) as select_candidates: result = recheck_calendar_before_final( page, lookahead_months=1, start_day=date(2026, 10, 1), end_day=date(2026, 10, 31), session_is_current=lambda: True, dom_timeout=0.5, ) self.assertIsNotNone(result) self.assertEqual(select_candidates.call_count, 1) self.assertEqual(slot_reads, [False, False, False, True, False]) self.assertEqual(page.clicks, 1) self.assertEqual(page.refreshes, 1) self.assertEqual(len(page.requests), 2) self.assert_stopped(page) def test_delayed_slot_timeout_is_bounded_without_extra_request_or_click(self): page = FlowPage() original = page.run_js clock = [0.0] def missing_slot(script, *args): raw = original(script, *args) if script == SLOT_SELECTION_SCRIPT: raw.update(candidateReady=False, candidateCount=0) return raw page.run_js = missing_slot with browser_navigation(page), \ patch.object(book_calendar.time, "monotonic", side_effect=lambda: clock[0]), \ patch.object(book_calendar.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)), \ self.assertRaisesRegex(CalendarBookError, "slot DOM did not match"): recheck_calendar_before_final( page, lookahead_months=1, start_day=date(2026, 10, 1), end_day=date(2026, 10, 31), session_is_current=lambda: True, dom_timeout=0.25, ) self.assertAlmostEqual(clock[0], 0.25) self.assertEqual(page.clicks, 0) self.assertEqual(page.refreshes, 1) self.assertEqual(len(page.requests), 2) self.assert_stopped(page) def test_old_listener_queue_is_cleared_before_month_action(self): page = FlowPage() stale = packet(TIME_SLOTS_PATH, {}, []) stale.tab_id = "query-tab" page.listen.queue.append(stale) result = run_flow(page) self.assertIsNotNone(result) self.assertIsNot(page.requests[-1], stale) def test_can_collect_automatic_response_before_availability_delivery(self): page = FlowPage() page.reverse_responses = True self.assertIsNotNone(run_flow(page)) self.assertEqual(page.date_clicks, []) def test_cross_year_scan_stops_at_first_usable_day(self): page = FlowPage([month("2026-12", {1: 0}), month("2027-01", {5: 1}), month("2027-02", {1: 4})]) result = run_flow(page, end_day=date(2027, 3, 1)) self.assertEqual(result.candidate.day, date(2027, 1, 5)) self.assertEqual(page.month_clicks, 1) def test_applies_inclusive_preferences_even_if_earlier_month_is_positive(self): page = FlowPage([month("2026-09", {1: 2}), month("2026-10", {12: 2, 13: 1, 14: 3})]) result = run_flow(page, start_day=date(2026, 10, 13), end_day=date(2026, 10, 13)) self.assertEqual(result.candidate.day, date(2026, 10, 13)) self.assertEqual(page.date_clicks, ["2026-10-13"]) self.assertEqual(page.month_clicks, 1) def test_date_inventory_race_tries_next_day_without_repeating_failed_candidate(self): page = FlowPage([month("2026-10", {13: 1, 14: 2}, slots={13: 0})]) result = run_flow(page) self.assertEqual(result.candidate.day, date(2026, 10, 14)) self.assertEqual(page.date_clicks, ["2026-10-14"]) self.assertEqual(page.clicks, 1) def test_later_automatic_day_is_recaptured_after_another_date_was_selected(self): page = FlowPage([month("2026-10", {13: 1, 14: 1}, automatic_day=14, slots={13: 0})]) result = run_flow(page) self.assertEqual(result.candidate.day, date(2026, 10, 14)) self.assertEqual(page.date_clicks, ["2026-10-13", "2026-10-14"]) def test_scans_applicant_inventory_once_in_chronological_order(self): page = FlowPage([month("2026-09", {9: 2}), month("2026-10", {13: 1})]) result = run_flow(page) self.assertEqual(result.candidate.day, date(2026, 9, 9)) self.assertEqual(page.refreshes, 1) self.assertEqual(page.month_clicks, 0) def test_full_negative_horizon_returns_none_without_slot_clicks(self): page = FlowPage([month("2026-08", {1: 0}), month("2026-09", {}), month("2026-10", {1: 0})]) self.assertIsNone(run_flow(page)) self.assertEqual(page.month_clicks, 2) self.assertEqual(page.date_clicks, []) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_no_month_beyond_user_end_is_requested(self): page = FlowPage([month("2026-10", {1: 0})]) self.assertIsNone(run_flow(page, end_day=date(2026, 10, 31))) self.assertEqual(page.month_clicks, 0) def test_missing_next_month_is_an_error_not_no_inventory(self): page = FlowPage([month("2026-10", {})]) with self.assertRaises(CalendarBookError): run_flow(page) self.assert_stopped(page) def test_month_jump_is_rejected(self): page = FlowPage([month("2026-08", {}), month("2026-10", {13: 1})]) with self.assertRaisesRegex(CalendarBookError, "exactly one month"): run_flow(page) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_bad_packet_metadata_is_never_used_or_retried(self): mutations = [ lambda p: setattr(p, "tab_id", "query-tab"), lambda p: setattr(p, "is_failed", True), lambda p: setattr(p, "url", "https://other.example.test" + AVAILABILITY_PATH), lambda p: setattr(p, "method", "GET"), lambda p: setattr(p.response, "status", 429), lambda p: p.request.postData.update(_Servizio=None), ] for mutate in mutations: with self.subTest(mutation=mutations.index(mutate)): page = FlowPage() page.request_mutator = mutate with self.assertRaises(CalendarBookError): run_flow(page) self.assertEqual(page.refreshes, 1) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_time_slots_from_wrong_date_or_service_fail(self): for field, value in (("selectedDay", "2026-10-14"), ("idService", "wrong-service")): page = FlowPage() page.request_mutator = lambda p: p.request.postData.update({field: value}) if p.url.endswith(TIME_SLOTS_PATH) else None with self.subTest(field=field), self.assertRaises(CalendarBookError): run_flow(page) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_date_click_response_is_bound_to_that_day_and_tab(self): for field in ("tab", "day"): with self.subTest(field=field): page = FlowPage([month("2026-10", {1: 0, 13: 1})]) def corrupt_after_click(result): if not page.date_clicks: return if field == "tab": result.tab_id = "old-query-tab" else: result.request.postData["selectedDay"] = "2026-10-01" page.request_mutator = corrupt_after_click with self.assertRaises(CalendarBookError): run_flow(page) self.assertEqual(page.date_clicks, ["2026-10-13"]) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_availability_service_must_remain_same_across_months(self): page = FlowPage([month("2026-09", {}), positive_month()]) page.request_mutator = lambda p: p.request.postData.update(_Servizio="changed") if page.month_clicks and p.url.endswith(AVAILABILITY_PATH) else None with self.assertRaisesRegex(CalendarBookError, "runtime service changed"): run_flow(page) def test_missing_automatic_response_and_duplicate_month_stop_listener(self): for option in ("drop_automatic", "duplicate_availability"): with self.subTest(option=option): page = FlowPage() setattr(page, option, True) with self.assertRaises(CalendarBookError): run_flow(page) self.assertEqual(page.date_clicks, []) self.assert_stopped(page) def test_negative_availability_but_positive_auto_slot_is_conflict(self): page = FlowPage([month("2026-10", {13: 0}, slots={13: 1})]) with self.assertRaisesRegex(CalendarBookError, "disagree"): run_flow(page) self.assertEqual(page.clicks, 0) def test_site_date_fallback_does_not_select_wrong_day(self): page = FlowPage() page.render_day = "2026-10-01" with self.assertRaisesRegex(CalendarBookError, "selected date"): run_flow(page) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_failed_date_click_is_not_retried(self): page = FlowPage([month("2026-10", {1: 0, 13: 1})]) page.date_ack = False with self.assertRaisesRegex(CalendarBookError, "acknowledged"): run_flow(page) self.assertEqual(page.date_clicks, []) self.assert_stopped(page) def test_bad_date_control_is_rejected_without_click(self): for field, value in (("date_candidate_count", 2), ("date_enabled", False), ("date_runtime_matches", False)): with self.subTest(field=field): page = FlowPage([month("2026-10", {1: 0, 13: 1})]) setattr(page, field, value) with self.assertRaises(CalendarBookError): run_flow(page) self.assertEqual(page.date_clicks, []) self.assert_stopped(page) def test_post_slot_click_error_stops_without_trying_another_day(self): page = FlowPage([month("2026-10", {13: 1, 14: 2})]) page.after_overrides = {"selected": False} with self.assertRaises(CalendarBookError): run_flow(page) self.assertEqual(page.clicks, 1) self.assertEqual(page.date_clicks, []) def test_context_invalid_before_or_during_capture_blocks_selection(self): page = FlowPage() with self.assertRaises(CalendarBookError): run_flow(page, session_is_current=lambda: False) self.assertEqual(page.refreshes, 0) current = [True] page = FlowPage() page.wait_hook = lambda: current.__setitem__(0, False) with self.assertRaises(CalendarBookError): run_flow(page, session_is_current=lambda: current[0]) self.assertEqual(page.clicks, 0) self.assert_stopped(page) def test_invalid_settings_do_not_navigate(self): for kwargs in ({"lookahead_months": True}, {"lookahead_months": 0}, {"start_day": None}, {"end_day": date(2025, 1, 1)}, {"timeout": 0}, {"timeout": float("nan")}, {"dom_timeout": -1}): with self.subTest(kwargs=kwargs): page = FlowPage() with self.assertRaises(CalendarBookError): run_flow(page, **kwargs) self.assertEqual(page.refreshes, 0) def test_provider_error_does_not_leak_raw_body(self): page = FlowPage() page.wait_hook = Mock(side_effect=RuntimeError("secret-response-body")) try: run_flow(page) except CalendarBookError: self.assertNotIn("secret-response-body", traceback.format_exc()) else: self.fail("Provider error was accepted") self.assert_stopped(page) class BookPreferenceTests(unittest.TestCase): def test_uses_existing_keys_and_does_not_mutate_inputs(self): values = {"expected_start_date": "2026-10-13", "expected_end_date": "2026-10-13", "other": "keep"} before = copy.deepcopy(values) self.assertEqual(book_date_preferences(values), (date(2026, 10, 13), date(2026, 10, 13))) self.assertEqual(values, before) self.assertEqual(book_date_preferences({}), (date(2000, 1, 1), date(2100, 1, 1))) def test_rejects_unknown_formats_and_inverted_range(self): for values in (None, {"expected_start_date": None}, {"expected_start_date": "20261013"}, {"expected_start_date": "2026-02-30"}, {"expected_start_date": "secret-input"}, {"expected_start_date": "2026-10-14", "expected_end_date": "2026-10-13"}): with self.subTest(values=values), self.assertRaises(CalendarBookError) as raised: book_date_preferences(values) self.assertNotIn("secret-input", str(raised.exception)) def prepared_plugin(page, *, routing_key="slot.example.it.tourist"): plugin = plugin_fixtures.ItaPluginQuerySafetyTests._plugin( page, routing_key=routing_key, service_id=9001, capability="single_schengen_tourism", lookahead_months=3, ) plugin.config = VSPlgConfig(account=VSAccount(username="applicant@example.test"), free_config=plugin.free_config) plugin.instance_id = "book-offline" plugin.session_create_time = 111.0 plugin.user_data_path = "/nonexistent/ita-book-flow-test" plugin._reset_calendar_state() route = plugin._resolve_route(AppointmentType(routing_key=routing_key)) plugin._record_calendar_prepared_route(route, role="book") plugin.query = Mock(side_effect=AssertionError("Calendar Book must not call Query")) trigger = VSQueryResult(apt_type=AppointmentType(routing_key=routing_key)) return plugin, route, trigger class BookEntryTests(unittest.TestCase): def test_query_and_book_share_month_reader_but_not_account_inventory(self): from test.ita.test_debug_ita_production_query_gate import FakeProductionPage, make_plugin query_page = FakeProductionPage([[(2026, 9, ()), (2026, 10, (13,))]]) query, query_route = make_plugin(query_page) query.free_config["query_mode"] = "calendar" book_page = FlowPage([month("2026-10", {13: 0, 14: 1})]) applicant, _, _ = prepared_plugin(book_page, routing_key=query_route.routing_key) with browser_navigation(book_page), patch.object( book_calendar, "_capture_month", wraps=book_calendar._capture_month ) as capture: signal = query.query(query_route.appointment_type()) result, approval = book_with_approval( applicant, signal, {"username": "applicant@example.test"}, ) self.assertTrue(signal.success) self.assertEqual(signal.earliest_date, datetime(2026, 10, 13)) self.assertFalse(result.success) # Pre-final selection is not a booking. self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) self.assertEqual(approval.candidate.day, date(2026, 10, 14)) self.assertNotEqual(query.config.account.username, applicant.config.account.username) self.assertEqual([call.args[0] for call in capture.call_args_list], [query_page, query_page, book_page]) self.assertTrue(all(call.kwargs.get("service") is None for call in capture.call_args_list[:2])) self.assertEqual(capture.call_args_list[2].kwargs["service"], SERVICE) self.assertEqual(query_page.final_requests, 0) self.assertEqual(book_page.guard_final_count, 0) self.assertEqual(book_page.clicks, 1) self.assertEqual(query_page.listen.stops, len(query_page.listen.starts)) self.assertEqual(book_page.listen.stops, book_page.listen.starts) applicant.query.assert_not_called() def test_real_entry_runs_flow_and_keeps_book_result_unsuccessful(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) inputs = {"username": "applicant@example.test", "expected_start_date": "2026-10-13", "expected_end_date": "2026-10-13"} original = copy.deepcopy(inputs) with browser_navigation(page): result, approval = book_with_approval(plugin, trigger, inputs) self.assertFalse(result.success) self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) self.assertEqual((result.urn, result.book_date, result.book_time, result.account), ("", "", "", "")) self.assertEqual(approval.candidate.day, date(2026, 10, 13)) self.assertNotIn("80000113", str(plugin.logger.call_args_list)) self.assertNotIn("applicant@example.test", str(plugin.logger.call_args_list)) self.assertEqual(inputs, original) plugin.query.assert_not_called() def test_entry_signal_date_does_not_override_earlier_applicant_inventory(self): page = FlowPage([month("2026-09", {1: 1}), month("2026-10", {13: 1})]) plugin, _, trigger = prepared_plugin(page) trigger.earliest_date = datetime(2026, 10, 13) trigger.availability = [DateAvailability(date=datetime(2026, 10, 13), times=[TimeSlot(time="01:23", label="stale-query-slot")])] with browser_navigation(page): result, approval = book_with_approval( plugin, trigger, {"username": "applicant@example.test"}, ) self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) self.assertEqual(approval.candidate.day, date(2026, 9, 1)) self.assertEqual(approval.candidate.time_label, "10:05 - 11:05") self.assertEqual(page.refreshes, 1) self.assertEqual(page.month_clicks, 0) def test_query_preparation_cannot_be_converted_into_book_preparation(self): page = FlowPage() plugin, route, trigger = prepared_plugin(page) plugin._reset_calendar_state() plugin._record_calendar_prepared_route(route, role="query") with self.assertRaises(BizLogicError): plugin._record_calendar_prepared_route(route, role="book") with self.assertRaises(BizLogicError): plugin.book(trigger, {"username": "applicant@example.test"}) self.assertEqual(page.refreshes, 0) def test_url_alone_is_not_a_book_preparation_proof(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) plugin._reset_calendar_state() plugin._enter_service = Mock(side_effect=BizLogicError("fresh preparation required")) with self.assertRaises(BizLogicError): plugin.book(trigger, {"username": "applicant@example.test"}) plugin._enter_service.assert_called_once() self.assertEqual(page.refreshes, 0) plugin.query.assert_not_called() def test_missing_or_different_applicant_is_rejected(self): for inputs in (None, {}, {"username": "other@example.test"}): with self.subTest(inputs=inputs): page = FlowPage() plugin, _, trigger = prepared_plugin(page) with self.assertRaises(BizLogicError): plugin.book(trigger, inputs) self.assertEqual(page.refreshes, 0) def test_changed_account_page_login_or_route_is_rejected(self): mutations = [ lambda p: setattr(p.config.account, "username", "other@example.test"), lambda p: setattr(p, "page", FlowPage()), lambda p: setattr(p, "session_create_time", 222.0), lambda p: setattr(p.page, "tab_id", "another-tab"), lambda p: p.free_config["apt_configs"]["slot.example.it.tourist"].update(service_id=9002), lambda p: p.free_config.update(final_submit_enabled=True), lambda p: setattr(p.page, "service", "another-runtime"), ] for mutation in mutations: with self.subTest(mutation=mutations.index(mutation)): page = FlowPage() plugin, _, trigger = prepared_plugin(page) mutation(plugin) with self.assertRaises(BizLogicError): plugin.book(trigger, {"username": "applicant@example.test"}) self.assertEqual(page.refreshes, 0) def test_preparation_from_another_page_is_rejected(self): first, _, _ = prepared_plugin(FlowPage()) second, _, trigger = prepared_plugin(FlowPage()) second._prepared_calendar = first._prepared_calendar with self.assertRaises(BizLogicError): second.book(trigger, {"username": "applicant@example.test"}) def test_second_book_call_rechecks_current_inventory(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) with browser_navigation(page): first, first_approval = book_with_approval( plugin, trigger, {"username": "applicant@example.test"}, ) second, second_approval = book_with_approval( plugin, trigger, {"username": "applicant@example.test"}, ) self.assertEqual(first.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) self.assertEqual(second.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) self.assertEqual(first_approval.candidate.day, second_approval.candidate.day) self.assertEqual(first_approval.candidate.time_label, second_approval.candidate.time_label) self.assertEqual(page.refreshes, 2) self.assertEqual(page.clicks, 2) def test_no_inventory_within_preferences_is_not_reported_as_success(self): page = FlowPage([month("2026-10", {13: 0})]) plugin, _, trigger = prepared_plugin(page) with browser_navigation(page): result, approval = book_with_approval( plugin, trigger, {"username": "applicant@example.test", "expected_end_date": "2026-10-31"}, ) self.assertFalse(result.success) self.assertEqual(result.label, BOOKING_RECHECK_NONE_AVAILABLE_LABEL) self.assertIsNone(approval) def test_mid_capture_account_change_invalidates_preparation(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) page.wait_hook = lambda: setattr(plugin.config.account, "username", "other@example.test") with browser_navigation(page), self.assertRaises(BizLogicError): plugin.book(trigger, {"username": "applicant@example.test"}) self.assertIsNone(plugin._prepared_calendar) self.assertEqual(page.clicks, 0) def test_account_change_during_candidate_dom_read_blocks_the_click(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) original = page.run_js def changed_account(script, *args): raw = original(script, *args) if script == SLOT_SELECTION_SCRIPT and args[-1] is False: plugin.config.account.username = "other@example.test" return raw page.run_js = changed_account with browser_navigation(page), self.assertRaises(BizLogicError): plugin.book(trigger, {"username": "applicant@example.test"}) self.assertIsNone(plugin._prepared_calendar) self.assertEqual(page.clicks, 0) self.assertEqual(page.date_clicks, []) def test_lifecycle_operations_clear_book_preparation(self): for action in ("config", "login", "cleanup"): with self.subTest(action=action): plugin, _, _ = prepared_plugin(FlowPage()) if action == "config": plugin.set_config(plugin.config) elif action == "login": with patch("plugins.ita_plugin.init_chromium_options", side_effect=RuntimeError("offline stop")): with self.assertRaises(RuntimeError): plugin.create_session() else: plugin.cleanup() self.assertIsNone(plugin._prepared_calendar) self.assertFalse(hasattr(plugin, "last_booking_precommit")) def test_http_auth_and_rate_limit_use_existing_framework_errors(self): for status, error in ((401, SessionExpiredOrInvalidError), (429, RateLimiteddError)): with self.subTest(status=status): page = FlowPage() plugin, _, trigger = prepared_plugin(page) page.request_mutator = lambda p: setattr(p.response, "status", status) with browser_navigation(page), self.assertRaises(error): plugin.book(trigger, {"username": "applicant@example.test"}) self.assertIsNone(plugin._prepared_calendar) self.assertEqual(page.clicks, 0) def test_provider_failure_at_entry_is_sanitized_and_invalidates_proof(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) page.browser_error = "secret-provider-body" try: plugin.book(trigger, {"username": "applicant@example.test"}) except BizLogicError: self.assertNotIn("secret-provider-body", traceback.format_exc()) else: self.fail("Provider failure was accepted") self.assertIsNone(plugin._prepared_calendar) def test_two_route_keys_share_the_same_calendar_flow(self): for key in ("slot.hkg.it.tourist", "slot.dub.it.tourist"): with self.subTest(key=key): page = FlowPage() plugin, _, trigger = prepared_plugin(page, routing_key=key) with browser_navigation(page): result = plugin.book(trigger, {"username": "applicant@example.test"}) self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) def test_query_mode_does_not_drive_the_prepared_book_branch(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) plugin.free_config["query_mode"] = "calendar" with browser_navigation(page): result = plugin.book(trigger, {"username": "applicant@example.test"}) self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) plugin.query.assert_not_called() def test_final_request_observation_rejects_instead_of_reporting_precommit(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) page.guard_final_count = 1 with browser_navigation(page), self.assertRaises(BizLogicError): plugin.book(trigger, {"username": "applicant@example.test"}) self.assertEqual(page.refreshes, 0) self.assertEqual(page.clicks, 0) DATE_JS_HARNESS = r""" const vm = require('node:vm'); const {source, mode} = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); let clicks = 0, finalClicks = 0; const zeroSize = mode.startsWith('zero_size') || mode === 'selected_zero_size'; function node(day) { const classes = new Set(['input-async-abilitato']); return {dataset: {date: day}, isConnected: true, classList: {contains: c => classes.has(c), add: c => classes.add(c)}, hasAttribute: () => false, getAttribute: () => null, getBoundingClientRect: () => ({width: zeroSize || mode === 'zero_width' ? 0 : 90, height: zeroSize || mode === 'zero_height' ? 0 : 30, left: 3000}), }; } const old = node('2026-10-01'), link = node('2026-10-13'); let selected = ['already_selected', 'selected_zero_size'].includes(mode) ? link : old; const content = node(selected.dataset.date); link.click = () => {clicks++; selected = link; content.dataset.date = link.dataset.date;}; if (['disabled', 'zero_size_disabled'].includes(mode)) link.classList.add('input-async-disabilitato'); if (mode === 'negative') link.classList.add('notAvailableDay'); const final = {disabled: mode !== 'unguarded', dataset: {coordinateFinalGuard: 'enabled'}, click: () => finalClicks++}; const document = { querySelectorAll(q) { if (q === '#idServizio') return [{value: mode === 'wrong_service' ? 'wrong' : '7002'}]; if (q === '#btnPrenotaNoOtp') return [final]; if (q === '.events a[data-date]') return mode === 'duplicate' ? [old, link, link] : [old, link]; if (q === '.events a.selected') return [selected]; if (q === '.events-content li.selected') return [content]; throw Error('Unexpected selector'); }, querySelector(q) {if (q === '.selected') return selected; throw Error('Unexpected selector');}, }; const window = { location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it', pathname: '/BookingCalendar'}, getComputedStyle: element => ({ display: ['hidden', 'zero_size_hidden'].includes(mode) ? 'none' : 'block', visibility: 'visible', opacity: '1', pointerEvents: mode === 'zero_size_pointer_blocked' || (mode === 'selected_zero_size' && element === selected) ? 'none' : 'auto', }), }; const run = click => vm.runInNewContext('(function(){' + source + '\n}).apply(null, args)', {document, window, args: ['7002', '2026-10-13', click]}, {timeout: 1000}); const before = run(false), acted = run(true), after = run(false); process.stdout.write(JSON.stringify({before, acted, after, clicks, finalClicks})); """ @unittest.skipUnless(shutil.which("node"), "Node is required for the native-date script contract") class BookDateJavaScriptTests(unittest.TestCase): def run_case(self, mode): completed = subprocess.run([shutil.which("node"), "-e", DATE_JS_HARNESS], input=json.dumps({"source": DATE_SELECTION_SCRIPT, "mode": mode}), text=True, capture_output=True, timeout=10, check=True) return json.loads(completed.stdout) def test_native_date_selection_can_target_offscreen_timeline_and_never_final(self): result = self.run_case("positive") self.assertEqual(result["clicks"], 1) self.assertTrue(result["after"]["selected"]) self.assertEqual(result["finalClicks"], 0) def test_already_selected_date_is_not_clicked_again(self): result = self.run_case("already_selected") self.assertEqual(result["clicks"], 0) self.assertTrue(result["before"]["selected"]) def test_zero_size_enabled_dates_follow_native_click_and_readback(self): for mode in ("zero_width", "zero_height", "zero_size"): with self.subTest(mode=mode): result = self.run_case(mode) self.assertTrue(result["before"]["candidateReady"]) self.assertEqual(result["clicks"], 1) self.assertTrue(result["after"]["selected"]) self.assertEqual(result["finalClicks"], 0) def test_selected_zero_size_pointer_blocked_date_is_not_reclicked(self): result = self.run_case("selected_zero_size") self.assertTrue(result["before"]["selected"]) self.assertFalse(result["before"]["candidateReady"]) self.assertEqual(result["clicks"], 0) self.assertEqual(result["finalClicks"], 0) def test_guarded_native_date_action_rejects_unsafe_controls(self): for mode in ("disabled", "negative", "unguarded", "wrong_service", "wrong_origin", "duplicate", "hidden", "zero_size_disabled", "zero_size_hidden", "zero_size_pointer_blocked"): with self.subTest(mode=mode): result = self.run_case(mode) self.assertEqual(result["clicks"], 0) self.assertEqual(result["finalClicks"], 0) if __name__ == "__main__": unittest.main()