test_ita_calendar_book_flow.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. import copy
  2. import json
  3. import shutil
  4. import subprocess
  5. import traceback
  6. import unittest
  7. from contextlib import contextmanager
  8. from datetime import date, datetime
  9. from unittest.mock import Mock, patch
  10. from plugins import ita_calendar_book as book_calendar
  11. from plugins.ita_calendar_book import (
  12. DATE_SELECTION_SCRIPT, SLOT_SELECTION_SCRIPT, TIME_SLOTS_PATH,
  13. CalendarBookError, book_date_preferences, recheck_calendar_before_final,
  14. )
  15. from plugins.ita_calendar_query import AVAILABILITY_PATH, CalendarNextMonthUnavailableError
  16. from plugins.ita_plugin import (
  17. BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL, ItaPlugin,
  18. )
  19. from test.test_ita_calendar_book import FakePage, SERVICE, packet
  20. from test import test_ita_plugin as plugin_fixtures
  21. from test.test_ita_protocol import availability_item, slot_item
  22. from vs_types import (
  23. AppointmentType, BizLogicError, DateAvailability, RateLimiteddError,
  24. SessionExpiredOrInvalidError, TimeSlot, VSAccount, VSPlgConfig, VSQueryResult,
  25. )
  26. def month(value, inventory, *, automatic_day=None, slots=None):
  27. """Synthetic inventory only; IDs and accounts below never leave the tests."""
  28. return {"month": value, "inventory": inventory, "automatic_day": automatic_day,
  29. "slots": slots or {}}
  30. def positive_month():
  31. return month("2026-10", {13: 1})
  32. class FakeListener:
  33. def __init__(self, page):
  34. self.page = page
  35. self.queue = []
  36. self.listening = False
  37. self.starts = 0
  38. self.stops = 0
  39. self.target = None
  40. def start(self, targets, method):
  41. self.starts += 1
  42. self.target = targets
  43. self.queue.clear() # Matches the installed Listener.start contract.
  44. self.listening = True
  45. self.page.events.append("listen-start")
  46. if method != "POST":
  47. raise AssertionError("Unexpected listener method")
  48. def wait(self, timeout, raise_err=False):
  49. if not self.listening:
  50. raise AssertionError("Wait without listener")
  51. if self.page.wait_hook:
  52. self.page.wait_hook()
  53. if not self.queue:
  54. return False
  55. result = self.queue.pop(0)
  56. if result.url.endswith(TIME_SLOTS_PATH):
  57. self.page.selected_day = getattr(result, "fixture_day", None)
  58. self.page.content_day = self.page.render_day or self.page.selected_day
  59. self.page.current_slots = getattr(result, "fixture_slots", [])
  60. self.page.active = False
  61. return result
  62. def stop(self):
  63. self.stops += 1
  64. self.queue.clear()
  65. self.listening = False
  66. self.page.events.append("listen-stop")
  67. class FlowPage(FakePage):
  68. def __init__(self, months=None, *, passes=None):
  69. super().__init__()
  70. self.tab_id = "book-tab"
  71. self.listen = FakeListener(self)
  72. self.wait = Mock()
  73. self.quit = Mock()
  74. self.passes = passes or [months or [positive_month()]]
  75. self.refreshes = 0
  76. self.month_index = 0
  77. self.month_spec = self.passes[0][0]
  78. self.selected_day = None
  79. self.content_day = None
  80. self.current_slots = []
  81. self.date_clicks = []
  82. self.month_clicks = 0
  83. self.requests = []
  84. self.request_mutator = None
  85. self.wait_hook = None
  86. self.render_day = None
  87. self.reverse_responses = False
  88. self.drop_automatic = False
  89. self.duplicate_availability = False
  90. self.date_ack = True
  91. self.date_candidate_count = None
  92. self.date_enabled = True
  93. self.date_runtime_matches = True
  94. def response_packet(self, path, body, items, day=None):
  95. result = packet(path, body, items)
  96. result.tab_id = self.tab_id
  97. result.is_failed = False
  98. result.fixture_day = day
  99. result.fixture_slots = items
  100. if self.request_mutator:
  101. self.request_mutator(result)
  102. self.requests.append(result)
  103. return result
  104. def times_packet(self, day):
  105. number = int(day[-2:])
  106. free = self.month_spec["slots"].get(number, self.month_spec["inventory"].get(number, 0))
  107. day_value = date.fromisoformat(day)
  108. items = [slot_item(day_value.strftime("%d/%m/%Y 00:00:00"), (10, 5), (11, 5),
  109. free, free - 1, 80000000 + self.refreshes * 100 + number)]
  110. return self.response_packet(TIME_SLOTS_PATH, {"selectedDay": day, "idService": SERVICE}, items, day)
  111. def load_month(self):
  112. self.selected_day = self.content_day = None
  113. value = self.month_spec["month"]
  114. inventory = self.month_spec["inventory"]
  115. items = [availability_item(date.fromisoformat(f"{value}-{day:02d}").strftime("%d/%m/%Y 00:00:00"),
  116. free, free - 1) for day, free in inventory.items()]
  117. availability = self.response_packet(
  118. AVAILABILITY_PATH,
  119. {"_Servizio": "calendar-runtime-key", "selectedDay": f"{value}-01"}, items,
  120. )
  121. responses = [availability]
  122. if self.duplicate_availability:
  123. responses.append(availability)
  124. elif inventory and not self.drop_automatic:
  125. auto = self.month_spec["automatic_day"] or min(inventory)
  126. responses.append(self.times_packet(f"{value}-{auto:02d}"))
  127. if self.reverse_responses:
  128. responses.reverse()
  129. self.listen.queue.extend(responses)
  130. def refresh(self):
  131. self.refreshes += 1
  132. self.month_index = 0
  133. self.month_spec = self.passes[min(self.refreshes - 1, len(self.passes) - 1)][0]
  134. self.events.append("refresh")
  135. self.load_month()
  136. def next_month(self):
  137. self.month_clicks += 1
  138. self.month_index += 1
  139. sequence = self.passes[min(self.refreshes - 1, len(self.passes) - 1)]
  140. if self.month_index >= len(sequence):
  141. raise CalendarNextMonthUnavailableError("No next month in fixture")
  142. self.month_spec = sequence[self.month_index]
  143. self.events.append("next-month")
  144. self.load_month()
  145. def run_js(self, script, *args):
  146. if script == DATE_SELECTION_SCRIPT:
  147. service, day, click = args
  148. count = int(day[:7] == self.month_spec["month"] and int(day[-2:]) in self.month_spec["inventory"])
  149. if self.date_candidate_count is not None:
  150. count = self.date_candidate_count
  151. selected = day == self.selected_day == self.content_day
  152. clicked = bool(click and self.date_ack and not selected)
  153. raw = {"runtimeMatches": self.date_runtime_matches and service == self.service,
  154. "finalGuarded": True, "candidateCount": count,
  155. "candidateEnabled": self.date_enabled, "selectedMatches": selected, "clicked": clicked}
  156. if clicked:
  157. self.date_clicks.append(day)
  158. self.events.append("date-click")
  159. self.listen.queue.append(self.times_packet(day))
  160. return raw
  161. raw = super().run_js(script, *args)
  162. if script == SLOT_SELECTION_SCRIPT:
  163. _, day, daily_id, label, free, _ = args
  164. matching = [item for item in self.current_slots
  165. if str(item["IDCalendarioServizioGiornaliero"]) == daily_id]
  166. raw["timelineDays"] = [self.selected_day] if self.selected_day else []
  167. raw["contentDays"] = [self.content_day] if self.content_day else []
  168. raw["firstSelectedMatches"] = day == self.selected_day == self.content_day
  169. raw["candidateCount"] = len(matching)
  170. raw["candidateReady"] = len(matching) == 1 and matching[0]["SlotLiberi"] == free
  171. raw.update(self.after_overrides if self.clicks else {})
  172. return raw
  173. @contextmanager
  174. def browser_navigation(page):
  175. with patch.object(book_calendar, "click_next_month", side_effect=lambda _page: page.next_month()), \
  176. patch.object(book_calendar.time, "sleep"):
  177. yield
  178. def run_flow(page, **kwargs):
  179. options = dict(lookahead_months=3, start_day=date(2026, 8, 1), end_day=date(2026, 12, 31),
  180. session_is_current=lambda: True, month_click_interval_seconds=0, dom_timeout=0)
  181. options.update(kwargs)
  182. with browser_navigation(page):
  183. return recheck_calendar_before_final(page, **options)
  184. class BookCalendarFlowTests(unittest.TestCase):
  185. def assert_stopped(self, page):
  186. self.assertFalse(page.listen.listening)
  187. self.assertEqual(page.listen.starts, page.listen.stops)
  188. def test_refresh_waits_for_runtime_reassignment_without_repeating_refresh(self):
  189. page = FlowPage()
  190. original_run_js = page.run_js
  191. pending_reads = []
  192. def delayed(script, *args):
  193. result = original_run_js(script, *args)
  194. if script == book_calendar.RUNTIME_SERVICE_SCRIPT and page.refreshes:
  195. pending_reads.append(True)
  196. if len(pending_reads) == 1:
  197. return {**result, "value": ""}
  198. return result
  199. page.run_js = delayed
  200. self.assertIsNotNone(run_flow(page, dom_timeout=1))
  201. self.assertEqual(page.refreshes, 1)
  202. self.assertEqual(page.clicks, 1)
  203. self.assertEqual(len(page.requests), 2)
  204. self.assert_stopped(page)
  205. def test_empty_after_refresh_times_out_without_selecting_or_refreshing_again(self):
  206. page = FlowPage()
  207. original_refresh = page.refresh
  208. def empty_refresh():
  209. original_refresh()
  210. page.service = ""
  211. page.refresh = empty_refresh
  212. with self.assertRaises(book_calendar.CalendarServiceNotReadyError):
  213. run_flow(page)
  214. self.assertEqual(page.refreshes, 1)
  215. self.assertEqual(page.clicks, 0)
  216. self.assert_stopped(page)
  217. def test_automatic_positive_day_uses_fresh_response_without_date_click(self):
  218. page = FlowPage()
  219. result = run_flow(page)
  220. self.assertEqual(result.candidate.day, date(2026, 10, 13))
  221. self.assertEqual(result.candidate.daily_calendar_id, "80000113")
  222. self.assertEqual(page.refreshes, 1)
  223. self.assertEqual(page.date_clicks, [])
  224. self.assertEqual(page.clicks, 1)
  225. self.assertEqual(len(page.requests), 2)
  226. self.assert_stopped(page)
  227. def test_native_date_click_is_followed_by_current_time_slots(self):
  228. page = FlowPage([month("2026-10", {1: 0, 13: 1})])
  229. result = run_flow(page)
  230. self.assertEqual(result.candidate.day, date(2026, 10, 13))
  231. self.assertEqual(page.date_clicks, ["2026-10-13"])
  232. self.assertEqual(page.listen.starts, 2)
  233. self.assertEqual(len(page.requests), 3)
  234. self.assert_stopped(page)
  235. def test_old_listener_queue_is_cleared_before_month_action(self):
  236. page = FlowPage()
  237. stale = packet(TIME_SLOTS_PATH, {}, [])
  238. stale.tab_id = "query-tab"
  239. page.listen.queue.append(stale)
  240. result = run_flow(page)
  241. self.assertIsNotNone(result)
  242. self.assertIsNot(page.requests[-1], stale)
  243. def test_can_collect_automatic_response_before_availability_delivery(self):
  244. page = FlowPage()
  245. page.reverse_responses = True
  246. self.assertIsNotNone(run_flow(page))
  247. self.assertEqual(page.date_clicks, [])
  248. def test_cross_year_scan_stops_at_first_usable_day(self):
  249. page = FlowPage([month("2026-12", {1: 0}), month("2027-01", {5: 1}), month("2027-02", {1: 4})])
  250. result = run_flow(page, end_day=date(2027, 3, 1))
  251. self.assertEqual(result.candidate.day, date(2027, 1, 5))
  252. self.assertEqual(page.month_clicks, 1)
  253. def test_applies_inclusive_preferences_even_if_earlier_month_is_positive(self):
  254. page = FlowPage([month("2026-09", {1: 2}), month("2026-10", {12: 2, 13: 1, 14: 3})])
  255. result = run_flow(page, start_day=date(2026, 10, 13), end_day=date(2026, 10, 13))
  256. self.assertEqual(result.candidate.day, date(2026, 10, 13))
  257. self.assertEqual(page.date_clicks, ["2026-10-13"])
  258. self.assertEqual(page.month_clicks, 1)
  259. def test_date_inventory_race_tries_next_day_without_repeating_failed_candidate(self):
  260. page = FlowPage([month("2026-10", {13: 1, 14: 2}, slots={13: 0})])
  261. result = run_flow(page)
  262. self.assertEqual(result.candidate.day, date(2026, 10, 14))
  263. self.assertEqual(page.date_clicks, ["2026-10-14"])
  264. self.assertEqual(page.clicks, 1)
  265. def test_later_automatic_day_is_recaptured_after_another_date_was_selected(self):
  266. page = FlowPage([month("2026-10", {13: 1, 14: 1}, automatic_day=14, slots={13: 0})])
  267. result = run_flow(page)
  268. self.assertEqual(result.candidate.day, date(2026, 10, 14))
  269. self.assertEqual(page.date_clicks, ["2026-10-13", "2026-10-14"])
  270. def test_valid_hint_is_rechecked_before_earlier_dates(self):
  271. page = FlowPage([month("2026-09", {9: 2}), month("2026-10", {12: 2, 13: 1})])
  272. result = run_flow(page, preferred_day=date(2026, 10, 13))
  273. self.assertEqual(result.candidate.day, date(2026, 10, 13))
  274. self.assertEqual(page.refreshes, 1)
  275. self.assertEqual(page.date_clicks, ["2026-10-13"])
  276. def test_missing_hint_restarts_once_and_uses_new_earlier_month_response(self):
  277. first = [month("2026-09", {9: 0}), month("2026-10", {13: 0})]
  278. second = [month("2026-09", {9: 1}), month("2026-10", {13: 0})]
  279. page = FlowPage(passes=[first, second])
  280. result = run_flow(page, preferred_day=date(2026, 10, 13))
  281. self.assertEqual(result.candidate.day, date(2026, 9, 9))
  282. self.assertEqual(result.candidate.daily_calendar_id, "80000209")
  283. self.assertEqual(page.refreshes, 2)
  284. def test_hint_slot_race_does_not_repeat_same_day_on_fallback(self):
  285. page = FlowPage([month("2026-10", {13: 1, 14: 1}, slots={13: 0})])
  286. result = run_flow(page, preferred_day=date(2026, 10, 13))
  287. self.assertEqual(result.candidate.day, date(2026, 10, 14))
  288. self.assertEqual(page.refreshes, 2)
  289. self.assertNotIn("2026-10-13", page.date_clicks)
  290. def test_hint_outside_preference_or_horizon_is_not_followed(self):
  291. for hint in (date(2027, 10, 13), date(2026, 9, 30)):
  292. with self.subTest(hint=hint):
  293. page = FlowPage()
  294. result = run_flow(page, preferred_day=hint, start_day=date(2026, 10, 1))
  295. self.assertEqual(result.candidate.day, date(2026, 10, 13))
  296. self.assertEqual(page.refreshes, 1)
  297. def test_full_negative_horizon_returns_none_without_slot_clicks(self):
  298. page = FlowPage([month("2026-08", {1: 0}), month("2026-09", {}), month("2026-10", {1: 0})])
  299. self.assertIsNone(run_flow(page))
  300. self.assertEqual(page.month_clicks, 2)
  301. self.assertEqual(page.date_clicks, [])
  302. self.assertEqual(page.clicks, 0)
  303. self.assert_stopped(page)
  304. def test_no_month_beyond_user_end_is_requested(self):
  305. page = FlowPage([month("2026-10", {1: 0})])
  306. self.assertIsNone(run_flow(page, end_day=date(2026, 10, 31)))
  307. self.assertEqual(page.month_clicks, 0)
  308. def test_missing_next_month_is_an_error_not_no_inventory(self):
  309. page = FlowPage([month("2026-10", {})])
  310. with self.assertRaises(CalendarBookError):
  311. run_flow(page)
  312. self.assert_stopped(page)
  313. def test_month_jump_is_rejected(self):
  314. page = FlowPage([month("2026-08", {}), month("2026-10", {13: 1})])
  315. with self.assertRaisesRegex(CalendarBookError, "exactly one month"):
  316. run_flow(page)
  317. self.assertEqual(page.clicks, 0)
  318. self.assert_stopped(page)
  319. def test_fallback_anchor_change_is_rejected(self):
  320. page = FlowPage(passes=[[month("2026-10", {13: 0})], [month("2026-11", {13: 1})]])
  321. with self.assertRaisesRegex(CalendarBookError, "anchor"):
  322. run_flow(page, preferred_day=date(2026, 10, 13))
  323. self.assertEqual(page.clicks, 0)
  324. def test_bad_packet_metadata_is_never_used_or_retried(self):
  325. mutations = [
  326. lambda p: setattr(p, "tab_id", "query-tab"),
  327. lambda p: setattr(p, "is_failed", True),
  328. lambda p: setattr(p, "url", "https://other.example.test" + AVAILABILITY_PATH),
  329. lambda p: setattr(p, "method", "GET"),
  330. lambda p: setattr(p.response, "status", 429),
  331. lambda p: p.request.postData.update(_Servizio=None),
  332. ]
  333. for mutate in mutations:
  334. with self.subTest(mutation=mutations.index(mutate)):
  335. page = FlowPage()
  336. page.request_mutator = mutate
  337. with self.assertRaises(CalendarBookError):
  338. run_flow(page)
  339. self.assertEqual(page.refreshes, 1)
  340. self.assertEqual(page.clicks, 0)
  341. self.assert_stopped(page)
  342. def test_time_slots_from_wrong_date_or_service_fail(self):
  343. for field, value in (("selectedDay", "2026-10-14"), ("idService", "wrong-service")):
  344. page = FlowPage()
  345. page.request_mutator = lambda p: p.request.postData.update({field: value}) if p.url.endswith(TIME_SLOTS_PATH) else None
  346. with self.subTest(field=field), self.assertRaises(CalendarBookError):
  347. run_flow(page)
  348. self.assertEqual(page.clicks, 0)
  349. self.assert_stopped(page)
  350. def test_date_click_response_is_bound_to_that_day_and_tab(self):
  351. for field in ("tab", "day"):
  352. with self.subTest(field=field):
  353. page = FlowPage([month("2026-10", {1: 0, 13: 1})])
  354. def corrupt_after_click(result):
  355. if not page.date_clicks:
  356. return
  357. if field == "tab":
  358. result.tab_id = "old-query-tab"
  359. else:
  360. result.request.postData["selectedDay"] = "2026-10-01"
  361. page.request_mutator = corrupt_after_click
  362. with self.assertRaises(CalendarBookError):
  363. run_flow(page)
  364. self.assertEqual(page.date_clicks, ["2026-10-13"])
  365. self.assertEqual(page.clicks, 0)
  366. self.assert_stopped(page)
  367. def test_availability_service_must_remain_same_across_months(self):
  368. page = FlowPage([month("2026-09", {}), positive_month()])
  369. page.request_mutator = lambda p: p.request.postData.update(_Servizio="changed") if page.month_clicks and p.url.endswith(AVAILABILITY_PATH) else None
  370. with self.assertRaisesRegex(CalendarBookError, "runtime service changed"):
  371. run_flow(page)
  372. def test_missing_automatic_response_and_duplicate_month_stop_listener(self):
  373. for option in ("drop_automatic", "duplicate_availability"):
  374. with self.subTest(option=option):
  375. page = FlowPage()
  376. setattr(page, option, True)
  377. with self.assertRaises(CalendarBookError):
  378. run_flow(page)
  379. self.assertEqual(page.date_clicks, [])
  380. self.assert_stopped(page)
  381. def test_negative_availability_but_positive_auto_slot_is_conflict(self):
  382. page = FlowPage([month("2026-10", {13: 0}, slots={13: 1})])
  383. with self.assertRaisesRegex(CalendarBookError, "disagree"):
  384. run_flow(page)
  385. self.assertEqual(page.clicks, 0)
  386. def test_site_date_fallback_does_not_select_wrong_day(self):
  387. page = FlowPage()
  388. page.render_day = "2026-10-01"
  389. with self.assertRaisesRegex(CalendarBookError, "selected date"):
  390. run_flow(page)
  391. self.assertEqual(page.clicks, 0)
  392. self.assert_stopped(page)
  393. def test_failed_date_click_is_not_retried(self):
  394. page = FlowPage([month("2026-10", {1: 0, 13: 1})])
  395. page.date_ack = False
  396. with self.assertRaisesRegex(CalendarBookError, "acknowledged"):
  397. run_flow(page)
  398. self.assertEqual(page.date_clicks, [])
  399. self.assert_stopped(page)
  400. def test_bad_date_control_is_rejected_without_click(self):
  401. for field, value in (("date_candidate_count", 2), ("date_enabled", False),
  402. ("date_runtime_matches", False)):
  403. with self.subTest(field=field):
  404. page = FlowPage([month("2026-10", {1: 0, 13: 1})])
  405. setattr(page, field, value)
  406. with self.assertRaises(CalendarBookError):
  407. run_flow(page)
  408. self.assertEqual(page.date_clicks, [])
  409. self.assert_stopped(page)
  410. def test_post_slot_click_error_stops_without_trying_another_day(self):
  411. page = FlowPage([month("2026-10", {13: 1, 14: 2})])
  412. page.after_overrides = {"activeIdMatches": False}
  413. with self.assertRaises(CalendarBookError):
  414. run_flow(page)
  415. self.assertEqual(page.clicks, 1)
  416. self.assertEqual(page.date_clicks, [])
  417. def test_context_invalid_before_or_during_capture_blocks_selection(self):
  418. page = FlowPage()
  419. with self.assertRaises(CalendarBookError):
  420. run_flow(page, session_is_current=lambda: False)
  421. self.assertEqual(page.refreshes, 0)
  422. current = [True]
  423. page = FlowPage()
  424. page.wait_hook = lambda: current.__setitem__(0, False)
  425. with self.assertRaises(CalendarBookError):
  426. run_flow(page, session_is_current=lambda: current[0])
  427. self.assertEqual(page.clicks, 0)
  428. self.assert_stopped(page)
  429. def test_invalid_settings_do_not_navigate(self):
  430. for kwargs in ({"lookahead_months": True}, {"lookahead_months": 0},
  431. {"start_day": None}, {"end_day": date(2025, 1, 1)},
  432. {"preferred_day": "2026-10-13"}, {"timeout": 0},
  433. {"timeout": float("nan")}, {"dom_timeout": -1}):
  434. with self.subTest(kwargs=kwargs):
  435. page = FlowPage()
  436. with self.assertRaises(CalendarBookError):
  437. run_flow(page, **kwargs)
  438. self.assertEqual(page.refreshes, 0)
  439. def test_provider_error_does_not_leak_raw_body(self):
  440. page = FlowPage()
  441. page.wait_hook = Mock(side_effect=RuntimeError("secret-response-body"))
  442. try:
  443. run_flow(page)
  444. except CalendarBookError:
  445. self.assertNotIn("secret-response-body", traceback.format_exc())
  446. else:
  447. self.fail("Provider error was accepted")
  448. self.assert_stopped(page)
  449. class BookPreferenceTests(unittest.TestCase):
  450. def test_uses_existing_keys_and_does_not_mutate_inputs(self):
  451. values = {"expected_start_date": "2026-10-13", "expected_end_date": "2026-10-13", "other": "keep"}
  452. before = copy.deepcopy(values)
  453. self.assertEqual(book_date_preferences(values), (date(2026, 10, 13), date(2026, 10, 13)))
  454. self.assertEqual(values, before)
  455. self.assertEqual(book_date_preferences({}), (date(2000, 1, 1), date(2100, 1, 1)))
  456. def test_rejects_unknown_formats_and_inverted_range(self):
  457. for values in (None, {"expected_start_date": None}, {"expected_start_date": "20261013"},
  458. {"expected_start_date": "2026-02-30"}, {"expected_start_date": "secret-input"},
  459. {"expected_start_date": "2026-10-14", "expected_end_date": "2026-10-13"}):
  460. with self.subTest(values=values), self.assertRaises(CalendarBookError) as raised:
  461. book_date_preferences(values)
  462. self.assertNotIn("secret-input", str(raised.exception))
  463. def prepared_plugin(page, *, routing_key="slot.example.it.tourist"):
  464. plugin = plugin_fixtures.ItaPluginQuerySafetyTests._plugin(
  465. page, routing_key=routing_key, service_id=9001,
  466. capability="single_schengen_tourism", lookahead_months=3,
  467. )
  468. plugin.config = VSPlgConfig(account=VSAccount(username="applicant@example.test"), free_config=plugin.free_config)
  469. plugin.instance_id = "book-offline"
  470. plugin.session_create_time = 111.0
  471. plugin._transient_user_data_path = "/nonexistent/ita-book-flow-test"
  472. plugin._reset_calendar_book_state()
  473. route = plugin._resolve_route(AppointmentType(routing_key=routing_key))
  474. plugin._record_calendar_book_prepared_route(route)
  475. plugin.query = Mock(side_effect=AssertionError("Calendar Book must not call Query"))
  476. trigger = VSQueryResult(apt_type=AppointmentType(routing_key=routing_key))
  477. return plugin, route, trigger
  478. class BookEntryTests(unittest.TestCase):
  479. def test_real_entry_runs_flow_and_keeps_book_result_unsuccessful(self):
  480. page = FlowPage()
  481. plugin, _, trigger = prepared_plugin(page)
  482. inputs = {"username": "applicant@example.test", "expected_start_date": "2026-10-13",
  483. "expected_end_date": "2026-10-13"}
  484. original = copy.deepcopy(inputs)
  485. with browser_navigation(page):
  486. result = plugin.book(trigger, inputs)
  487. self.assertFalse(result.success)
  488. self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  489. self.assertEqual((result.urn, result.book_date, result.book_time, result.account), ("", "", "", ""))
  490. self.assertEqual(plugin.last_booking_precommit.candidate.day, date(2026, 10, 13))
  491. self.assertNotIn("80000113", str(plugin.logger.call_args_list))
  492. self.assertNotIn("applicant@example.test", str(plugin.logger.call_args_list))
  493. self.assertEqual(inputs, original)
  494. plugin.query.assert_not_called()
  495. def test_entry_treats_query_date_as_hint_not_inventory(self):
  496. page = FlowPage([month("2026-10", {13: 0, 14: 1})])
  497. plugin, _, trigger = prepared_plugin(page)
  498. trigger.earliest_date = datetime(2026, 10, 13)
  499. trigger.availability = [DateAvailability(date=datetime(2026, 10, 13),
  500. times=[TimeSlot(time="01:23", label="stale-query-slot")])]
  501. with browser_navigation(page):
  502. result = plugin.book(trigger, {"username": "applicant@example.test"})
  503. self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  504. self.assertEqual(plugin.last_booking_precommit.candidate.day, date(2026, 10, 14))
  505. self.assertEqual(plugin.last_booking_precommit.candidate.time_label, "10:05 - 11:05")
  506. def test_query_preparation_cannot_be_converted_into_book_preparation(self):
  507. page = FlowPage()
  508. plugin, route, trigger = prepared_plugin(page)
  509. plugin._calendar_query_route_key = route.routing_key
  510. with self.assertRaises(BizLogicError):
  511. plugin._record_calendar_book_prepared_route(route)
  512. with self.assertRaises(BizLogicError):
  513. plugin.book(trigger, {"username": "applicant@example.test"})
  514. self.assertEqual(page.refreshes, 0)
  515. def test_url_alone_is_not_a_book_preparation_proof(self):
  516. page = FlowPage()
  517. plugin, _, trigger = prepared_plugin(page)
  518. plugin._reset_calendar_book_state()
  519. with self.assertRaises(BizLogicError):
  520. plugin.book(trigger, {"username": "applicant@example.test"})
  521. self.assertEqual(page.refreshes, 0)
  522. plugin.query.assert_not_called()
  523. def test_missing_or_different_applicant_is_rejected(self):
  524. for inputs in (None, {}, {"username": "other@example.test"}):
  525. with self.subTest(inputs=inputs):
  526. page = FlowPage()
  527. plugin, _, trigger = prepared_plugin(page)
  528. with self.assertRaises(BizLogicError):
  529. plugin.book(trigger, inputs)
  530. self.assertEqual(page.refreshes, 0)
  531. def test_changed_account_page_login_or_route_is_rejected(self):
  532. mutations = [
  533. lambda p: setattr(p.config.account, "username", "other@example.test"),
  534. lambda p: setattr(p, "page", FlowPage()),
  535. lambda p: setattr(p, "session_create_time", 222.0),
  536. lambda p: setattr(p.page, "tab_id", "another-tab"),
  537. lambda p: p.free_config["apt_configs"]["slot.example.it.tourist"].update(service_id=9002),
  538. lambda p: p.free_config.update(final_submit_enabled=True),
  539. lambda p: setattr(p.page, "service", "another-runtime"),
  540. ]
  541. for mutation in mutations:
  542. with self.subTest(mutation=mutations.index(mutation)):
  543. page = FlowPage()
  544. plugin, _, trigger = prepared_plugin(page)
  545. mutation(plugin)
  546. with self.assertRaises(BizLogicError):
  547. plugin.book(trigger, {"username": "applicant@example.test"})
  548. self.assertEqual(page.refreshes, 0)
  549. def test_preparation_from_another_plugin_instance_is_rejected(self):
  550. page = FlowPage()
  551. first, _, _ = prepared_plugin(page)
  552. second, _, trigger = prepared_plugin(page)
  553. second._calendar_book_prepared_context = first._calendar_book_prepared_context
  554. with self.assertRaises(BizLogicError):
  555. second.book(trigger, {"username": "applicant@example.test"})
  556. def test_second_book_call_does_not_repeat_any_network_action(self):
  557. page = FlowPage()
  558. plugin, _, trigger = prepared_plugin(page)
  559. with browser_navigation(page):
  560. plugin.book(trigger, {"username": "applicant@example.test"})
  561. with self.assertRaisesRegex(BizLogicError, "already attempted"):
  562. plugin.book(trigger, {"username": "applicant@example.test"})
  563. self.assertEqual(page.refreshes, 1)
  564. self.assertEqual(page.clicks, 1)
  565. def test_no_inventory_within_preferences_is_not_reported_as_success(self):
  566. page = FlowPage([month("2026-10", {13: 0})])
  567. plugin, _, trigger = prepared_plugin(page)
  568. with browser_navigation(page):
  569. result = plugin.book(trigger, {"username": "applicant@example.test", "expected_end_date": "2026-10-31"})
  570. self.assertFalse(result.success)
  571. self.assertEqual(result.label, BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
  572. self.assertIsNone(plugin.last_booking_precommit)
  573. def test_mid_capture_account_change_invalidates_preparation(self):
  574. page = FlowPage()
  575. plugin, _, trigger = prepared_plugin(page)
  576. page.wait_hook = lambda: setattr(plugin.config.account, "username", "other@example.test")
  577. with browser_navigation(page), self.assertRaises(BizLogicError):
  578. plugin.book(trigger, {"username": "applicant@example.test"})
  579. self.assertIsNone(plugin._calendar_book_prepared_context)
  580. self.assertIsNone(plugin.last_booking_precommit)
  581. self.assertEqual(page.clicks, 0)
  582. def test_lifecycle_operations_clear_book_preparation(self):
  583. for action in ("config", "login", "cleanup"):
  584. with self.subTest(action=action):
  585. plugin, _, _ = prepared_plugin(FlowPage())
  586. if action == "config":
  587. plugin.set_config(plugin.config)
  588. elif action == "login":
  589. with patch("plugins.ita_plugin.ChromiumOptions", side_effect=RuntimeError("offline stop")):
  590. with self.assertRaises(RuntimeError):
  591. plugin.create_session()
  592. else:
  593. plugin.cleanup()
  594. self.assertIsNone(plugin._calendar_book_prepared_context)
  595. self.assertIsNone(plugin.last_booking_precommit)
  596. def test_http_auth_and_rate_limit_use_existing_framework_errors(self):
  597. for status, error in ((401, SessionExpiredOrInvalidError), (429, RateLimiteddError)):
  598. with self.subTest(status=status):
  599. page = FlowPage()
  600. plugin, _, trigger = prepared_plugin(page)
  601. page.request_mutator = lambda p: setattr(p.response, "status", status)
  602. with browser_navigation(page), self.assertRaises(error):
  603. plugin.book(trigger, {"username": "applicant@example.test"})
  604. self.assertIsNone(plugin._calendar_book_prepared_context)
  605. self.assertEqual(page.clicks, 0)
  606. def test_provider_failure_at_entry_is_sanitized_and_invalidates_proof(self):
  607. page = FlowPage()
  608. plugin, _, trigger = prepared_plugin(page)
  609. page.browser_error = "secret-provider-body"
  610. try:
  611. plugin.book(trigger, {"username": "applicant@example.test"})
  612. except BizLogicError:
  613. self.assertNotIn("secret-provider-body", traceback.format_exc())
  614. else:
  615. self.fail("Provider failure was accepted")
  616. self.assertIsNone(plugin._calendar_book_prepared_context)
  617. def test_two_route_keys_share_the_same_calendar_flow(self):
  618. for key in ("slot.hkg.it.tourist", "slot.dub.it.tourist"):
  619. with self.subTest(key=key):
  620. page = FlowPage()
  621. plugin, _, trigger = prepared_plugin(page, routing_key=key)
  622. with browser_navigation(page):
  623. result = plugin.book(trigger, {"username": "applicant@example.test"})
  624. self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  625. def test_query_mode_does_not_drive_the_prepared_book_branch(self):
  626. page = FlowPage()
  627. plugin, _, trigger = prepared_plugin(page)
  628. plugin.free_config["query_mode"] = "calendar"
  629. with browser_navigation(page):
  630. result = plugin.book(trigger, {"username": "applicant@example.test"})
  631. self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
  632. plugin.query.assert_not_called()
  633. def test_final_request_observation_rejects_instead_of_reporting_precommit(self):
  634. page = FlowPage()
  635. plugin, _, trigger = prepared_plugin(page)
  636. page.guard_final_count = 1
  637. with browser_navigation(page), self.assertRaises(BizLogicError):
  638. plugin.book(trigger, {"username": "applicant@example.test"})
  639. self.assertIsNone(plugin.last_booking_precommit)
  640. self.assertEqual(page.refreshes, 0)
  641. self.assertEqual(page.clicks, 0)
  642. DATE_JS_HARNESS = r"""
  643. const vm = require('node:vm');
  644. const {source, mode} = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
  645. let clicks = 0, finalClicks = 0;
  646. const zeroSize = mode.startsWith('zero_size') || mode === 'selected_zero_size';
  647. function node(day) {
  648. const classes = new Set(['input-async-abilitato']);
  649. return {dataset: {date: day}, isConnected: true,
  650. classList: {contains: c => classes.has(c), add: c => classes.add(c)},
  651. hasAttribute: () => false, getAttribute: () => null,
  652. getBoundingClientRect: () => ({width: zeroSize || mode === 'zero_width' ? 0 : 90,
  653. height: zeroSize || mode === 'zero_height' ? 0 : 30, left: 3000}),
  654. };
  655. }
  656. const old = node('2026-10-01'), link = node('2026-10-13');
  657. let selected = ['already_selected', 'selected_zero_size'].includes(mode) ? link : old;
  658. const content = node(selected.dataset.date);
  659. link.click = () => {clicks++; selected = link; content.dataset.date = link.dataset.date;};
  660. if (['disabled', 'zero_size_disabled'].includes(mode)) link.classList.add('input-async-disabilitato');
  661. if (mode === 'negative') link.classList.add('notAvailableDay');
  662. const final = {disabled: mode !== 'unguarded', dataset: {coordinateFinalGuard: 'enabled'}, click: () => finalClicks++};
  663. const document = {
  664. querySelectorAll(q) {
  665. if (q === '#idServizio') return [{value: mode === 'wrong_service' ? 'wrong' : '7002'}];
  666. if (q === '#btnPrenotaNoOtp') return [final];
  667. if (q === '.events a[data-date]') return mode === 'duplicate' ? [old, link, link] : [old, link];
  668. if (q === '.events a.selected') return [selected];
  669. if (q === '.events-content li.selected') return [content];
  670. throw Error('Unexpected selector');
  671. },
  672. querySelector(q) {if (q === '.selected') return selected; throw Error('Unexpected selector');},
  673. };
  674. const window = {
  675. location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it', pathname: '/BookingCalendar'},
  676. getComputedStyle: element => ({
  677. display: ['hidden', 'zero_size_hidden'].includes(mode) ? 'none' : 'block',
  678. visibility: 'visible', opacity: '1',
  679. pointerEvents: mode === 'zero_size_pointer_blocked' ||
  680. (mode === 'selected_zero_size' && element === selected) ? 'none' : 'auto',
  681. }),
  682. };
  683. const run = click => vm.runInNewContext('(function(){' + source + '\n}).apply(null, args)',
  684. {document, window, args: ['7002', '2026-10-13', click]}, {timeout: 1000});
  685. const before = run(false), acted = run(true), after = run(false);
  686. process.stdout.write(JSON.stringify({before, acted, after, clicks, finalClicks}));
  687. """
  688. @unittest.skipUnless(shutil.which("node"), "Node is required for the native-date script contract")
  689. class BookDateJavaScriptTests(unittest.TestCase):
  690. def run_case(self, mode):
  691. completed = subprocess.run([shutil.which("node"), "-e", DATE_JS_HARNESS],
  692. input=json.dumps({"source": DATE_SELECTION_SCRIPT, "mode": mode}),
  693. text=True, capture_output=True, timeout=10, check=True)
  694. return json.loads(completed.stdout)
  695. def test_native_date_selection_can_target_offscreen_timeline_and_never_final(self):
  696. result = self.run_case("positive")
  697. self.assertEqual(result["clicks"], 1)
  698. self.assertTrue(result["after"]["selectedMatches"])
  699. self.assertEqual(result["finalClicks"], 0)
  700. def test_already_selected_date_is_not_clicked_again(self):
  701. result = self.run_case("already_selected")
  702. self.assertEqual(result["clicks"], 0)
  703. self.assertTrue(result["before"]["selectedMatches"])
  704. def test_zero_size_enabled_dates_follow_native_click_and_readback(self):
  705. for mode in ("zero_width", "zero_height", "zero_size"):
  706. with self.subTest(mode=mode):
  707. result = self.run_case(mode)
  708. self.assertTrue(result["before"]["candidateEnabled"])
  709. self.assertEqual(result["clicks"], 1)
  710. self.assertTrue(result["after"]["selectedMatches"])
  711. self.assertEqual(result["finalClicks"], 0)
  712. def test_selected_zero_size_pointer_blocked_date_is_not_reclicked(self):
  713. result = self.run_case("selected_zero_size")
  714. self.assertTrue(result["before"]["selectedMatches"])
  715. self.assertFalse(result["before"]["candidateEnabled"])
  716. self.assertEqual(result["clicks"], 0)
  717. self.assertEqual(result["finalClicks"], 0)
  718. def test_guarded_native_date_action_rejects_unsafe_controls(self):
  719. for mode in ("disabled", "negative", "unguarded", "wrong_service", "wrong_origin", "duplicate", "hidden",
  720. "zero_size_disabled", "zero_size_hidden", "zero_size_pointer_blocked"):
  721. with self.subTest(mode=mode):
  722. result = self.run_case(mode)
  723. self.assertEqual(result["clicks"], 0)
  724. self.assertEqual(result["finalClicks"], 0)
  725. if __name__ == "__main__":
  726. unittest.main()