| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417 |
- 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_runtime_service_id_rejects_missing_boolean_and_zero_values(self):
- for value in (None, True, False, 0, "0", ""):
- with self.subTest(value=value), self.assertRaises(ita.BizLogicError):
- ita._runtime_id(value)
- 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.SessionExpiredOrInvalidError),
- (403, ita.PermissionDeniedError),
- (404, ita.NotFoundError),
- (429, ita.RateLimiteddError),
- (504, ita.BizLogicError))
- 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_context",
- return_value=("9999", date(2026, 8, 1))):
- with self.assertRaisesRegex(ita.BizLogicError, "service changed"):
- ita.wait_for_calendar_service(
- unittest.mock.ANY, 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.BizLogicError, "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.BizLogicError, "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_preflight_failure_uses_framework_business_error(self):
- with self.assertRaisesRegex(ita.BizLogicError, "verification is not ready"):
- ita.validate_booking_preflight({
- "formReady": True,
- "turnstileReady": True,
- "otpValuePresent": False,
- "otpSendEnabled": False,
- "avantiEnabled": True,
- })
- 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_raises_framework_business_error(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:
- with self.assertRaises(ita.BizLogicError):
- ita._submit_final_once(self.plugin, self.route, self.slot)
- self.assertEqual(fetch.call_count, 1)
- self.plugin._reset_calendar_state.assert_called_once()
- class CalendarSelectionRegressionTests(unittest.TestCase):
- def setUp(self):
- self.day = date(2026, 10, 1)
- self.candidate = ita.parse_time_slots(encoded([slot()]))[0]
- self.days = ita.parse_calendar_availability(encoded([day()]))
- self.selected, self.pending, self.clicks = False, 0, []
- self.page = SimpleNamespace(url="https://prenotami.esteri.it/BookingCalendar",
- run_js=Mock(side_effect=self.dom))
- self.now = 0
- self.enterContext(patch.object(ita.time, "monotonic", side_effect=lambda: self.now))
- self.enterContext(patch.object(ita.time, "sleep", side_effect=self.advance))
- self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch",
- side_effect=AssertionError("Selection must not send business requests")))
- def advance(self, seconds):
- self.now += seconds
- def dom(self, script, mode, service, selected_day, daily_id, label, capacity, click):
- self.assertEqual(script, ita.CALENDAR_DOM_SCRIPT)
- self.assertEqual((service, selected_day), ("4937", self.day.isoformat()))
- count = 1
- if mode == "slot":
- self.assertEqual((daily_id, label, capacity),
- (self.candidate.daily_calendar_id, self.candidate.time_label, 1))
- if self.pending:
- self.pending -= 1
- count = 0
- if click:
- self.assertEqual(count, 1)
- self.clicks.append(mode)
- self.selected = True
- return {"contextReady": True, "candidateCount": count,
- "candidateReady": count == 1, "selected": mode == "date" or self.selected,
- "clicked": click and mode == "slot"}
- def select(self, **kwargs):
- return ita.select_slot_before_final(self.page, target_day=self.day, days=self.days,
- slots=(self.candidate,), runtime_service="4937", dom_timeout=0.3, **kwargs)
- def test_async_slots_are_waited_for_without_requery_or_extra_click(self):
- self.pending = 2
- self.assertEqual(self.select(), self.candidate)
- self.assertEqual(self.clicks, ["slot"])
- self.assertAlmostEqual(self.now, 0.2)
- self.fetch.assert_not_called()
- def test_missing_slots_timeout_without_click_or_submission(self):
- self.pending = 100
- with self.assertRaisesRegex(ita.BizLogicError, "did not finish loading"):
- self.select()
- self.assertEqual(self.clicks, [])
- self.assertLessEqual(self.now, 0.4)
- self.fetch.assert_not_called()
- def test_changed_session_stops_before_the_first_date_action(self):
- with self.assertRaises(ita.SessionExpiredOrInvalidError):
- self.select(session_is_current=lambda: False)
- self.page.run_js.assert_not_called()
- def test_duplicate_slots_are_rejected_immediately(self):
- self.page.run_js.side_effect = None
- self.page.run_js.return_value = {"contextReady": True, "candidateCount": 2,
- "candidateReady": True, "selected": True, "clicked": False}
- with self.assertRaises(ita.BizLogicError):
- self.select()
- self.assertEqual(self.now, 0)
- def test_readback_requires_real_boolean_and_integer_facts(self):
- raw = {"contextReady": True, "candidateCount": 1, "candidateReady": True,
- "selected": True, "clicked": False}
- self.page.run_js.side_effect = None
- for field, value in (("candidateCount", True), ("candidateCount", 1.0),
- ("contextReady", 1), ("candidateReady", "true"),
- ("selected", 1), ("clicked", 0)):
- with self.subTest(field=field, value=value):
- self.page.run_js.return_value = {**raw, field: value}
- with self.assertRaises(ita.BizLogicError):
- ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=self.candidate)
- def test_readback_never_accepts_missing_or_negative_candidate(self):
- self.selected = True
- self.pending = 1
- with self.assertRaises(ita.BizLogicError):
- ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=self.candidate)
- negative = ita.parse_time_slots(encoded([slot(free=0, remaining=-1)]))[0]
- self.page.run_js.side_effect = None
- self.page.run_js.return_value = {"contextReady": True, "candidateCount": 1,
- "candidateReady": True, "selected": True, "clicked": False}
- with self.assertRaises(ita.BizLogicError):
- ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=negative)
- 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.instance_id = "compact-test"
- plugin.session_create_time = 0
- plugin._prepared_calendar = object()
- plugin.logger = None
- return plugin
- def test_bad_query_mode_is_not_misreported_as_an_expired_session(self):
- plugin = self.plugin(query_mode="services_probe")
- with patch.object(plugin, "health_check") as health, \
- self.assertRaisesRegex(ita.BizLogicError, "query_mode=calendar"):
- plugin.query(AppointmentType(routing_key="route"))
- health.assert_not_called()
- def test_status_reports_elapsed_session_age(self):
- plugin = self.plugin()
- plugin.session_create_time = 100
- with patch.object(ita.time, "time", return_value=145.8):
- self.assertEqual(plugin.get_plugin_status().session_age_sec, 45)
- plugin.session_create_time = 0
- self.assertEqual(plugin.get_plugin_status().session_age_sec, 0)
- def test_disconnected_browser_does_not_break_status_reporting(self):
- plugin = self.plugin()
- page = Mock()
- type(page).url = unittest.mock.PropertyMock(side_effect=RuntimeError("disconnected"))
- plugin.page = page
- self.assertEqual(plugin.get_plugin_status().current_url, "")
- 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()
|