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_calendar_book as book_calendar from plugins.ita_calendar_book import ( DATE_SELECTION_SCRIPT, SLOT_SELECTION_SCRIPT, TIME_SLOTS_PATH, CalendarBookError, book_date_preferences, recheck_calendar_before_final, ) from plugins.ita_calendar_query import AVAILABILITY_PATH, CalendarNextMonthUnavailableError from plugins.ita_plugin import ( BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL, ItaPlugin, ) from test.test_ita_calendar_book import FakePage, SERVICE, packet from test import test_ita_plugin as plugin_fixtures from test.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 clicked = bool(click and self.date_ack and not selected) raw = {"runtimeMatches": self.date_runtime_matches and service == self.service, "finalGuarded": True, "candidateCount": count, "candidateEnabled": self.date_enabled, "selectedMatches": 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["timelineDays"] = [self.selected_day] if self.selected_day else [] raw["contentDays"] = [self.content_day] if self.content_day else [] raw["firstSelectedMatches"] = day == self.selected_day == self.content_day raw["candidateCount"] = len(matching) raw["candidateReady"] = len(matching) == 1 and matching[0]["SlotLiberi"] == free raw.update(self.after_overrides if self.clicks else {}) return raw @contextmanager def browser_navigation(page): with patch.object(book_calendar, "click_next_month", side_effect=lambda _page: page.next_month()), \ patch.object(book_calendar.time, "sleep"): yield 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_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_valid_hint_is_rechecked_before_earlier_dates(self): page = FlowPage([month("2026-09", {9: 2}), month("2026-10", {12: 2, 13: 1})]) result = run_flow(page, preferred_day=date(2026, 10, 13)) self.assertEqual(result.candidate.day, date(2026, 10, 13)) self.assertEqual(page.refreshes, 1) self.assertEqual(page.date_clicks, ["2026-10-13"]) def test_missing_hint_restarts_once_and_uses_new_earlier_month_response(self): first = [month("2026-09", {9: 0}), month("2026-10", {13: 0})] second = [month("2026-09", {9: 1}), month("2026-10", {13: 0})] page = FlowPage(passes=[first, second]) result = run_flow(page, preferred_day=date(2026, 10, 13)) self.assertEqual(result.candidate.day, date(2026, 9, 9)) self.assertEqual(result.candidate.daily_calendar_id, "80000209") self.assertEqual(page.refreshes, 2) def test_hint_slot_race_does_not_repeat_same_day_on_fallback(self): page = FlowPage([month("2026-10", {13: 1, 14: 1}, slots={13: 0})]) result = run_flow(page, preferred_day=date(2026, 10, 13)) self.assertEqual(result.candidate.day, date(2026, 10, 14)) self.assertEqual(page.refreshes, 2) self.assertNotIn("2026-10-13", page.date_clicks) def test_hint_outside_preference_or_horizon_is_not_followed(self): for hint in (date(2027, 10, 13), date(2026, 9, 30)): with self.subTest(hint=hint): page = FlowPage() result = run_flow(page, preferred_day=hint, start_day=date(2026, 10, 1)) self.assertEqual(result.candidate.day, date(2026, 10, 13)) self.assertEqual(page.refreshes, 1) 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_fallback_anchor_change_is_rejected(self): page = FlowPage(passes=[[month("2026-10", {13: 0})], [month("2026-11", {13: 1})]]) with self.assertRaisesRegex(CalendarBookError, "anchor"): run_flow(page, preferred_day=date(2026, 10, 13)) self.assertEqual(page.clicks, 0) 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 = {"activeIdMatches": 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)}, {"preferred_day": "2026-10-13"}, {"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._transient_user_data_path = "/nonexistent/ita-book-flow-test" plugin._reset_calendar_book_state() route = plugin._resolve_route(AppointmentType(routing_key=routing_key)) plugin._record_calendar_book_prepared_route(route) 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_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 = plugin.book(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(plugin.last_booking_precommit.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_treats_query_date_as_hint_not_inventory(self): page = FlowPage([month("2026-10", {13: 0, 14: 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 = plugin.book(trigger, {"username": "applicant@example.test"}) self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL) self.assertEqual(plugin.last_booking_precommit.candidate.day, date(2026, 10, 14)) self.assertEqual(plugin.last_booking_precommit.candidate.time_label, "10:05 - 11:05") def test_query_preparation_cannot_be_converted_into_book_preparation(self): page = FlowPage() plugin, route, trigger = prepared_plugin(page) plugin._calendar_query_route_key = route.routing_key with self.assertRaises(BizLogicError): plugin._record_calendar_book_prepared_route(route) 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_book_state() with self.assertRaises(BizLogicError): plugin.book(trigger, {"username": "applicant@example.test"}) 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_plugin_instance_is_rejected(self): page = FlowPage() first, _, _ = prepared_plugin(page) second, _, trigger = prepared_plugin(page) second._calendar_book_prepared_context = first._calendar_book_prepared_context with self.assertRaises(BizLogicError): second.book(trigger, {"username": "applicant@example.test"}) def test_second_book_call_does_not_repeat_any_network_action(self): page = FlowPage() plugin, _, trigger = prepared_plugin(page) with browser_navigation(page): plugin.book(trigger, {"username": "applicant@example.test"}) with self.assertRaisesRegex(BizLogicError, "already attempted"): plugin.book(trigger, {"username": "applicant@example.test"}) self.assertEqual(page.refreshes, 1) self.assertEqual(page.clicks, 1) 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 = plugin.book(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(plugin.last_booking_precommit) 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._calendar_book_prepared_context) self.assertIsNone(plugin.last_booking_precommit) self.assertEqual(page.clicks, 0) 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.ChromiumOptions", side_effect=RuntimeError("offline stop")): with self.assertRaises(RuntimeError): plugin.create_session() else: plugin.cleanup() self.assertIsNone(plugin._calendar_book_prepared_context) self.assertIsNone(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._calendar_book_prepared_context) 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._calendar_book_prepared_context) 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.assertIsNone(plugin.last_booking_precommit) 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"]["selectedMatches"]) 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"]["selectedMatches"]) 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"]["candidateEnabled"]) self.assertEqual(result["clicks"], 1) self.assertTrue(result["after"]["selectedMatches"]) 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"]["selectedMatches"]) self.assertFalse(result["before"]["candidateEnabled"]) 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()