test_ita_compact.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import json
  2. import unittest
  3. from datetime import date, datetime, time
  4. from types import SimpleNamespace
  5. from unittest.mock import Mock, patch
  6. from plugins import ita_plugin as ita
  7. from vs_types import (
  8. AppointmentType, AvailabilityStatus, VSAccount, VSPlgConfig, VSQueryResult,
  9. )
  10. def encoded(records):
  11. return json.dumps(json.dumps(records))
  12. def day(value="01/10/2026 00:00:00", free=1, remaining=0):
  13. return {"DateLibere": value, "SlotLiberi": free, "SlotRimanenti": remaining}
  14. def slot(value="01/10/2026 00:00:00", free=1, remaining=0, daily_id=12345678):
  15. clock = lambda hour, minute: {
  16. "Hours": hour, "Minutes": minute, "Seconds": 0, "Milliseconds": 0,
  17. }
  18. return {
  19. "Data": value, "SlotLiberi": free, "SlotRimanenti": remaining,
  20. "IDCalendarioServizioGiornaliero": daily_id,
  21. "OrarioInizioFascia": clock(10, 5),
  22. "OrarioFineFascia": clock(11, 5),
  23. }
  24. def route_config(service=4937):
  25. return {
  26. "capability": "single_schengen_tourism",
  27. "service_id": service,
  28. "calendar_scan": {"lookahead_months": 12},
  29. "form": {
  30. "booking_type_control_id": "typeofbookingddl",
  31. "booking_type_value": "1",
  32. "booking_type_labels": ["Single booking"],
  33. "purpose_control_id": "ddls_0",
  34. "purpose_value": "42",
  35. "purpose_labels": ["Tourism"],
  36. },
  37. "mail": {"authorization_source": "account"},
  38. }
  39. class Response:
  40. def __init__(self, status, text="", url=""):
  41. self.status_code, self.text, self.url = status, text, url
  42. def json(self):
  43. try:
  44. return json.loads(self.text)
  45. except Exception:
  46. return {}
  47. class CompactProtocolTests(unittest.TestCase):
  48. def test_route_is_configuration_driven(self):
  49. routes = {"slot.hkg.it.tourist": route_config(4937),
  50. "slot.syd.it.tourist": route_config(8123)}
  51. self.assertEqual(ita.resolve_route_config(routes, "slot.hkg.it.tourist").service_id, 4937)
  52. self.assertEqual(ita.resolve_route_config(routes, "slot.syd.it.tourist").service_id, 8123)
  53. def test_inventory_and_last_slot_semantics(self):
  54. days = ita.parse_calendar_availability(encoded([day()]))
  55. slots = ita.parse_time_slots(encoded([slot()]))
  56. self.assertTrue(days[0].is_available)
  57. self.assertTrue(slots[0].is_available)
  58. self.assertEqual(slots[0].time_label, "10:05 - 11:05")
  59. def test_zero_inventory_is_unavailable(self):
  60. self.assertFalse(ita.parse_calendar_availability(
  61. encoded([day(free=0, remaining=-1)]))[0].is_available)
  62. class CompactCalendarTests(unittest.TestCase):
  63. def test_query_stops_at_first_positive_month(self):
  64. empty = ()
  65. positive = (ita.CalendarDay(date(2026, 9, 2), 1, 0),)
  66. with patch.object(ita, "read_calendar_context", return_value=("4937", date(2026, 8, 1))), \
  67. patch.object(ita, "fetch_calendar_month", side_effect=[empty, positive]) as fetch:
  68. result = ita.scan_until_first_available_month(
  69. object(), lookahead_months=12, month_click_interval_seconds=0)
  70. self.assertEqual(result, (empty, positive))
  71. self.assertEqual(fetch.call_count, 2)
  72. def test_calendar_fetch_uses_existing_browser_fetch(self):
  73. response = Response(200, encoded([day()]),
  74. "https://prenotami.esteri.it/BookingCalendar/RetrieveCalendarAvailability")
  75. with patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  76. result = ita.fetch_calendar_month(object(), "4937", date(2026, 10, 1))
  77. self.assertEqual(len(ita.available_calendar_days(result)), 1)
  78. self.assertEqual(fetch.call_args.kwargs["json_data"], {
  79. "_Servizio": "4937", "selectedDay": "01/10/2026",
  80. })
  81. def test_calendar_status_mapping(self):
  82. cases = ((401, ita.CalendarAuthenticationExpiredError),
  83. (403, ita.CalendarAccessDeniedError),
  84. (429, ita.CalendarRateLimitedError),
  85. (504, ita.CalendarTransientError))
  86. for status, error in cases:
  87. with self.subTest(status=status), patch.object(
  88. ita, "perform_browser_fetch", return_value=Response(
  89. status, "", ita.AVAILABILITY_PATH)):
  90. with self.assertRaises(error):
  91. ita.fetch_calendar_month(object(), "4937", date(2026, 10, 1))
  92. def test_book_rechecks_applicant_inventory_and_selects_first_slot(self):
  93. day_value = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  94. candidate = ita.SlotCandidate(
  95. day_value.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  96. with patch.object(ita, "read_calendar_context", return_value=("4937", date(2026, 8, 1))), \
  97. patch.object(ita, "fetch_calendar_month", side_effect=[
  98. (), (), (day_value,)]), \
  99. patch.object(ita, "_move_to_month") as move, \
  100. patch.object(ita, "fetch_calendar_slots", return_value=(candidate,)), \
  101. patch.object(ita, "select_slot_before_final", return_value=candidate) as select:
  102. result = ita.recheck_calendar_before_final(
  103. object(), lookahead_months=12, start_day=date(2026, 8, 1),
  104. end_day=date(2026, 12, 31), session_is_current=lambda: True,
  105. month_click_interval_seconds=0)
  106. self.assertEqual(result, candidate)
  107. move.assert_called_once_with(unittest.mock.ANY, "4937", (2026, 10), 30)
  108. self.assertEqual(select.call_args.kwargs["target_day"], date(2026, 10, 2))
  109. def test_service_mismatch_fails_instead_of_timing_out(self):
  110. with patch.object(ita, "read_calendar_service", return_value="9999"):
  111. with self.assertRaisesRegex(ita.CalendarBookError, "service changed"):
  112. ita.wait_for_calendar_service(
  113. object(), session_is_current=lambda: True,
  114. expected_service=4937, timeout=0.1)
  115. class CompactPreflightTests(unittest.TestCase):
  116. @staticmethod
  117. def snapshot(**changes):
  118. value = {
  119. "formReady": True, "turnstileReady": True,
  120. "otpValuePresent": False, "otpSendEnabled": True,
  121. "avantiEnabled": True,
  122. }
  123. value.update(changes)
  124. return value
  125. def test_async_form_options_are_polled_before_turnstile_interaction(self):
  126. page = SimpleNamespace(run_js=Mock(side_effect=[
  127. self.snapshot(formReady=False, turnstileReady=False),
  128. self.snapshot(turnstileReady=False),
  129. self.snapshot(),
  130. ]))
  131. bypasser = Mock()
  132. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 1, 2]), \
  133. patch.object(ita.time, "sleep"), \
  134. patch.object(ita, "CloudflareBypasser", return_value=bypasser) as factory:
  135. result = ita.wait_for_booking_preflight(page, script="offline")
  136. self.assertTrue(result["formReady"])
  137. self.assertEqual(page.run_js.call_count, 3)
  138. factory.assert_called_once_with(page, log=False)
  139. bypasser.click_verification_button.assert_called_once_with(is_dfs=False)
  140. def test_never_ready_form_times_out_without_touching_turnstile(self):
  141. page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
  142. formReady=False, turnstileReady=False)))
  143. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
  144. patch.object(ita.time, "sleep"), \
  145. patch.object(ita, "CloudflareBypasser") as factory, \
  146. self.assertRaisesRegex(ita.CalendarGateError, "form_pending"):
  147. ita.wait_for_booking_preflight(page, script="offline")
  148. factory.assert_not_called()
  149. def test_otp_send_button_must_be_ready_before_preflight_returns(self):
  150. page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
  151. otpSendEnabled=False)))
  152. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
  153. patch.object(ita.time, "sleep"), \
  154. self.assertRaisesRegex(ita.CalendarGateError, "otp_send_disabled"):
  155. ita.wait_for_booking_preflight(page, script="offline")
  156. def test_after_otp_accepts_the_expected_send_button_cooldown(self):
  157. raw = self.snapshot(otpValuePresent=True, otpSendEnabled=False)
  158. ita.validate_booking_preflight(raw, after_otp=True)
  159. def test_query_failure_keeps_the_safe_calendar_reason(self):
  160. plugin = object.__new__(ita.ItaPlugin)
  161. plugin._prepared_calendar = object()
  162. error = plugin._calendar_failure(
  163. ita.CalendarGateError("Italy booking verification timed out: form_pending"),
  164. "Query")
  165. self.assertIn("form_pending", str(error))
  166. class CompactFinalTests(unittest.TestCase):
  167. def setUp(self):
  168. self.route = ita.resolve_route_config({"route": route_config()}, "route")
  169. self.day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  170. self.slot = ita.SlotCandidate(
  171. self.day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  172. self.page = SimpleNamespace(
  173. tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
  174. self.plugin = SimpleNamespace(
  175. page=self.page,
  176. config=SimpleNamespace(account=VSAccount(username="applicant@example.com")),
  177. _require_calendar_context=Mock(return_value=SimpleNamespace(
  178. tab_id="tab", runtime_service="4937")),
  179. _reset_calendar_state=Mock(), _log=Mock(),
  180. )
  181. def test_final_submits_once_and_requires_explicit_success(self):
  182. response = Response(200, json.dumps({
  183. "errorMessage": "", "url": "/Reservation",
  184. }), "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
  185. with patch.object(ita, "verify_precommit_selection"), \
  186. patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  187. result = ita._submit_final_once(self.plugin, self.route, self.slot)
  188. self.assertTrue(result.success)
  189. self.assertEqual(fetch.call_count, 1)
  190. self.assertEqual(fetch.call_args.kwargs["data"]["idCalendarioGiornaliero"], "12345678")
  191. self.plugin._reset_calendar_state.assert_not_called()
  192. def test_ambiguous_final_response_is_retryable_failure(self):
  193. response = Response(200, "{}",
  194. "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
  195. with patch.object(ita, "verify_precommit_selection"), \
  196. patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  197. result = ita._submit_final_once(self.plugin, self.route, self.slot)
  198. self.assertFalse(result.success)
  199. self.assertEqual(fetch.call_count, 1)
  200. self.plugin._reset_calendar_state.assert_called_once()
  201. class CompactPluginTests(unittest.TestCase):
  202. def plugin(self, *, query_mode="calendar", final=False):
  203. plugin = object.__new__(ita.ItaPlugin)
  204. plugin.config = VSPlgConfig(
  205. account=VSAccount(username="applicant@example.com", password="secret"),
  206. free_config={
  207. "query_mode": query_mode, "otp_mode": "cloud",
  208. "final_submit_enabled": final,
  209. "apt_configs": {"route": route_config()},
  210. },
  211. )
  212. plugin.free_config = plugin.config.free_config
  213. plugin.group_id = "ita.compact"
  214. plugin.page = SimpleNamespace(
  215. tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
  216. plugin.is_healthy = True
  217. plugin._prepared_calendar = object()
  218. plugin.logger = None
  219. return plugin
  220. def test_query_publishes_only_real_calendar_availability(self):
  221. plugin, apt = self.plugin(), AppointmentType(routing_key="route")
  222. positive = (ita.CalendarDay(date(2026, 10, 2), 1, 0),)
  223. with patch.object(plugin, "health_check", return_value=True), \
  224. patch.object(plugin, "_require_calendar_context"), \
  225. patch.object(ita, "scan_until_first_available_month", return_value=(positive,)):
  226. result = plugin.query(apt)
  227. self.assertTrue(result.success)
  228. self.assertEqual(result.availability_status, AvailabilityStatus.Available)
  229. self.assertEqual(result.earliest_date.date(), date(2026, 10, 2))
  230. def test_book_rejects_pool_account_signal_as_applicant_identity(self):
  231. plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
  232. signal = VSQueryResult(success=True, apt_type=apt,
  233. availability_status=AvailabilityStatus.Available)
  234. with self.assertRaisesRegex(Exception, "applicant account"):
  235. plugin.book(signal, {"username": "pool@example.com"})
  236. def test_prefinal_book_does_not_submit(self):
  237. plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
  238. signal = VSQueryResult(success=True, apt_type=apt,
  239. availability_status=AvailabilityStatus.Available)
  240. selected_day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  241. slot = ita.SlotCandidate(
  242. selected_day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  243. with patch.object(ita, "book_date_preferences", return_value=(date.min, date.max)), \
  244. patch.object(plugin, "_calendar_context_matches", return_value=True), \
  245. patch.object(ita, "recheck_calendar_before_final", return_value=slot), \
  246. patch.object(ita, "_submit_final_once") as submit:
  247. result = plugin.book(signal, {"username": "applicant@example.com"})
  248. self.assertFalse(result.success)
  249. self.assertEqual(result.label, ita.BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  250. submit.assert_not_called()
  251. if __name__ == "__main__":
  252. unittest.main()