test_ita_compact.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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.SessionExpiredOrInvalidError),
  87. (403, ita.PermissionDeniedError),
  88. (404, ita.NotFoundError),
  89. (429, ita.RateLimiteddError),
  90. (504, ita.BizLogicError))
  91. for status, error in cases:
  92. with self.subTest(status=status), patch.object(
  93. ita, "perform_browser_fetch", return_value=Response(
  94. status, "", ita.AVAILABILITY_PATH)):
  95. with self.assertRaises(error):
  96. ita.fetch_calendar_month(object(), "4937", date(2026, 10, 1))
  97. def test_book_rechecks_applicant_inventory_and_selects_first_slot(self):
  98. day_value = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  99. candidate = ita.SlotCandidate(
  100. day_value.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  101. with patch.object(ita, "read_calendar_context", return_value=("4937", date(2026, 8, 1))), \
  102. patch.object(ita, "fetch_calendar_month", side_effect=[
  103. (), (), (day_value,)]), \
  104. patch.object(ita, "_move_to_month") as move, \
  105. patch.object(ita, "fetch_calendar_slots", return_value=(candidate,)), \
  106. patch.object(ita, "select_slot_before_final", return_value=candidate) as select:
  107. result = ita.recheck_calendar_before_final(
  108. object(), lookahead_months=12, start_day=date(2026, 8, 1),
  109. end_day=date(2026, 12, 31), session_is_current=lambda: True,
  110. month_click_interval_seconds=0)
  111. self.assertEqual(result, candidate)
  112. move.assert_called_once_with(unittest.mock.ANY, "4937", (2026, 10), 30)
  113. self.assertEqual(select.call_args.kwargs["target_day"], date(2026, 10, 2))
  114. def test_service_mismatch_fails_instead_of_timing_out(self):
  115. with patch.object(ita, "read_calendar_context",
  116. return_value=("9999", date(2026, 8, 1))):
  117. with self.assertRaisesRegex(ita.BizLogicError, "service changed"):
  118. ita.wait_for_calendar_service(
  119. unittest.mock.ANY, session_is_current=lambda: True,
  120. expected_service=4937, timeout=0.1)
  121. class CompactPreflightTests(unittest.TestCase):
  122. @staticmethod
  123. def snapshot(**changes):
  124. value = {
  125. "formReady": True, "turnstileReady": True,
  126. "otpValuePresent": False, "otpSendEnabled": True,
  127. "avantiEnabled": True,
  128. }
  129. value.update(changes)
  130. return value
  131. def test_async_form_options_are_polled_before_turnstile_interaction(self):
  132. page = SimpleNamespace(run_js=Mock(side_effect=[
  133. self.snapshot(formReady=False, turnstileReady=False),
  134. self.snapshot(turnstileReady=False),
  135. self.snapshot(),
  136. ]))
  137. bypasser = Mock()
  138. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 1, 2]), \
  139. patch.object(ita.time, "sleep"), \
  140. patch.object(ita, "CloudflareBypasser", return_value=bypasser) as factory:
  141. result = ita.wait_for_booking_preflight(page, script="offline")
  142. self.assertTrue(result["formReady"])
  143. self.assertEqual(page.run_js.call_count, 3)
  144. factory.assert_called_once_with(page, log=False)
  145. bypasser.click_verification_button.assert_called_once_with(is_dfs=False)
  146. def test_never_ready_form_times_out_without_touching_turnstile(self):
  147. page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
  148. formReady=False, turnstileReady=False)))
  149. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
  150. patch.object(ita.time, "sleep"), \
  151. patch.object(ita, "CloudflareBypasser") as factory, \
  152. self.assertRaisesRegex(ita.BizLogicError, "form_pending"):
  153. ita.wait_for_booking_preflight(page, script="offline")
  154. factory.assert_not_called()
  155. def test_otp_send_button_must_be_ready_before_preflight_returns(self):
  156. page = SimpleNamespace(run_js=Mock(return_value=self.snapshot(
  157. otpSendEnabled=False)))
  158. with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
  159. patch.object(ita.time, "sleep"), \
  160. self.assertRaisesRegex(ita.BizLogicError, "otp_send_disabled"):
  161. ita.wait_for_booking_preflight(page, script="offline")
  162. def test_after_otp_accepts_the_expected_send_button_cooldown(self):
  163. raw = self.snapshot(otpValuePresent=True, otpSendEnabled=False)
  164. ita.validate_booking_preflight(raw, after_otp=True)
  165. def test_preflight_failure_uses_framework_business_error(self):
  166. with self.assertRaisesRegex(ita.BizLogicError, "verification is not ready"):
  167. ita.validate_booking_preflight({
  168. "formReady": True,
  169. "turnstileReady": True,
  170. "otpValuePresent": False,
  171. "otpSendEnabled": False,
  172. "avantiEnabled": True,
  173. })
  174. class CompactFinalTests(unittest.TestCase):
  175. def setUp(self):
  176. self.route = ita.resolve_route_config({"route": route_config()}, "route")
  177. self.day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  178. self.slot = ita.SlotCandidate(
  179. self.day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  180. self.page = SimpleNamespace(
  181. tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
  182. self.plugin = SimpleNamespace(
  183. page=self.page,
  184. config=SimpleNamespace(account=VSAccount(username="applicant@example.com")),
  185. _require_calendar_context=Mock(return_value=SimpleNamespace(
  186. tab_id="tab", runtime_service="4937")),
  187. _reset_calendar_state=Mock(), _log=Mock(),
  188. )
  189. def test_final_submits_once_and_requires_explicit_success(self):
  190. response = Response(200, json.dumps({
  191. "errorMessage": "", "url": "/Reservation",
  192. }), "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
  193. with patch.object(ita, "verify_precommit_selection"), \
  194. patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  195. result = ita._submit_final_once(self.plugin, self.route, self.slot)
  196. self.assertTrue(result.success)
  197. self.assertEqual(fetch.call_count, 1)
  198. self.assertEqual(fetch.call_args.kwargs["data"]["idCalendarioGiornaliero"], "12345678")
  199. self.plugin._reset_calendar_state.assert_not_called()
  200. def test_ambiguous_final_response_raises_framework_business_error(self):
  201. response = Response(200, "{}",
  202. "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
  203. with patch.object(ita, "verify_precommit_selection"), \
  204. patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
  205. with self.assertRaises(ita.BizLogicError):
  206. ita._submit_final_once(self.plugin, self.route, self.slot)
  207. self.assertEqual(fetch.call_count, 1)
  208. self.plugin._reset_calendar_state.assert_called_once()
  209. class CalendarSelectionRegressionTests(unittest.TestCase):
  210. def setUp(self):
  211. self.day = date(2026, 10, 1)
  212. self.candidate = ita.parse_time_slots(encoded([slot()]))[0]
  213. self.days = ita.parse_calendar_availability(encoded([day()]))
  214. self.selected, self.pending, self.clicks = False, 0, []
  215. self.page = SimpleNamespace(url="https://prenotami.esteri.it/BookingCalendar",
  216. run_js=Mock(side_effect=self.dom))
  217. self.now = 0
  218. self.enterContext(patch.object(ita.time, "monotonic", side_effect=lambda: self.now))
  219. self.enterContext(patch.object(ita.time, "sleep", side_effect=self.advance))
  220. self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch",
  221. side_effect=AssertionError("Selection must not send business requests")))
  222. def advance(self, seconds):
  223. self.now += seconds
  224. def dom(self, script, mode, service, selected_day, daily_id, label, capacity, click):
  225. self.assertEqual(script, ita.CALENDAR_DOM_SCRIPT)
  226. self.assertEqual((service, selected_day), ("4937", self.day.isoformat()))
  227. count = 1
  228. if mode == "slot":
  229. self.assertEqual((daily_id, label, capacity),
  230. (self.candidate.daily_calendar_id, self.candidate.time_label, 1))
  231. if self.pending:
  232. self.pending -= 1
  233. count = 0
  234. if click:
  235. self.assertEqual(count, 1)
  236. self.clicks.append(mode)
  237. self.selected = True
  238. return {"contextReady": True, "candidateCount": count,
  239. "candidateReady": count == 1, "selected": mode == "date" or self.selected,
  240. "clicked": click and mode == "slot"}
  241. def select(self, **kwargs):
  242. return ita.select_slot_before_final(self.page, target_day=self.day, days=self.days,
  243. slots=(self.candidate,), runtime_service="4937", dom_timeout=0.3, **kwargs)
  244. def test_async_slots_are_waited_for_without_requery_or_extra_click(self):
  245. self.pending = 2
  246. self.assertEqual(self.select(), self.candidate)
  247. self.assertEqual(self.clicks, ["slot"])
  248. self.assertAlmostEqual(self.now, 0.2)
  249. self.fetch.assert_not_called()
  250. def test_missing_slots_timeout_without_click_or_submission(self):
  251. self.pending = 100
  252. with self.assertRaisesRegex(ita.BizLogicError, "did not finish loading"):
  253. self.select()
  254. self.assertEqual(self.clicks, [])
  255. self.assertLessEqual(self.now, 0.4)
  256. self.fetch.assert_not_called()
  257. def test_changed_session_stops_before_the_first_date_action(self):
  258. with self.assertRaises(ita.SessionExpiredOrInvalidError):
  259. self.select(session_is_current=lambda: False)
  260. self.page.run_js.assert_not_called()
  261. def test_duplicate_slots_are_rejected_immediately(self):
  262. self.page.run_js.side_effect = None
  263. self.page.run_js.return_value = {"contextReady": True, "candidateCount": 2,
  264. "candidateReady": True, "selected": True, "clicked": False}
  265. with self.assertRaises(ita.BizLogicError):
  266. self.select()
  267. self.assertEqual(self.now, 0)
  268. def test_readback_requires_real_boolean_and_integer_facts(self):
  269. raw = {"contextReady": True, "candidateCount": 1, "candidateReady": True,
  270. "selected": True, "clicked": False}
  271. self.page.run_js.side_effect = None
  272. for field, value in (("candidateCount", True), ("candidateCount", 1.0),
  273. ("contextReady", 1), ("candidateReady", "true"),
  274. ("selected", 1), ("clicked", 0)):
  275. with self.subTest(field=field, value=value):
  276. self.page.run_js.return_value = {**raw, field: value}
  277. with self.assertRaises(ita.BizLogicError):
  278. ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=self.candidate)
  279. def test_readback_never_accepts_missing_or_negative_candidate(self):
  280. self.selected = True
  281. self.pending = 1
  282. with self.assertRaises(ita.BizLogicError):
  283. ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=self.candidate)
  284. negative = ita.parse_time_slots(encoded([slot(free=0, remaining=-1)]))[0]
  285. self.page.run_js.side_effect = None
  286. self.page.run_js.return_value = {"contextReady": True, "candidateCount": 1,
  287. "candidateReady": True, "selected": True, "clicked": False}
  288. with self.assertRaises(ita.BizLogicError):
  289. ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=negative)
  290. class CompactPluginTests(unittest.TestCase):
  291. def plugin(self, *, query_mode="calendar", final=False):
  292. plugin = object.__new__(ita.ItaPlugin)
  293. plugin.config = VSPlgConfig(
  294. account=VSAccount(username="applicant@example.com", password="secret"),
  295. free_config={
  296. "query_mode": query_mode, "otp_mode": "cloud",
  297. "final_submit_enabled": final,
  298. "apt_configs": {"route": route_config()},
  299. },
  300. )
  301. plugin.free_config = plugin.config.free_config
  302. plugin.group_id = "ita.compact"
  303. plugin.page = SimpleNamespace(
  304. tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
  305. plugin.is_healthy = True
  306. plugin.instance_id = "compact-test"
  307. plugin.session_create_time = 0
  308. plugin._prepared_calendar = object()
  309. plugin.logger = None
  310. return plugin
  311. def test_bad_query_mode_is_not_misreported_as_an_expired_session(self):
  312. plugin = self.plugin(query_mode="services_probe")
  313. with patch.object(plugin, "health_check") as health, \
  314. self.assertRaisesRegex(ita.BizLogicError, "query_mode=calendar"):
  315. plugin.query(AppointmentType(routing_key="route"))
  316. health.assert_not_called()
  317. def test_status_reports_elapsed_session_age(self):
  318. plugin = self.plugin()
  319. plugin.session_create_time = 100
  320. with patch.object(ita.time, "time", return_value=145.8):
  321. self.assertEqual(plugin.get_plugin_status().session_age_sec, 45)
  322. plugin.session_create_time = 0
  323. self.assertEqual(plugin.get_plugin_status().session_age_sec, 0)
  324. def test_disconnected_browser_does_not_break_status_reporting(self):
  325. plugin = self.plugin()
  326. page = Mock()
  327. type(page).url = unittest.mock.PropertyMock(side_effect=RuntimeError("disconnected"))
  328. plugin.page = page
  329. self.assertEqual(plugin.get_plugin_status().current_url, "")
  330. def test_query_publishes_only_real_calendar_availability(self):
  331. plugin, apt = self.plugin(), AppointmentType(routing_key="route")
  332. positive = (ita.CalendarDay(date(2026, 10, 2), 1, 0),)
  333. with patch.object(plugin, "health_check", return_value=True), \
  334. patch.object(plugin, "_require_calendar_context"), \
  335. patch.object(ita, "scan_until_first_available_month", return_value=(positive,)):
  336. result = plugin.query(apt)
  337. self.assertTrue(result.success)
  338. self.assertEqual(result.availability_status, AvailabilityStatus.Available)
  339. self.assertEqual(result.earliest_date.date(), date(2026, 10, 2))
  340. def test_book_rejects_pool_account_signal_as_applicant_identity(self):
  341. plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
  342. signal = VSQueryResult(success=True, apt_type=apt,
  343. availability_status=AvailabilityStatus.Available)
  344. with self.assertRaisesRegex(Exception, "applicant account"):
  345. plugin.book(signal, {"username": "pool@example.com"})
  346. def test_prefinal_book_does_not_submit(self):
  347. plugin, apt = self.plugin(query_mode="services_probe"), AppointmentType(routing_key="route")
  348. signal = VSQueryResult(success=True, apt_type=apt,
  349. availability_status=AvailabilityStatus.Available)
  350. selected_day = ita.CalendarDay(date(2026, 10, 2), 1, 0)
  351. slot = ita.SlotCandidate(
  352. selected_day.day, 1, 0, time(10, 5), time(11, 5), "12345678")
  353. with patch.object(ita, "book_date_preferences", return_value=(date.min, date.max)), \
  354. patch.object(plugin, "_calendar_context_matches", return_value=True), \
  355. patch.object(ita, "recheck_calendar_before_final", return_value=slot), \
  356. patch.object(ita, "_submit_final_once") as submit:
  357. result = plugin.book(signal, {"username": "applicant@example.com"})
  358. self.assertFalse(result.success)
  359. self.assertEqual(result.label, ita.BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  360. submit.assert_not_called()
  361. if __name__ == "__main__":
  362. unittest.main()