| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292 |
- import json
- import unittest
- from datetime import date, datetime, time
- from types import SimpleNamespace
- from unittest.mock import Mock, patch
- from plugins import ita_plugin as ita
- from vs_types import (
- AppointmentType, AvailabilityStatus, VSAccount, VSPlgConfig, VSQueryResult,
- )
- def encoded(records):
- return json.dumps(json.dumps(records))
- def day(value="01/10/2026 00:00:00", free=1, remaining=0):
- return {"DateLibere": value, "SlotLiberi": free, "SlotRimanenti": remaining}
- def slot(value="01/10/2026 00:00:00", free=1, remaining=0, daily_id=12345678):
- clock = lambda hour, minute: {
- "Hours": hour, "Minutes": minute, "Seconds": 0, "Milliseconds": 0,
- }
- return {
- "Data": value, "SlotLiberi": free, "SlotRimanenti": remaining,
- "IDCalendarioServizioGiornaliero": daily_id,
- "OrarioInizioFascia": clock(10, 5),
- "OrarioFineFascia": clock(11, 5),
- }
- def route_config(service=4937):
- return {
- "capability": "single_schengen_tourism",
- "service_id": service,
- "calendar_scan": {"lookahead_months": 12},
- "form": {
- "booking_type_control_id": "typeofbookingddl",
- "booking_type_value": "1",
- "booking_type_labels": ["Single booking"],
- "purpose_control_id": "ddls_0",
- "purpose_value": "42",
- "purpose_labels": ["Tourism"],
- },
- "mail": {"authorization_source": "account"},
- }
- class Response:
- def __init__(self, status, text="", url=""):
- self.status_code, self.text, self.url = status, text, url
- def json(self):
- try:
- return json.loads(self.text)
- except Exception:
- return {}
- class CompactProtocolTests(unittest.TestCase):
- def test_route_is_configuration_driven(self):
- routes = {"slot.hkg.it.tourist": route_config(4937),
- "slot.syd.it.tourist": route_config(8123)}
- self.assertEqual(ita.resolve_route_config(routes, "slot.hkg.it.tourist").service_id, 4937)
- self.assertEqual(ita.resolve_route_config(routes, "slot.syd.it.tourist").service_id, 8123)
- def test_inventory_and_last_slot_semantics(self):
- days = ita.parse_calendar_availability(encoded([day()]))
- slots = ita.parse_time_slots(encoded([slot()]))
- self.assertTrue(days[0].is_available)
- self.assertTrue(slots[0].is_available)
- self.assertEqual(slots[0].time_label, "10:05 - 11:05")
- def test_zero_inventory_is_unavailable(self):
- self.assertFalse(ita.parse_calendar_availability(
- encoded([day(free=0, remaining=-1)]))[0].is_available)
- class CompactCalendarTests(unittest.TestCase):
- def test_query_stops_at_first_positive_month(self):
- empty = ()
- positive = (ita.CalendarDay(date(2026, 9, 2), 1, 0),)
- with patch.object(ita, "read_calendar_context", return_value=("4937", date(2026, 8, 1))), \
- patch.object(ita, "fetch_calendar_month", side_effect=[empty, positive]) as fetch:
- result = ita.scan_until_first_available_month(
- object(), lookahead_months=12, month_click_interval_seconds=0)
- self.assertEqual(result, (empty, positive))
- self.assertEqual(fetch.call_count, 2)
- def test_calendar_fetch_uses_existing_browser_fetch(self):
- response = Response(200, encoded([day()]),
- "https://prenotami.esteri.it/BookingCalendar/RetrieveCalendarAvailability")
- with patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
- result = ita.fetch_calendar_month(object(), "4937", date(2026, 10, 1))
- self.assertEqual(len(ita.available_calendar_days(result)), 1)
- self.assertEqual(fetch.call_args.kwargs["json_data"], {
- "_Servizio": "4937", "selectedDay": "01/10/2026",
- })
- def test_calendar_status_mapping(self):
- cases = ((401, ita.CalendarAuthenticationExpiredError),
- (403, ita.CalendarAccessDeniedError),
- (429, ita.CalendarRateLimitedError),
- (504, ita.CalendarTransientError))
- for status, error in cases:
- with self.subTest(status=status), patch.object(
- ita, "perform_browser_fetch", return_value=Response(
- status, "", ita.AVAILABILITY_PATH)):
- with self.assertRaises(error):
- ita.fetch_calendar_month(object(), "4937", date(2026, 10, 1))
- def test_book_rechecks_applicant_inventory_and_selects_first_slot(self):
- day_value = ita.CalendarDay(date(2026, 10, 2), 1, 0)
- candidate = ita.SlotCandidate(
- day_value.day, 1, 0, time(10, 5), time(11, 5), "12345678")
- with patch.object(ita, "read_calendar_context", return_value=("4937", date(2026, 8, 1))), \
- patch.object(ita, "fetch_calendar_month", side_effect=[
- (), (), (day_value,)]), \
- patch.object(ita, "_move_to_month") as move, \
- patch.object(ita, "fetch_calendar_slots", return_value=(candidate,)), \
- patch.object(ita, "select_slot_before_final", return_value=candidate) as select:
- result = ita.recheck_calendar_before_final(
- object(), lookahead_months=12, start_day=date(2026, 8, 1),
- end_day=date(2026, 12, 31), session_is_current=lambda: True,
- month_click_interval_seconds=0)
- self.assertEqual(result, candidate)
- move.assert_called_once_with(unittest.mock.ANY, "4937", (2026, 10), 30)
- self.assertEqual(select.call_args.kwargs["target_day"], date(2026, 10, 2))
- def test_service_mismatch_fails_instead_of_timing_out(self):
- with patch.object(ita, "read_calendar_service", return_value="9999"):
- with self.assertRaisesRegex(ita.CalendarBookError, "service changed"):
- ita.wait_for_calendar_service(
- object(), session_is_current=lambda: True,
- expected_service=4937, timeout=0.1)
- class CompactPreflightTests(unittest.TestCase):
- @staticmethod
- def snapshot(**changes):
- value = {
- "formReady": True, "turnstileReady": True,
- "otpValuePresent": False, "otpSendEnabled": True,
- "avantiEnabled": True,
- }
- value.update(changes)
- return value
- def test_async_form_options_are_polled_before_turnstile_interaction(self):
- page = SimpleNamespace(run_js=Mock(side_effect=[
- self.snapshot(formReady=False, turnstileReady=False),
- self.snapshot(turnstileReady=False),
- self.snapshot(),
- ]))
- bypasser = Mock()
- with patch.object(ita.time, "monotonic", side_effect=[0, 0, 1, 2]), \
- patch.object(ita.time, "sleep"), \
- patch.object(ita, "CloudflareBypasser", return_value=bypasser) as factory:
- result = ita.wait_for_booking_preflight(page, script="offline")
- self.assertTrue(result["formReady"])
- self.assertEqual(page.run_js.call_count, 3)
- factory.assert_called_once_with(page, log=False)
- bypasser.click_verification_button.assert_called_once_with(is_dfs=False)
- def test_never_ready_form_times_out_without_touching_turnstile(self):
- page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
- formReady=False, turnstileReady=False)))
- with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
- patch.object(ita.time, "sleep"), \
- patch.object(ita, "CloudflareBypasser") as factory, \
- self.assertRaisesRegex(ita.CalendarGateError, "form_pending"):
- ita.wait_for_booking_preflight(page, script="offline")
- factory.assert_not_called()
- def test_otp_send_button_must_be_ready_before_preflight_returns(self):
- page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
- otpSendEnabled=False)))
- with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
- patch.object(ita.time, "sleep"), \
- self.assertRaisesRegex(ita.CalendarGateError, "otp_send_disabled"):
- ita.wait_for_booking_preflight(page, script="offline")
- def test_after_otp_accepts_the_expected_send_button_cooldown(self):
- raw = self.snapshot(otpValuePresent=True, otpSendEnabled=False)
- ita.validate_booking_preflight(raw, after_otp=True)
- def test_query_failure_keeps_the_safe_calendar_reason(self):
- plugin = object.__new__(ita.ItaPlugin)
- plugin._prepared_calendar = object()
- error = plugin._calendar_failure(
- ita.CalendarGateError("Italy booking verification timed out: form_pending"),
- "Query")
- self.assertIn("form_pending", str(error))
- class CompactFinalTests(unittest.TestCase):
- def setUp(self):
- self.route = ita.resolve_route_config({"route": route_config()}, "route")
- self.day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
- self.slot = ita.SlotCandidate(
- self.day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
- self.page = SimpleNamespace(
- tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
- self.plugin = SimpleNamespace(
- page=self.page,
- config=SimpleNamespace(account=VSAccount(username="applicant@example.com")),
- _require_calendar_context=Mock(return_value=SimpleNamespace(
- tab_id="tab", runtime_service="4937")),
- _reset_calendar_state=Mock(), _log=Mock(),
- )
- def test_final_submits_once_and_requires_explicit_success(self):
- response = Response(200, json.dumps({
- "errorMessage": "", "url": "/Reservation",
- }), "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
- with patch.object(ita, "verify_precommit_selection"), \
- patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
- result = ita._submit_final_once(self.plugin, self.route, self.slot)
- self.assertTrue(result.success)
- self.assertEqual(fetch.call_count, 1)
- self.assertEqual(fetch.call_args.kwargs["data"]["idCalendarioGiornaliero"], "12345678")
- self.plugin._reset_calendar_state.assert_not_called()
- def test_ambiguous_final_response_is_retryable_failure(self):
- response = Response(200, "{}",
- "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
- with patch.object(ita, "verify_precommit_selection"), \
- patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
- result = ita._submit_final_once(self.plugin, self.route, self.slot)
- self.assertFalse(result.success)
- self.assertEqual(fetch.call_count, 1)
- self.plugin._reset_calendar_state.assert_called_once()
- class CompactPluginTests(unittest.TestCase):
- def plugin(self, *, query_mode="calendar", final=False):
- plugin = object.__new__(ita.ItaPlugin)
- plugin.config = VSPlgConfig(
- account=VSAccount(username="applicant@example.com", password="secret"),
- free_config={
- "query_mode": query_mode, "otp_mode": "cloud",
- "final_submit_enabled": final,
- "apt_configs": {"route": route_config()},
- },
- )
- plugin.free_config = plugin.config.free_config
- plugin.group_id = "ita.compact"
- plugin.page = SimpleNamespace(
- tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
- plugin.is_healthy = True
- plugin._prepared_calendar = object()
- plugin.logger = None
- return plugin
- def test_query_publishes_only_real_calendar_availability(self):
- plugin, apt = self.plugin(), AppointmentType(routing_key="route")
- positive = (ita.CalendarDay(date(2026, 10, 2), 1, 0),)
- with patch.object(plugin, "health_check", return_value=True), \
- patch.object(plugin, "_require_calendar_context"), \
- patch.object(ita, "scan_until_first_available_month", return_value=(positive,)):
- result = plugin.query(apt)
- self.assertTrue(result.success)
- self.assertEqual(result.availability_status, AvailabilityStatus.Available)
- self.assertEqual(result.earliest_date.date(), date(2026, 10, 2))
- def test_book_rejects_pool_account_signal_as_applicant_identity(self):
- plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
- signal = VSQueryResult(success=True, apt_type=apt,
- availability_status=AvailabilityStatus.Available)
- with self.assertRaisesRegex(Exception, "applicant account"):
- plugin.book(signal, {"username": "pool@example.com"})
- def test_prefinal_book_does_not_submit(self):
- plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
- signal = VSQueryResult(success=True, apt_type=apt,
- availability_status=AvailabilityStatus.Available)
- selected_day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
- slot = ita.SlotCandidate(
- selected_day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
- with patch.object(ita, "book_date_preferences", return_value=(date.min, date.max)), \
- patch.object(plugin, "_calendar_context_matches", return_value=True), \
- patch.object(ita, "recheck_calendar_before_final", return_value=slot), \
- patch.object(ita, "_submit_final_once") as submit:
- result = plugin.book(signal, {"username": "applicant@example.com"})
- self.assertFalse(result.success)
- self.assertEqual(result.label, ita.BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
- submit.assert_not_called()
- if __name__ == "__main__":
- unittest.main()
|