test_ita_compact.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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_runtime_service_id_rejects_missing_boolean_and_zero_values(self):
  64. for value in (None, True, False, 0, "0", ""):
  65. with self.subTest(value=value), self.assertRaises(ita.BizLogicError):
  66. ita._runtime_id(value)
  67. def test_query_stops_at_first_positive_month(self):
  68. empty = ()
  69. positive = (ita.CalendarDay(date(2026, 9, 2), 1, 0),)
  70. with patch.object(ita, "read_calendar_context", return_value=("4937", date(2026, 8, 1))), \
  71. patch.object(ita, "fetch_calendar_month", side_effect=[empty, positive]) as fetch:
  72. result = ita.scan_until_first_available_month(
  73. object(), lookahead_months=12, month_click_interval_seconds=0)
  74. self.assertEqual(result, (empty, positive))
  75. self.assertEqual(fetch.call_count, 2)
  76. def test_calendar_fetch_uses_existing_browser_fetch(self):
  77. response = Response(200, encoded([day()]),
  78. "https://prenotami.esteri.it/BookingCalendar/RetrieveCalendarAvailability")
  79. with patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  80. result = ita.fetch_calendar_month(object(), "4937", date(2026, 10, 1))
  81. self.assertEqual(len(ita.available_calendar_days(result)), 1)
  82. self.assertEqual(fetch.call_args.kwargs["json_data"], {
  83. "_Servizio": "4937", "selectedDay": "01/10/2026",
  84. })
  85. def test_calendar_status_mapping(self):
  86. cases = ((401, ita.CalendarAuthenticationExpiredError),
  87. (403, ita.CalendarAccessDeniedError),
  88. (429, ita.CalendarRateLimitedError),
  89. (504, ita.CalendarTransientError))
  90. for status, error in cases:
  91. with self.subTest(status=status), patch.object(
  92. ita, "perform_browser_fetch", return_value=Response(
  93. status, "", ita.AVAILABILITY_PATH)):
  94. with self.assertRaises(error):
  95. ita.fetch_calendar_month(object(), "4937", date(2026, 10, 1))
  96. def test_book_rechecks_applicant_inventory_and_selects_first_slot(self):
  97. day_value = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  98. candidate = ita.SlotCandidate(
  99. day_value.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  100. with patch.object(ita, "read_calendar_context", return_value=("4937", date(2026, 8, 1))), \
  101. patch.object(ita, "fetch_calendar_month", side_effect=[
  102. (), (), (day_value,)]), \
  103. patch.object(ita, "_move_to_month") as move, \
  104. patch.object(ita, "fetch_calendar_slots", return_value=(candidate,)), \
  105. patch.object(ita, "select_slot_before_final", return_value=candidate) as select:
  106. result = ita.recheck_calendar_before_final(
  107. object(), lookahead_months=12, start_day=date(2026, 8, 1),
  108. end_day=date(2026, 12, 31), session_is_current=lambda: True,
  109. month_click_interval_seconds=0)
  110. self.assertEqual(result, candidate)
  111. move.assert_called_once_with(unittest.mock.ANY, "4937", (2026, 10), 30)
  112. self.assertEqual(select.call_args.kwargs["target_day"], date(2026, 10, 2))
  113. def test_service_mismatch_fails_instead_of_timing_out(self):
  114. with patch.object(ita, "read_calendar_context",
  115. return_value=("9999", date(2026, 8, 1))):
  116. with self.assertRaisesRegex(ita.CalendarBookError, "service changed"):
  117. ita.wait_for_calendar_service(
  118. unittest.mock.ANY, session_is_current=lambda: True,
  119. expected_service=4937, timeout=0.1)
  120. class CompactPreflightTests(unittest.TestCase):
  121. @staticmethod
  122. def snapshot(**changes):
  123. value = {
  124. "formReady": True, "turnstileReady": True,
  125. "otpValuePresent": False, "otpSendEnabled": True,
  126. "avantiEnabled": True,
  127. }
  128. value.update(changes)
  129. return value
  130. def test_async_form_options_are_polled_before_turnstile_interaction(self):
  131. page = SimpleNamespace(run_js=Mock(side_effect=[
  132. self.snapshot(formReady=False, turnstileReady=False),
  133. self.snapshot(turnstileReady=False),
  134. self.snapshot(),
  135. ]))
  136. bypasser = Mock()
  137. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 1, 2]), \
  138. patch.object(ita.time, "sleep"), \
  139. patch.object(ita, "CloudflareBypasser", return_value=bypasser) as factory:
  140. result = ita.wait_for_booking_preflight(page, script="offline")
  141. self.assertTrue(result["formReady"])
  142. self.assertEqual(page.run_js.call_count, 3)
  143. factory.assert_called_once_with(page, log=False)
  144. bypasser.click_verification_button.assert_called_once_with(is_dfs=False)
  145. def test_never_ready_form_times_out_without_touching_turnstile(self):
  146. page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
  147. formReady=False, turnstileReady=False)))
  148. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
  149. patch.object(ita.time, "sleep"), \
  150. patch.object(ita, "CloudflareBypasser") as factory, \
  151. self.assertRaisesRegex(ita.CalendarGateError, "form_pending"):
  152. ita.wait_for_booking_preflight(page, script="offline")
  153. factory.assert_not_called()
  154. def test_otp_send_button_must_be_ready_before_preflight_returns(self):
  155. page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
  156. otpSendEnabled=False)))
  157. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
  158. patch.object(ita.time, "sleep"), \
  159. self.assertRaisesRegex(ita.CalendarGateError, "otp_send_disabled"):
  160. ita.wait_for_booking_preflight(page, script="offline")
  161. def test_after_otp_accepts_the_expected_send_button_cooldown(self):
  162. raw = self.snapshot(otpValuePresent=True, otpSendEnabled=False)
  163. ita.validate_booking_preflight(raw, after_otp=True)
  164. def test_preflight_failure_uses_framework_business_error(self):
  165. with self.assertRaisesRegex(ita.BizLogicError, "verification is not ready"):
  166. ita.validate_booking_preflight({
  167. "formReady": True,
  168. "turnstileReady": True,
  169. "otpValuePresent": False,
  170. "otpSendEnabled": False,
  171. "avantiEnabled": True,
  172. })
  173. class CompactFinalTests(unittest.TestCase):
  174. def setUp(self):
  175. self.route = ita.resolve_route_config({"route": route_config()}, "route")
  176. self.day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  177. self.slot = ita.SlotCandidate(
  178. self.day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  179. self.page = SimpleNamespace(
  180. tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
  181. self.plugin = SimpleNamespace(
  182. page=self.page,
  183. config=SimpleNamespace(account=VSAccount(username="applicant@example.com")),
  184. _require_calendar_context=Mock(return_value=SimpleNamespace(
  185. tab_id="tab", runtime_service="4937")),
  186. _reset_calendar_state=Mock(), _log=Mock(),
  187. )
  188. def test_final_submits_once_and_requires_explicit_success(self):
  189. response = Response(200, json.dumps({
  190. "errorMessage": "", "url": "/Reservation",
  191. }), "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
  192. with patch.object(ita, "verify_precommit_selection"), \
  193. patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  194. result = ita._submit_final_once(self.plugin, self.route, self.slot)
  195. self.assertTrue(result.success)
  196. self.assertEqual(fetch.call_count, 1)
  197. self.assertEqual(fetch.call_args.kwargs["data"]["idCalendarioGiornaliero"], "12345678")
  198. self.plugin._reset_calendar_state.assert_not_called()
  199. def test_ambiguous_final_response_is_retryable_failure(self):
  200. response = Response(200, "{}",
  201. "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
  202. with patch.object(ita, "verify_precommit_selection"), \
  203. patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  204. result = ita._submit_final_once(self.plugin, self.route, self.slot)
  205. self.assertFalse(result.success)
  206. self.assertEqual(fetch.call_count, 1)
  207. self.plugin._reset_calendar_state.assert_called_once()
  208. class CompactPluginTests(unittest.TestCase):
  209. def plugin(self, *, query_mode="calendar", final=False):
  210. plugin = object.__new__(ita.ItaPlugin)
  211. plugin.config = VSPlgConfig(
  212. account=VSAccount(username="applicant@example.com", password="secret"),
  213. free_config={
  214. "query_mode": query_mode, "otp_mode": "cloud",
  215. "final_submit_enabled": final,
  216. "apt_configs": {"route": route_config()},
  217. },
  218. )
  219. plugin.free_config = plugin.config.free_config
  220. plugin.group_id = "ita.compact"
  221. plugin.page = SimpleNamespace(
  222. tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
  223. plugin.is_healthy = True
  224. plugin._prepared_calendar = object()
  225. plugin.logger = None
  226. return plugin
  227. def test_query_publishes_only_real_calendar_availability(self):
  228. plugin, apt = self.plugin(), AppointmentType(routing_key="route")
  229. positive = (ita.CalendarDay(date(2026, 10, 2), 1, 0),)
  230. with patch.object(plugin, "health_check", return_value=True), \
  231. patch.object(plugin, "_require_calendar_context"), \
  232. patch.object(ita, "scan_until_first_available_month", return_value=(positive,)):
  233. result = plugin.query(apt)
  234. self.assertTrue(result.success)
  235. self.assertEqual(result.availability_status, AvailabilityStatus.Available)
  236. self.assertEqual(result.earliest_date.date(), date(2026, 10, 2))
  237. def test_book_rejects_pool_account_signal_as_applicant_identity(self):
  238. plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
  239. signal = VSQueryResult(success=True, apt_type=apt,
  240. availability_status=AvailabilityStatus.Available)
  241. with self.assertRaisesRegex(Exception, "applicant account"):
  242. plugin.book(signal, {"username": "pool@example.com"})
  243. def test_prefinal_book_does_not_submit(self):
  244. plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
  245. signal = VSQueryResult(success=True, apt_type=apt,
  246. availability_status=AvailabilityStatus.Available)
  247. selected_day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  248. slot = ita.SlotCandidate(
  249. selected_day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  250. with patch.object(ita, "book_date_preferences", return_value=(date.min, date.max)), \
  251. patch.object(plugin, "_calendar_context_matches", return_value=True), \
  252. patch.object(ita, "recheck_calendar_before_final", return_value=slot), \
  253. patch.object(ita, "_submit_final_once") as submit:
  254. result = plugin.book(signal, {"username": "applicant@example.com"})
  255. self.assertFalse(result.success)
  256. self.assertEqual(result.label, ita.BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  257. submit.assert_not_called()
  258. if __name__ == "__main__":
  259. unittest.main()