test_debug_ita_book_gate.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. import copy
  2. import ast
  3. import json
  4. import shutil
  5. import subprocess
  6. import tempfile
  7. import unittest
  8. from contextlib import ExitStack, redirect_stdout
  9. from io import StringIO
  10. from pathlib import Path
  11. from types import SimpleNamespace
  12. from unittest.mock import Mock, patch
  13. from plugins import ita_plugin as calendar_book
  14. from plugins.ita_plugin import AVAILABILITY_PATH, CALENDAR_PATH
  15. from plugins.ita_plugin import ItaPlugin
  16. from test.ita import test_debug_ita_calendar_gate as prep_fixtures
  17. from test.ita import test_debug_ita_production_query_gate as audit_fixtures
  18. from test.ita import test_ita_calendar_book_flow as flow_fixtures
  19. from tools import debug_ita_book_gate as gate
  20. from tools import debug_ita_calendar_gate as preparation
  21. from vs_types import AvailabilityStatus, VSBookResult, VSQueryResult
  22. ORIGIN = "https://prenotami.esteri.it"
  23. USERNAME = "applicant@example.test"
  24. PASSWORD = "private-test-pass"
  25. OTP = "012345"
  26. def gate_env():
  27. env = prep_fixtures.gate_env()
  28. env.update(ITA_BOOK_USERNAME=USERNAME, ITA_BOOK_PASSWORD=PASSWORD)
  29. return env
  30. class GateListener(flow_fixtures.FakeListener):
  31. def stop(self):
  32. # Installed DrissionPage stop() dereferences None on a repeated stop.
  33. if not self.listening:
  34. raise AttributeError("Fixture listener already stopped")
  35. super().stop()
  36. def start(self, targets, method):
  37. # The same listener is used for preparation and the real Book scanner.
  38. if targets in (preparation.OTP_PATH, self.page.booking_path):
  39. self.starts += 1
  40. self.target = targets
  41. self.queue.clear()
  42. self.listening = True
  43. self.page.events.append("listen-start")
  44. else:
  45. super().start(targets, method)
  46. class GateElement:
  47. def __init__(self, page, selector):
  48. self.page, self.selector = page, selector
  49. def input(self, value, *, clear):
  50. if self.selector != "#otp-input" or clear is not True:
  51. raise AssertionError("Unexpected input")
  52. self.page.otp_value = value if self.page.otp_write_matches else ""
  53. def run_js(self, script, value):
  54. if script != "return this.value === arguments[0];":
  55. raise AssertionError("Unexpected OTP readback")
  56. return self.page.otp_value == value
  57. def click(self):
  58. if self.selector == "#otp-input":
  59. return
  60. if self.selector == "#otp-send":
  61. self.page.otp_clicks += 1
  62. packet = self.page.preparation_packet(preparation.OTP_PATH, "GET")
  63. packet.url += "?ServiceID=" + str(self.page.service_id)
  64. packet.response.raw_body = json.dumps("SENT")
  65. self.page.emit(preparation.OTP_PATH, "GET")
  66. if self.page.duplicate_otp:
  67. self.page.emit(preparation.OTP_PATH, "GET")
  68. elif self.selector == "#btnAvanti":
  69. self.page.avanti_clicks += 1
  70. if self.page.auto_accept is not True:
  71. raise AssertionError("AVANTI confirmation was not enabled")
  72. packet = self.page.preparation_packet(self.page.booking_path, "POST")
  73. packet.response.status = self.page.avanti_status
  74. packet.response.url = ORIGIN + CALENDAR_PATH
  75. packet.response.headers = {"Location": CALENDAR_PATH + "?selectedService=fixture"}
  76. self.page.url = ORIGIN + CALENDAR_PATH
  77. self.page.emit(self.page.booking_path, "POST")
  78. if self.page.duplicate_avanti:
  79. self.page.emit(self.page.booking_path, "POST")
  80. # The original page's Calendar bootstrap is not Book's fresh scan.
  81. self.page.emit(AVAILABILITY_PATH, "POST")
  82. else:
  83. raise AssertionError("The gate must not click any other control")
  84. if self.page.preparation_mutator:
  85. self.page.preparation_mutator(packet, self.selector)
  86. self.page.listen.queue.append(packet)
  87. class GatePage(flow_fixtures.FlowPage):
  88. def __init__(self, months=None):
  89. super().__init__(months)
  90. self.url = ORIGIN + "/UserArea"
  91. self.service_id = 4937
  92. self.booking_path = "/Services/Booking/4937"
  93. self.driver = audit_fixtures.FakeDriver()
  94. self.listen = GateListener(self)
  95. self.set = SimpleNamespace(auto_handle_alert=self.auto_handle_alert)
  96. self.auto_accept = False
  97. self.alert_settings = []
  98. self.otp_value = ""
  99. self.otp_write_matches = True
  100. self.otp_clicks = self.avanti_clicks = 0
  101. self.duplicate_otp = self.duplicate_avanti = False
  102. self.avanti_status = 302
  103. self.preparation_mutator = None
  104. self.preflight_changes = {}
  105. self.preflight_hook = None
  106. self.commands = []
  107. def auto_handle_alert(self, on_off=True, accept=True):
  108. self.auto_accept = accept if on_off else False
  109. self.alert_settings.append(self.auto_accept)
  110. def run_cdp(self, name):
  111. self.commands.append(name)
  112. return {}
  113. def emit(self, path, method="POST"):
  114. if path.endswith("InsertNewBooking"):
  115. self.guard_final_count += 1
  116. callback = self.driver.immediate_event_handlers.get(preparation.CalendarRequestAudit.EVENT)
  117. if callback:
  118. callback(request={"url": ORIGIN + path, "method": method})
  119. def preparation_packet(self, path, method):
  120. return SimpleNamespace(
  121. tab_id=self.tab_id, is_failed=False, url=ORIGIN + path, method=method,
  122. response=SimpleNamespace(status=200, raw_body="", url=ORIGIN + path, headers={}),
  123. )
  124. def response_packet(self, path, body, items, day=None):
  125. self.emit(path)
  126. return super().response_packet(path, body, items, day)
  127. def ele(self, selector, timeout=None):
  128. if selector in ("#otp-send", "#otp-input", "#btnAvanti"):
  129. return GateElement(self, selector)
  130. return None
  131. def run_js(self, script, *args):
  132. if "coordinate:ita-book-gate-form-boundary" in script:
  133. if self.preflight_hook:
  134. self.preflight_hook()
  135. return prep_fixtures.booking_preflight_snapshot(
  136. formReady=self.url == ORIGIN + self.booking_path,
  137. otpValuePresent=bool(self.otp_value), otpSendEnabled=self.otp_clicks == 0,
  138. **self.preflight_changes,
  139. )
  140. if script == preparation.AVANTI_FAILURE_DIAGNOSTIC_SCRIPT:
  141. return {"path": self.url.removeprefix(ORIGIN), "otpValuePresent": bool(self.otp_value),
  142. "bookingFormPresent": self.url == ORIGIN + self.booking_path}
  143. return super().run_js(script, *args)
  144. def make_plugin(page):
  145. # No constructor, files, browser, real credentials, mail or external service.
  146. plugin = ItaPlugin.__new__(ItaPlugin)
  147. plugin.group_id = "offline-book-gate"
  148. plugin.logger = None
  149. plugin.page = page
  150. plugin._transient_user_data_path = "/unused/ita-book-gate-test"
  151. plugin.mouse = SimpleNamespace(human_click_ele=lambda element: element.click())
  152. plugin.session_create_time = 0
  153. plugin.is_healthy = False
  154. def create():
  155. plugin.session_create_time = 123.0
  156. plugin.is_healthy = True
  157. plugin.create_session = Mock(side_effect=create)
  158. plugin.cleanup = Mock()
  159. def enter(apt_type, **kwargs):
  160. page.url = ORIGIN + page.booking_path
  161. return VSQueryResult(success=True, apt_type=apt_type, availability_status=AvailabilityStatus.NoneAvailable)
  162. plugin._enter_service = Mock(side_effect=enter)
  163. plugin.query = Mock(side_effect=AssertionError("Book must not call public Query"))
  164. plugin.book = Mock(wraps=plugin.book)
  165. plugin._record_calendar_prepared_route = Mock(wraps=plugin._record_calendar_prepared_route)
  166. return plugin
  167. class BookGateFlowTests(unittest.TestCase):
  168. def run_gate(self, page=None, *, env=None, execute=True, inputs=None, configure=None,
  169. otp_reader=None, before=None, after=None, reservation_hook=None,
  170. use_local_query_account=False, verify_receipts=False, submit_once=False,
  171. final_confirm=lambda _: "no", review_reader=lambda _: ""):
  172. page = page or GatePage()
  173. plugin = make_plugin(page)
  174. # __del__ invokes cleanup again. Keep a fault-injection mock from raising
  175. # an unraisable exception after this test has already asserted its result.
  176. self.addCleanup(lambda: setattr(plugin.cleanup, "side_effect", None))
  177. if configure:
  178. configure(plugin, page)
  179. captured = StringIO()
  180. reservation_calls = []
  181. def reservations(_page):
  182. self.assertIs(_page, page)
  183. reservation_calls.append(True)
  184. if reservation_hook:
  185. reservation_hook(plugin, page, len(reservation_calls))
  186. return (before if len(reservation_calls) == 1 else after) or preparation.ReservationSnapshot(0, 0)
  187. with ExitStack() as stack:
  188. factory = stack.enter_context(patch.object(gate, "ItaPlugin", return_value=plugin))
  189. stack.enter_context(patch.object(gate, "resolve_chrome_path", return_value=Path("/fixture/Chrome")))
  190. stack.enter_context(patch.object(preparation, "read_reservation_snapshot", side_effect=reservations))
  191. stack.enter_context(patch.object(preparation.CalendarRequestAudit, "settled_snapshot", lambda audit: audit.snapshot()))
  192. stack.enter_context(patch.object(calendar_book, "click_next_month", side_effect=lambda _page: page.next_month()))
  193. stack.enter_context(patch.object(calendar_book.time, "sleep"))
  194. stack.enter_context(patch.dict(gate.os.environ, {}, clear=True))
  195. stack.enter_context(redirect_stdout(captured))
  196. code = gate.run_book_gate(env or gate_env(), execute=execute, user_inputs=inputs,
  197. otp_reader=otp_reader or (lambda: OTP),
  198. use_local_query_account=use_local_query_account,
  199. verify_receipts=verify_receipts, submit_once=submit_once,
  200. final_confirm=final_confirm, review_reader=review_reader)
  201. output = captured.getvalue()
  202. lines = [line for line in output.splitlines() if line.startswith("ITA_BOOK_GATE_RESULT=")]
  203. report = json.loads(lines[-1].split("=", 1)[1]) if lines else None
  204. return SimpleNamespace(code=code, report=report, output=output, plugin=plugin,
  205. page=page, factory=factory, reservation_calls=reservation_calls)
  206. def assert_clean(self, result):
  207. result.plugin.cleanup.assert_called_once()
  208. self.assertFalse(result.page.listen.listening)
  209. self.assertNotIn(preparation.CalendarRequestAudit.EVENT, result.page.driver.immediate_event_handlers)
  210. self.assertFalse(result.page.auto_accept)
  211. self.assertEqual(result.page.guard_final_count, 0)
  212. def test_production_failures_are_distinct_and_diagnostic_precedes_reconciliation(self):
  213. cases = (
  214. ("Book date control was not ready before timeout", "date_control_timeout"),
  215. ("Book TimeSlots request does not match the current service", "timeslot_service_mismatch"),
  216. ("Book slot DOM did not match the response before timeout", "slot_dom_timeout"),
  217. ("Book precommit rejected (precommit_rejected)", "precommit_readback_rejected"),
  218. )
  219. for message, reason in cases:
  220. with self.subTest(reason=reason):
  221. page = GatePage()
  222. seen = []
  223. original = page.run_js
  224. def read(script, *args):
  225. if script == gate.BOOK_FAILURE_STATE_SCRIPT:
  226. seen.append(True)
  227. return book_failure_state()
  228. return original(script, *args)
  229. def reconcile(plugin, page, count):
  230. if count == 2:
  231. self.assertEqual(seen, [True])
  232. page.run_js = read
  233. with patch.object(calendar_book, "_try_day", side_effect=calendar_book.CalendarBookError(message)):
  234. result = self.run_gate(page, reservation_hook=reconcile)
  235. self.assertEqual(result.code, 1, result.output)
  236. self.assertIn(f'"reason": "{reason}"', result.output)
  237. self.assertIn('"readSucceeded": true', result.output)
  238. self.assertEqual(result.report["calendarBookCalls"], 1)
  239. self.assertEqual(result.report["requests"]["finalRequests"], 0)
  240. self.assertEqual(result.report["requests"]["otpRequests"], 1)
  241. self.assertEqual(result.report["requests"]["avantiPosts"], 1)
  242. self.assertEqual(page.clicks, 0)
  243. self.assert_clean(result)
  244. def test_production_diagnostic_failure_does_not_replace_original_reason(self):
  245. # GatePage deliberately has no implementation of this diagnostic script.
  246. with patch.object(calendar_book, "_try_day", side_effect=calendar_book.CalendarBookError(
  247. "Book slot click was not acknowledged",
  248. )):
  249. result = self.run_gate()
  250. self.assertEqual(result.code, 1)
  251. self.assertIn('"reason": "slot_click_not_acknowledged"', result.output)
  252. self.assertIn('"readSucceeded": false', result.output)
  253. self.assert_clean(result)
  254. def test_full_gate_uses_real_book_and_stops_before_final(self):
  255. result = self.run_gate()
  256. self.assertEqual(result.code, 0, result.output)
  257. report = result.report
  258. self.assertIs(report["passed"], True)
  259. self.assertEqual(report["outcome"], "pre_final")
  260. self.assertEqual((report["entryBookCalls"], report["calendarBookCalls"]), (1, 1))
  261. self.assertEqual(report["requests"], {"otpRequests": 1, "avantiPosts": 1,
  262. "availabilityRequests": 2, "finalRequests": 0})
  263. self.assertEqual(report["bookRequestDelta"], {"otpRequests": 0, "avantiPosts": 0,
  264. "availabilityRequests": 1, "finalRequests": 0})
  265. self.assertEqual(report["selectedDate"], "2026-10-13")
  266. self.assertEqual(report["selectedTime"], "10:05 - 11:05")
  267. self.assertIs(report["bookResultSuccess"], False)
  268. self.assertEqual(result.plugin.book.call_count, 2)
  269. result.plugin._enter_service.assert_called_once()
  270. result.plugin.query.assert_not_called()
  271. self.assertEqual(result.page.clicks, 1)
  272. self.assertEqual(result.page.otp_value, OTP)
  273. self.assertEqual(result.page.alert_settings, [True, False])
  274. self.assertEqual(result.plugin._prepared_calendar.role, "book")
  275. self.assertEqual(result.plugin._record_calendar_prepared_route.call_count, 1)
  276. self.assertEqual(len(result.reservation_calls), 2)
  277. self.assert_clean(result)
  278. for secret in (USERNAME, PASSWORD, OTP, "80000113"):
  279. self.assertNotIn(secret, result.output)
  280. def test_receipt_baseline_mode_is_retired_before_browser_creation(self):
  281. with patch.object(gate, "_book_credentials") as credentials:
  282. result = self.run_gate(execute=False, verify_receipts=True)
  283. self.assertEqual(result.code, 1)
  284. self.assertIn("Receipt-baseline mode is no longer", result.output)
  285. credentials.assert_not_called()
  286. result.factory.assert_not_called()
  287. def test_submit_once_preflight_is_local_and_needs_no_persistent_fence(self):
  288. with patch.object(gate, "_book_credentials") as credentials:
  289. result = self.run_gate(execute=False, submit_once=True)
  290. self.assertEqual(result.code, 0, result.output)
  291. credentials.assert_not_called()
  292. result.factory.assert_not_called()
  293. def test_submit_once_delegates_to_one_production_result(self):
  294. page = GatePage()
  295. class FinalRun:
  296. def __init__(self, plugin, route, **_kwargs):
  297. self.plugin, self.route = plugin, route
  298. self.possibly_submitted = False
  299. self.result = None
  300. self.report = {
  301. "attempted": False, "automaticRetry": True,
  302. "bookingConfirmed": False, "outcome": "not_submitted",
  303. }
  304. def execute(self, **_kwargs):
  305. self.possibly_submitted = True
  306. page.emit("/BookingCalendar/InsertNewBooking", "POST")
  307. self.result = VSBookResult(
  308. success=True, account=USERNAME, book_date="2026-10-13",
  309. book_time="10:05 - 11:05",
  310. )
  311. self.report.update(
  312. attempted=True, bookingConfirmed=True, outcome="confirmed",
  313. confirmedDate=self.result.book_date, confirmedTime=self.result.book_time,
  314. )
  315. return self.report
  316. with patch.object(gate.final_evidence, "FinalEvidenceRun", FinalRun):
  317. result = self.run_gate(
  318. page, submit_once=True,
  319. before=preparation.ReservationSnapshot(1, 0),
  320. after=preparation.ReservationSnapshot(1, 0),
  321. )
  322. self.assertEqual(result.code, 0, result.output)
  323. self.assertTrue(result.report["passed"])
  324. self.assertTrue(result.report["bookResultSuccess"])
  325. self.assertEqual(result.report["requests"]["finalRequests"], 1)
  326. self.assertTrue(result.report["finalEvidence"]["automaticRetry"])
  327. result.plugin.cleanup.assert_called_once()
  328. self.assertFalse(result.page.listen.listening)
  329. self.assertFalse(result.page.driver.immediate_event_handlers)
  330. self.assertEqual(result.page.guard_final_count, 1)
  331. def test_final_cli_flag_is_forwarded_without_receipt_requirement(self):
  332. with patch.object(gate, "run_book_gate", return_value=0) as runner:
  333. self.assertEqual(gate.main(["--preflight", "--submit-once"]), 0)
  334. self.assertIs(runner.call_args.kwargs["submit_once"], True)
  335. self.assertIs(runner.call_args.kwargs["verify_receipts"], False)
  336. self.assertIs(runner.call_args.kwargs["execute"], False)
  337. def test_followed_redirect_200_is_accepted(self):
  338. page = GatePage()
  339. page.avanti_status = 200
  340. result = self.run_gate(page)
  341. self.assertEqual(result.code, 0, result.output)
  342. self.assertIn("followed_redirect_200", result.output)
  343. self.assert_clean(result)
  344. def test_config_not_geography_controls_route(self):
  345. env = gate_env()
  346. env.update(ITA_ROUTING_KEY="slot.other.it.tourist", ITA_CITY="Another City", ITA_SERVICE_ID="9001")
  347. page = GatePage()
  348. page.service_id, page.booking_path = 9001, "/Services/Booking/9001"
  349. result = self.run_gate(page, env=env)
  350. self.assertEqual(result.code, 0, result.output)
  351. self.assertEqual(result.plugin._prepared_calendar.route.service_id, 9001)
  352. def test_default_preflight_does_not_load_credentials_or_create_browser(self):
  353. for reuse in (False, True):
  354. with self.subTest(reuse=reuse), patch.object(
  355. gate, "_book_credentials", side_effect=AssertionError("No credential access")
  356. ), patch.object(gate, "load_local_account") as loader:
  357. result = self.run_gate(execute=False, use_local_query_account=reuse)
  358. self.assertEqual(result.code, 0, result.output)
  359. loader.assert_not_called()
  360. result.factory.assert_not_called()
  361. result.plugin.create_session.assert_not_called()
  362. self.assertEqual(result.reservation_calls, [])
  363. def test_local_account_reuse_still_uses_independent_prefinal_book_flow(self):
  364. with patch.object(gate, "load_local_account", return_value=SimpleNamespace(
  365. username=USERNAME, password=PASSWORD,
  366. )) as loader, patch.object(gate, "_get_credentials") as prompt:
  367. result = self.run_gate(use_local_query_account=True)
  368. loader.assert_called_once_with(gate.ITA_QUERY_ACCOUNT_FILE)
  369. prompt.assert_not_called()
  370. self.assertEqual(result.code, 0, result.output)
  371. self.assertTrue(result.report["passed"])
  372. self.assertFalse(result.report["bookResultSuccess"])
  373. self.assertEqual(result.report["requests"]["finalRequests"], 0)
  374. self.assertEqual(result.plugin.config.account.username, USERNAME)
  375. self.assertEqual(result.plugin._prepared_calendar.role, "book")
  376. self.assertIsNone(result.plugin.free_config.get(gate.PERSISTENT_BROWSER_PROFILE_KEY))
  377. self.assertEqual(result.plugin.book.call_count, 2)
  378. self.assertIn("source=local_query_file", result.output)
  379. for secret in (USERNAME, PASSWORD, OTP):
  380. self.assertNotIn(secret, result.output)
  381. self.assert_clean(result)
  382. def test_invalid_local_account_stops_before_browser_without_fallback(self):
  383. with patch.object(gate, "load_local_account", side_effect=gate.LocalAccountConfigurationError(
  384. f"untrusted loader detail {USERNAME} {PASSWORD}",
  385. )), patch.object(gate, "_get_credentials") as prompt:
  386. result = self.run_gate(use_local_query_account=True)
  387. self.assertEqual(result.code, 1)
  388. self.assertFalse(result.report["passed"])
  389. result.factory.assert_not_called()
  390. result.plugin.create_session.assert_not_called()
  391. prompt.assert_not_called()
  392. self.assertEqual(result.page.otp_clicks, 0)
  393. self.assertEqual(result.page.avanti_clicks, 0)
  394. self.assertEqual(result.reservation_calls, [])
  395. self.assertIn("applicant_credentials", result.output)
  396. for secret in (USERNAME, PASSWORD, "untrusted loader detail"):
  397. self.assertNotIn(secret, result.output)
  398. def test_calendar_service_failure_retains_business_exit_and_safe_diagnostic(self):
  399. page = GatePage()
  400. page.context_count = 0
  401. result = self.run_gate(page)
  402. self.assertEqual(result.code, 1, result.output)
  403. self.assertFalse(result.report["passed"])
  404. self.assertEqual(result.report["calendarBookCalls"], 0)
  405. self.assertEqual(result.report["requests"], {
  406. "otpRequests": 1, "avantiPosts": 1, "availabilityRequests": 1, "finalRequests": 0,
  407. })
  408. diagnostic = json.loads(next(line.split("=", 1)[1] for line in result.output.splitlines()
  409. if line.startswith("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=")))
  410. self.assertEqual(diagnostic["controlCount"], 0)
  411. self.assertTrue(diagnostic["readSucceeded"])
  412. self.assertTrue(diagnostic["afterFailure"])
  413. self.assertIn('"reason": "calendar_service_unidentified"', result.output)
  414. self.assertNotIn("cleanup_listener", result.output)
  415. self.assertEqual(page.listen.stops, 2) # OTP and AVANTI; no third stop.
  416. self.assert_clean(result)
  417. def test_calendar_identifier_shapes_stay_rejected_without_logging_values(self):
  418. for value in ("", " ", "x" * 129, 7002, None):
  419. with self.subTest(value_type=type(value).__name__), patch.object(
  420. gate, "CALENDAR_READY_TIMEOUT_SECONDS", 0,
  421. ):
  422. page = GatePage()
  423. page.service = value
  424. result = self.run_gate(page)
  425. self.assertEqual(result.code, 1, result.output)
  426. self.assertEqual(result.report["calendarBookCalls"], 0)
  427. reason = "calendar_service_not_ready" if value == "" else "calendar_service_unidentified"
  428. self.assertIn(f'"reason": "{reason}"', result.output)
  429. diagnostic = json.loads(next(line.split("=", 1)[1] for line in result.output.splitlines()
  430. if line.startswith("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=")))
  431. self.assertEqual(diagnostic["valueType"], type(value).__name__)
  432. self.assertEqual(diagnostic["valueLength"], len(value) if isinstance(value, str) else None)
  433. self.assertFalse(diagnostic["valueAccepted"])
  434. self.assertNotIn("value", diagnostic)
  435. self.assertNotIn("x" * 129, result.output)
  436. self.assert_clean(result)
  437. def test_calendar_initialization_can_finish_after_document_loaded(self):
  438. page = GatePage()
  439. original_run_js = page.run_js
  440. reads = []
  441. def delayed(script, *args):
  442. result = original_run_js(script, *args)
  443. if script == calendar_book.RUNTIME_SERVICE_SCRIPT:
  444. reads.append(True)
  445. if len(reads) == 1:
  446. return {**result, "value": ""}
  447. return result
  448. page.run_js = delayed
  449. result = self.run_gate(page)
  450. self.assertEqual(result.code, 0, result.output)
  451. self.assertGreater(len(reads), 1)
  452. self.assertEqual(result.report["calendarBookCalls"], 1)
  453. self.assertEqual(result.report["requests"]["otpRequests"], 1)
  454. self.assertEqual(result.report["requests"]["avantiPosts"], 1)
  455. self.assertEqual(result.report["requests"]["finalRequests"], 0)
  456. self.assert_clean(result)
  457. def test_diagnostic_read_failure_does_not_replace_the_primary_error(self):
  458. page = GatePage()
  459. original_run_js = page.run_js
  460. def run_js(script, *args):
  461. if script == calendar_book.RUNTIME_SERVICE_SCRIPT:
  462. raise RuntimeError(f"{USERNAME} {PASSWORD} private-response")
  463. return original_run_js(script, *args)
  464. page.run_js = run_js
  465. result = self.run_gate(page)
  466. self.assertEqual(result.code, 1, result.output)
  467. self.assertIn('"readSucceeded": false', result.output)
  468. self.assertIn('"reason": "calendar_service_unidentified"', result.output)
  469. for secret in (USERNAME, PASSWORD, "private-response"):
  470. self.assertNotIn(secret, result.output)
  471. self.assert_clean(result)
  472. def test_active_listener_cleanup_failure_is_not_silenced(self):
  473. def reservation_hook(plugin, page, count):
  474. if count == 2:
  475. page.listen.listening = True
  476. page.listen.stop = Mock(side_effect=AttributeError("active listener failed"))
  477. result = self.run_gate(reservation_hook=reservation_hook)
  478. self.assertEqual(result.code, 3)
  479. self.assertFalse(result.report["passed"])
  480. self.assertIn("cleanup_listener", result.output)
  481. result.page.listen.stop.assert_called_once()
  482. result.plugin.cleanup.assert_called_once()
  483. self.assertNotIn(preparation.CalendarRequestAudit.EVENT,
  484. result.page.driver.immediate_event_handlers)
  485. self.assertEqual(result.page.guard_final_count, 0)
  486. def test_no_route_fallback_is_allowed(self):
  487. for name in prep_fixtures.gate_env():
  488. with self.subTest(missing=name):
  489. env = gate_env()
  490. del env[name]
  491. result = self.run_gate(env=env)
  492. self.assertEqual(result.code, 1)
  493. result.factory.assert_not_called()
  494. def test_bad_preferences_fail_before_credentials(self):
  495. for inputs in ({"expected_start_date": "20260230"}, {"username": "query@example.test"},
  496. {"expected_start_date": "2026-11-01", "expected_end_date": "2026-10-01"}):
  497. with self.subTest(inputs=inputs), patch.object(gate, "_book_credentials") as credentials:
  498. result = self.run_gate(inputs=inputs)
  499. self.assertEqual(result.code, 1)
  500. credentials.assert_not_called()
  501. result.factory.assert_not_called()
  502. def test_preferences_reach_real_book_without_changing_input(self):
  503. page = GatePage([flow_fixtures.month("2026-10", {13: 1, 14: 1})])
  504. inputs = {"expected_start_date": "2026-10-14", "expected_end_date": "2026-10-14"}
  505. original = copy.deepcopy(inputs)
  506. result = self.run_gate(page, inputs=inputs)
  507. self.assertEqual(result.code, 0, result.output)
  508. self.assertEqual(result.report["selectedDate"], "2026-10-14")
  509. self.assertEqual(page.date_clicks, ["2026-10-14"])
  510. self.assertEqual(inputs, original)
  511. def test_entry_unavailable_does_not_send_otp(self):
  512. def configure(plugin, page):
  513. plugin._enter_service = Mock(return_value=VSQueryResult(success=False))
  514. result = self.run_gate(configure=configure)
  515. self.assertEqual(result.code, 2, result.output)
  516. self.assertFalse(result.report["passed"])
  517. self.assertEqual(result.report["calendarBookCalls"], 0)
  518. self.assertEqual(result.page.otp_clicks, 0)
  519. self.assert_clean(result)
  520. def test_calendar_no_inventory_is_not_a_positive_gate(self):
  521. page = GatePage([flow_fixtures.month("2026-10", {13: 0})])
  522. result = self.run_gate(page, inputs={"expected_end_date": "2026-10-31"})
  523. self.assertEqual(result.code, 2, result.output)
  524. self.assertFalse(result.report["selectionVerified"])
  525. self.assertFalse(result.report["passed"])
  526. self.assertEqual(page.clicks, 0)
  527. self.assert_clean(result)
  528. def test_form_preflight_failure_does_not_send_otp(self):
  529. page = GatePage()
  530. page.preflight_changes = {"formReady": False}
  531. result = self.run_gate(page)
  532. self.assertEqual(result.code, 1)
  533. self.assertEqual(page.otp_clicks, 0)
  534. self.assert_clean(result)
  535. def test_otp_must_really_be_written_before_avanti(self):
  536. page = GatePage()
  537. page.otp_write_matches = False
  538. result = self.run_gate(page)
  539. self.assertEqual(result.code, 1)
  540. self.assertEqual((page.otp_clicks, page.avanti_clicks), (1, 0))
  541. self.assert_clean(result)
  542. def test_bad_manual_code_never_retries_or_reaches_avanti(self):
  543. for value in ("", "123456", "123 abc", None):
  544. with self.subTest(value=value):
  545. result = self.run_gate(otp_reader=lambda: value)
  546. self.assertEqual(result.code, 1)
  547. self.assertEqual((result.page.otp_clicks, result.page.avanti_clicks), (1, 0))
  548. self.assert_clean(result)
  549. def test_cancel_at_manual_otp_reconciles_and_cleans_without_retry(self):
  550. reader = Mock(side_effect=KeyboardInterrupt)
  551. result = self.run_gate(otp_reader=reader)
  552. self.assertEqual(result.code, 130)
  553. self.assertEqual((result.page.otp_clicks, result.page.avanti_clicks), (1, 0))
  554. self.assertEqual(len(result.reservation_calls), 2)
  555. self.assert_clean(result)
  556. def test_eof_at_manual_otp_is_safe_cancellation(self):
  557. result = self.run_gate(otp_reader=Mock(side_effect=EOFError))
  558. self.assertEqual(result.code, 130)
  559. self.assert_clean(result)
  560. def test_duplicate_otp_is_detected_before_reading_code(self):
  561. page = GatePage()
  562. page.duplicate_otp = True
  563. reader = Mock(return_value=OTP)
  564. result = self.run_gate(page, otp_reader=reader)
  565. self.assertEqual(result.code, 1)
  566. reader.assert_not_called()
  567. self.assertEqual(page.avanti_clicks, 0)
  568. self.assertEqual(result.report["requests"]["otpRequests"], 2)
  569. self.assert_clean(result)
  570. def test_duplicate_avanti_never_records_prepared_context(self):
  571. page = GatePage()
  572. page.duplicate_avanti = True
  573. result = self.run_gate(page)
  574. self.assertEqual(result.code, 1)
  575. result.plugin._record_calendar_prepared_route.assert_not_called()
  576. self.assertEqual(page.refreshes, 0)
  577. self.assert_clean(result)
  578. def test_preparation_packets_are_bound_to_tab_service_and_response(self):
  579. changes = (
  580. lambda packet: setattr(packet, "tab_id", "old-query-tab"),
  581. lambda packet: setattr(packet, "is_failed", True),
  582. lambda packet: setattr(packet.response, "status", True),
  583. lambda packet: setattr(packet, "url", ORIGIN + preparation.OTP_PATH + "?ServiceID=9001"),
  584. lambda packet: setattr(packet.response, "raw_body", json.dumps("NOT_SENT")),
  585. )
  586. for index, mutate in enumerate(changes):
  587. with self.subTest(index=index):
  588. page = GatePage()
  589. page.preparation_mutator = lambda packet, selector: mutate(packet) if selector == "#otp-send" else None
  590. result = self.run_gate(page)
  591. self.assertEqual(result.code, 1)
  592. self.assertEqual(page.avanti_clicks, 0)
  593. self.assert_clean(result)
  594. def test_avanti_wrong_tab_or_transition_does_not_attest_calendar(self):
  595. for variant in ("wrong-tab", "wrong-target", "bad-status", "response-form"):
  596. with self.subTest(variant=variant):
  597. page = GatePage()
  598. def mutate(packet, selector):
  599. if selector != "#btnAvanti":
  600. return
  601. if variant == "wrong-tab":
  602. packet.tab_id = "another-tab"
  603. elif variant == "wrong-target":
  604. packet.response.headers["Location"] = "https://other.example/BookingCalendar"
  605. elif variant == "bad-status":
  606. packet.response.status = 500
  607. else:
  608. packet.response.status = 200
  609. packet.response.url = ORIGIN + page.booking_path
  610. page.preparation_mutator = mutate
  611. result = self.run_gate(page)
  612. self.assertEqual(result.code, 1)
  613. result.plugin._record_calendar_prepared_route.assert_not_called()
  614. self.assertEqual(page.refreshes, 0)
  615. self.assert_clean(result)
  616. def test_avanti_timeout_does_not_repeat_and_disables_auto_accept(self):
  617. with patch.object(preparation, "_wait_for_calendar", side_effect=preparation.CalendarGateError("timeout")):
  618. result = self.run_gate()
  619. self.assertEqual(result.code, 1)
  620. self.assertEqual(result.page.avanti_clicks, 1)
  621. self.assertEqual(result.page.alert_settings, [True, False])
  622. self.assert_clean(result)
  623. def test_account_route_tab_and_login_drift_stop_before_otp(self):
  624. mutations = (
  625. lambda plugin, page: setattr(plugin.config.account, "username", "other@example.test"),
  626. lambda plugin, page: setattr(page, "tab_id", "other-tab"),
  627. lambda plugin, page: setattr(plugin, "session_create_time", 124.0),
  628. lambda plugin, page: plugin.free_config.update(final_submit_enabled=True),
  629. lambda plugin, page: setattr(plugin, "_prepared_calendar", SimpleNamespace(role="query")),
  630. lambda plugin, page: plugin.free_config["apt_configs"]["slot.hkg.it.tourist"].update(service_id=9001),
  631. )
  632. for index, mutate in enumerate(mutations):
  633. with self.subTest(index=index):
  634. def configure(plugin, page):
  635. page.preflight_hook = lambda: mutate(plugin, page)
  636. result = self.run_gate(configure=configure)
  637. self.assertEqual(result.code, 1)
  638. self.assertEqual(result.page.otp_clicks, 0)
  639. self.assert_clean(result)
  640. def test_account_change_while_reading_otp_does_not_write_code(self):
  641. state = {}
  642. def configure(plugin, page):
  643. state["plugin"] = plugin
  644. def reader():
  645. state["plugin"].config.account.username = "another@example.test"
  646. return OTP
  647. result = self.run_gate(configure=configure, otp_reader=reader)
  648. self.assertEqual(result.code, 1)
  649. self.assertEqual(result.page.otp_value, "")
  650. self.assertEqual(result.page.avanti_clicks, 0)
  651. self.assert_clean(result)
  652. def test_existing_calendar_is_not_accepted_as_a_fresh_login(self):
  653. page = GatePage()
  654. page.url = ORIGIN + CALENDAR_PATH
  655. result = self.run_gate(page)
  656. self.assertEqual(result.code, 1)
  657. result.plugin.book.assert_not_called()
  658. self.assertEqual(page.otp_clicks, 0)
  659. def test_unexpected_book_success_is_never_reported_as_gate_success(self):
  660. def configure(plugin, page):
  661. plugin.book = Mock(return_value=VSBookResult(success=True, urn="private-reservation"))
  662. result = self.run_gate(configure=configure)
  663. self.assertEqual(result.code, 1)
  664. self.assertEqual(result.page.otp_clicks, 0)
  665. self.assertNotIn("private-reservation", result.output)
  666. self.assert_clean(result)
  667. def test_lost_selection_after_book_is_not_clicked_again(self):
  668. def configure(plugin, page):
  669. original = plugin.book
  670. def call(*args, **kwargs):
  671. result = original(*args, **kwargs)
  672. if page.url.endswith(CALENDAR_PATH):
  673. page.active = False
  674. return result
  675. plugin.book = Mock(side_effect=call)
  676. result = self.run_gate(configure=configure)
  677. self.assertEqual(result.code, 1)
  678. self.assertEqual(result.page.clicks, 1)
  679. self.assert_clean(result)
  680. def test_otp_during_book_fails_audit_without_repeating_preparation(self):
  681. page = GatePage()
  682. original = page.refresh
  683. def refresh():
  684. original()
  685. page.emit(preparation.OTP_PATH, "GET")
  686. page.refresh = refresh
  687. result = self.run_gate(page)
  688. self.assertEqual(result.code, 1)
  689. self.assertEqual((page.otp_clicks, page.avanti_clicks), (1, 1))
  690. self.assertFalse(result.report["passed"])
  691. self.assert_clean(result)
  692. def test_final_request_after_avanti_is_detected_before_book(self):
  693. page = GatePage()
  694. page.preparation_mutator = lambda packet, selector: (
  695. page.emit("/BookingCalendar/InsertNewBooking") if selector == "#btnAvanti" else None
  696. )
  697. result = self.run_gate(page)
  698. self.assertEqual(result.code, 1)
  699. result.plugin._record_calendar_prepared_route.assert_not_called()
  700. self.assertEqual(page.refreshes, 0)
  701. self.assertEqual(result.report["requests"]["finalRequests"], 1)
  702. self.assertFalse(page.auto_accept)
  703. def test_reservation_change_prevents_positive_gate(self):
  704. result = self.run_gate(after=preparation.ReservationSnapshot(1, 0))
  705. self.assertEqual(result.code, 1)
  706. self.assertFalse(result.report["passed"])
  707. self.assert_clean(result)
  708. def test_waitlist_change_prevents_positive_gate(self):
  709. result = self.run_gate(after=preparation.ReservationSnapshot(0, 1))
  710. self.assertEqual(result.code, 1)
  711. self.assertFalse(result.report["passed"])
  712. def test_late_business_request_during_reconciliation_is_detected(self):
  713. def hook(plugin, page, count):
  714. if count == 2:
  715. page.emit(AVAILABILITY_PATH)
  716. result = self.run_gate(reservation_hook=hook)
  717. self.assertEqual(result.code, 1)
  718. self.assertFalse(result.report["passed"])
  719. self.assert_clean(result)
  720. def test_failed_read_only_reconciliation_does_not_publish_passed(self):
  721. def hook(plugin, page, count):
  722. if count == 2:
  723. raise RuntimeError("private-state")
  724. result = self.run_gate(reservation_hook=hook)
  725. self.assertEqual(result.code, 1)
  726. self.assertNotIn("private-state", result.output)
  727. self.assert_clean(result)
  728. def test_cleanup_failure_has_distinct_return_code(self):
  729. def configure(plugin, page):
  730. plugin.cleanup.side_effect = RuntimeError("private browser details")
  731. result = self.run_gate(configure=configure)
  732. self.assertEqual(result.code, 3)
  733. self.assertFalse(result.report["passed"])
  734. self.assertNotIn("private browser details", result.output)
  735. def test_provider_exception_does_not_log_credentials_code_or_body(self):
  736. def configure(plugin, page):
  737. plugin.create_session.side_effect = RuntimeError(f"{USERNAME} {PASSWORD} {OTP} BODY private")
  738. result = self.run_gate(configure=configure)
  739. self.assertEqual(result.code, 1)
  740. for secret in (USERNAME, PASSWORD, OTP, "BODY private"):
  741. self.assertNotIn(secret, result.output)
  742. result.plugin.cleanup.assert_called_once()
  743. class BookGateInputTests(unittest.TestCase):
  744. def test_cleanup_avoids_installed_sdk_duplicate_stop_failure(self):
  745. from DrissionPage._units.listener import Listener
  746. listener = Listener.__new__(Listener)
  747. listener.listening = False
  748. driver = listener._driver = Mock()
  749. listener.stop()
  750. driver.stop.assert_called_once()
  751. self.assertIsNone(listener._driver)
  752. # Prove the actual SDK failure, then exercise our guarded cleanup.
  753. with self.assertRaises(AttributeError):
  754. listener.stop()
  755. gate._stop_listener_if_active(SimpleNamespace(listen=listener))
  756. driver.stop.assert_called_once()
  757. def test_cleanup_stops_an_active_listener(self):
  758. listener = SimpleNamespace(listening=True, stop=Mock())
  759. gate._stop_listener_if_active(SimpleNamespace(listen=listener))
  760. listener.stop.assert_called_once()
  761. def test_diagnostic_only_reads_the_calendar_and_never_emits_service_value(self):
  762. for path in ("/BookingCalendar", "/Services"):
  763. with self.subTest(path=path):
  764. page = SimpleNamespace(url=ORIGIN + path, run_js=Mock(return_value={
  765. "path": path, "count": 1, "value": PASSWORD,
  766. }))
  767. captured = StringIO()
  768. with redirect_stdout(captured):
  769. gate._print_calendar_preparation_diagnostic(page)
  770. self.assertNotIn(PASSWORD, captured.getvalue())
  771. diagnostic = json.loads(captured.getvalue().split("=", 1)[1])
  772. if path == "/BookingCalendar":
  773. self.assertEqual(diagnostic["valueLength"], len(PASSWORD))
  774. page.run_js.assert_called_once_with(calendar_book.RUNTIME_SERVICE_SCRIPT)
  775. else:
  776. self.assertFalse(diagnostic["pathMatches"])
  777. page.run_js.assert_not_called()
  778. def test_preparation_reasons_only_allow_exact_known_messages(self):
  779. for message, reason in (*gate._PREPARATION_FAILURES.items(), (PASSWORD, None)):
  780. with self.subTest(reason=reason):
  781. captured = StringIO()
  782. with redirect_stdout(captured):
  783. gate._failure("calendar_preparation", gate.BizLogicError(message))
  784. failure = json.loads(captured.getvalue().split("=", 1)[1])
  785. self.assertEqual(failure.get("reason"), reason)
  786. self.assertNotIn(PASSWORD, captured.getvalue())
  787. def test_credentials_project_only_book_fields(self):
  788. env = {"ITA_USERNAME": "query@example.test", "ITA_PASSWORD": "query-secret",
  789. "ITA_BOOK_USERNAME": USERNAME, "ITA_BOOK_PASSWORD": PASSWORD}
  790. with patch.object(gate, "_get_credentials", return_value=(USERNAME, PASSWORD)) as helper, \
  791. patch.object(gate, "load_local_account") as loader, redirect_stdout(StringIO()):
  792. self.assertEqual(gate._book_credentials(env), (USERNAME, PASSWORD))
  793. helper.assert_called_once_with({"ITA_USERNAME": USERNAME, "ITA_PASSWORD": PASSWORD}, non_interactive=False)
  794. loader.assert_not_called()
  795. def test_query_credentials_do_not_supply_fallback(self):
  796. with patch.object(gate, "_get_credentials", return_value=(USERNAME, PASSWORD)) as helper, \
  797. patch.object(gate, "load_local_account") as loader, redirect_stdout(StringIO()):
  798. gate._book_credentials({"ITA_USERNAME": "query@example.test", "ITA_PASSWORD": "query-secret"})
  799. helper.assert_called_once_with({"ITA_USERNAME": "", "ITA_PASSWORD": ""}, non_interactive=False)
  800. loader.assert_not_called()
  801. def test_local_account_opt_in_uses_complete_saved_pair_and_never_prompts(self):
  802. env = {"ITA_BOOK_USERNAME": "other@example.test", "ITA_BOOK_PASSWORD": "other-pass",
  803. "ITA_USERNAME": "general@example.test", "ITA_PASSWORD": "general-pass"}
  804. captured = StringIO()
  805. with patch.object(gate, "load_local_account", return_value=SimpleNamespace(
  806. username=USERNAME, password=PASSWORD,
  807. )) as loader, patch.object(gate, "_get_credentials") as prompt, redirect_stdout(captured):
  808. self.assertEqual(
  809. gate._book_credentials(env, use_local_query_account=True), (USERNAME, PASSWORD),
  810. )
  811. loader.assert_called_once_with(gate.ITA_QUERY_ACCOUNT_FILE)
  812. prompt.assert_not_called()
  813. self.assertIn("source=local_query_file", captured.getvalue())
  814. for secret in (USERNAME, PASSWORD, *env.values()):
  815. self.assertNotIn(secret, captured.getvalue())
  816. def test_local_loader_errors_are_safe_and_never_switch_credentials(self):
  817. for reason in ("missing file", "unsafe permissions", "invalid JSON", "missing password"):
  818. with self.subTest(reason=reason), patch.object(
  819. gate, "load_local_account",
  820. side_effect=gate.LocalAccountConfigurationError(f"{reason} {PASSWORD}"),
  821. ), patch.object(gate, "_get_credentials") as prompt:
  822. with self.assertRaises(gate.BookGateError) as caught:
  823. gate._book_credentials(gate_env(), use_local_query_account=True)
  824. prompt.assert_not_called()
  825. self.assertNotIn(PASSWORD, str(caught.exception))
  826. self.assertIn("config/ita_query_account.local.json", str(caught.exception))
  827. def test_local_secrets_are_not_part_of_source_fingerprint(self):
  828. self.assertNotIn(gate.ITA_QUERY_ACCOUNT_FILE, gate.BOOK_GATE_SOURCE_PATHS)
  829. self.assertIn(gate.REPO_ROOT / "utils" / "local_account.py", gate.BOOK_GATE_SOURCE_PATHS)
  830. def test_cli_defaults_to_no_external_actions(self):
  831. with patch.object(gate, "run_book_gate", return_value=0) as runner:
  832. self.assertEqual(gate.main([]), 0)
  833. self.assertIs(runner.call_args.kwargs["execute"], False)
  834. self.assertIs(runner.call_args.kwargs["use_local_query_account"], False)
  835. def test_cli_forwards_explicit_local_account_selection(self):
  836. for mode, execute in (("--preflight", False), ("--run", True)):
  837. with self.subTest(mode=mode), patch.object(gate, "run_book_gate", return_value=0) as runner:
  838. self.assertEqual(gate.main(["--use-local-query-account", mode]), 0)
  839. self.assertIs(runner.call_args.kwargs["execute"], execute)
  840. self.assertIs(runner.call_args.kwargs["use_local_query_account"], True)
  841. def test_cli_maps_vfs_preferences_to_real_inputs(self):
  842. with patch.object(gate, "run_book_gate", return_value=0) as runner:
  843. gate.main(["--run", "--expected-start-date", "2026-10-01", "--expected-end-date", "2026-12-31"])
  844. self.assertIs(runner.call_args.kwargs["execute"], True)
  845. self.assertEqual(runner.call_args.kwargs["user_inputs"],
  846. {"expected_start_date": "2026-10-01", "expected_end_date": "2026-12-31"})
  847. def test_audit_rejects_non_integer_counts(self):
  848. audit = Mock()
  849. for value in (True, -1, "0", None):
  850. audit.settled_snapshot.return_value = {
  851. "otpRequests": value, "avantiPosts": 0, "availabilityRequests": 0, "finalRequests": 0,
  852. }
  853. with self.subTest(value=value), self.assertRaises(gate.BookGateError):
  854. gate._counts(audit)
  855. def test_no_query_session_loader_or_profile_setup_or_final_click_in_tool(self):
  856. source = Path(gate.__file__).read_text()
  857. # Only the explicitly read-only diagnostic may mention the final button.
  858. self.assertEqual(source.count(gate.BOOK_FAILURE_STATE_SCRIPT), 1)
  859. source = source.replace(gate.BOOK_FAILURE_STATE_SCRIPT, "")
  860. for forbidden in ("_get_query_credentials(", "_prepare_query_profile(", "prepare_ita_query_profile(",
  861. "#btnPrenotaNoOtp", "InsertNewBooking"):
  862. self.assertNotIn(forbidden, source)
  863. registrations = [node for node in ast.walk(ast.parse(source))
  864. if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
  865. and node.func.attr == "_record_calendar_prepared_route"]
  866. self.assertEqual(len(registrations), 1)
  867. self.assertEqual({kw.arg: ast.literal_eval(kw.value) for kw in registrations[0].keywords}, {"role": "book"})
  868. self.assertIn("preparation.OneShotAction", source)
  869. self.assertIn("plugin.book(trigger", source)
  870. def book_failure_state():
  871. result = {key: False for key in gate._BOOK_STATE_BOOLS}
  872. result.update({key: 0 for key in gate._BOOK_STATE_COUNTS})
  873. result.update(pathMatches=True, serviceValuePresent=True, serviceControlCount=1,
  874. finalButtonCount=1, finalGuarded=True, slotStates=[])
  875. return result
  876. class BookProductionDiagnosticTests(unittest.TestCase):
  877. def test_static_reason_messages_exist_in_the_current_producer_source(self):
  878. source = Path(calendar_book.__file__).read_text() + (gate.REPO_ROOT / "plugins/ita_plugin.py").read_text()
  879. for message in gate._PRODUCTION_BOOK_FAILURES:
  880. if message in {"Book precommit rejected (precommit_rejected)",
  881. "Book TimeSlots request fields changed"}:
  882. continue # Produced by the shared protocol/request formatters and covered by packet tests.
  883. with self.subTest(message=message):
  884. self.assertIn(message, source)
  885. def test_plugin_internal_failure_keeps_its_classification(self):
  886. output = StringIO()
  887. with redirect_stdout(output):
  888. gate._failure("production_book", gate.BizLogicError(
  889. "Italy Book Calendar failed before final confirmation",
  890. ))
  891. failure = json.loads(output.getvalue().split("=", 1)[1])
  892. self.assertEqual(failure["reason"], "calendar_internal_failure")
  893. def capture_state(self, raw):
  894. page = SimpleNamespace(url=ORIGIN + CALENDAR_PATH, run_js=Mock(return_value=raw))
  895. output = StringIO()
  896. with redirect_stdout(output):
  897. gate._print_production_book_diagnostic(page)
  898. page.run_js.assert_called_once_with(gate.BOOK_FAILURE_STATE_SCRIPT)
  899. return output.getvalue(), json.loads(output.getvalue().split("=", 1)[1])
  900. def test_all_allowlisted_failures_publish_only_the_fixed_reason(self):
  901. for message, reason in gate._PRODUCTION_BOOK_FAILURES.items():
  902. with self.subTest(reason=reason):
  903. output = StringIO()
  904. with redirect_stdout(output):
  905. gate._failure("production_book", gate.BizLogicError(message))
  906. result = json.loads(output.getvalue().split("=", 1)[1])
  907. self.assertEqual(result["reason"], reason)
  908. self.assertNotEqual(result["message"], message)
  909. def test_unknown_body_and_wrong_stage_or_exception_type_are_not_exposed(self):
  910. secret = f"Book slot DOM did not match the response before timeout {USERNAME} {PASSWORD} {OTP}"
  911. for stage, error in (("production_book", gate.BizLogicError(secret)),
  912. ("production_book", RuntimeError(secret)),
  913. ("calendar_preparation", gate.BizLogicError(secret))):
  914. with self.subTest(stage=stage, error_type=type(error).__name__):
  915. output = StringIO()
  916. with redirect_stdout(output):
  917. gate._failure(stage, error)
  918. for value in (USERNAME, PASSWORD, OTP):
  919. self.assertNotIn(value, output.getvalue())
  920. self.assertNotIn('"reason": "slot_dom_timeout"', output.getvalue())
  921. def test_protocol_messages_emit_a_category_without_echoing_dynamic_code(self):
  922. for label, expected in (("TimeSlots protocol", "timeslot_protocol_rejected"),
  923. ("Calendar protocol", "calendar_protocol_rejected"),
  924. ("precommit", "precommit_readback_rejected")):
  925. output = StringIO()
  926. with redirect_stdout(output):
  927. gate._failure("production_book", gate.BizLogicError(f"Book {label} rejected (synthetic_code)"))
  928. self.assertIn(f'"reason": "{expected}"', output.getvalue())
  929. self.assertNotIn("synthetic_code", output.getvalue())
  930. def test_valid_shape_is_reported_as_after_failure_not_original_error_state(self):
  931. state = book_failure_state()
  932. state["slotStates"] = [{**{key: False for key in gate._BOOK_SLOT_BOOLS}, "hiddenInputCount": 1}]
  933. state["slotCount"] = 1
  934. _, result = self.capture_state(state)
  935. self.assertTrue(result["afterFailure"])
  936. self.assertTrue(result["readSucceeded"])
  937. self.assertEqual(result["state"], state)
  938. def test_unexpected_fields_and_types_fail_closed_without_partial_values(self):
  939. bad = []
  940. state = book_failure_state()
  941. bad.append({**state, "serviceValue": PASSWORD})
  942. bad.append({**state, "serviceValuePresent": PASSWORD})
  943. bad.append({**state, "slotCount": PASSWORD})
  944. bad.append({**state, "slotCount": True})
  945. bad.append({**state, "slotStates": [{"body": PASSWORD}]})
  946. bad.append({**state, "slotStates": [{}] * 13})
  947. bad.append({**state, "timeSlotResourceEntries": -1})
  948. for raw in bad:
  949. with self.subTest(raw_keys=tuple(raw)):
  950. output, result = self.capture_state(raw)
  951. self.assertFalse(result["readSucceeded"])
  952. self.assertNotIn("state", result)
  953. self.assertNotIn(PASSWORD, output)
  954. def test_non_calendar_page_is_not_read(self):
  955. page = SimpleNamespace(url=ORIGIN + "/Reservation", run_js=Mock())
  956. output = StringIO()
  957. with redirect_stdout(output):
  958. gate._print_production_book_diagnostic(page)
  959. page.run_js.assert_not_called()
  960. self.assertIn('"readSucceeded": false', output.getvalue())
  961. @unittest.skipUnless(shutil.which("node"), "Node is required for the read-only JS fixture")
  962. def test_readonly_script_distinguishes_offscreen_and_obscured_slots(self):
  963. fixture = r"""
  964. const script = process.argv[1], mode = process.argv[2];
  965. let measured = [];
  966. const makeSlot = (index) => ({
  967. index,
  968. classList: {contains: value => index === 0 && value === 'notAvailableFascia'},
  969. querySelector: () => null,
  970. querySelectorAll: () => [{get value() {throw Error('must not read slot identity');}}],
  971. getBoundingClientRect: () => {
  972. measured.push(index);
  973. const left = index === 1 ? 1100 : 10;
  974. return {left, right:left+100, top:20, bottom:60, width:100, height:40};
  975. },
  976. contains: () => false,
  977. get innerText() {throw Error('must not read slot text');},
  978. click: () => {throw Error('must not click');},
  979. });
  980. const slots = Array.from({length:mode === 'many' ? 13 : 3}, (_, index) => makeSlot(index));
  981. const timelineLink = {dataset:{date:'2026-10-13'}};
  982. const document = {
  983. querySelector: selector => selector === '.selected' ? timelineLink : null,
  984. querySelectorAll: selector => {
  985. if (selector === '#idServizio') return [{value:'private-runtime-identifier'}];
  986. if (selector === '.events a.selected') return [timelineLink];
  987. if (selector === '.events-content li.selected') return [{dataset:{date:'2026-10-13'},querySelectorAll:()=>slots}];
  988. if (selector === '#btnPrenotaNoOtp') return [Object.freeze({disabled:true,dataset:{coordinateFinalGuard:'enabled'}})];
  989. if (selector === '.fascia.act') return [];
  990. throw Error('unexpected selector');
  991. },
  992. elementFromPoint: () => slots[0],
  993. };
  994. const window = {innerWidth:1000, innerHeight:800,
  995. getComputedStyle:()=>({display:'block',visibility:'visible',pointerEvents:'auto',opacity:'1'})};
  996. const location = {origin:'https://prenotami.esteri.it',pathname:'/BookingCalendar'};
  997. const performance = {getEntriesByType:()=>[
  998. {name:location.origin+'/BookingCalendar/RetrieveTimeSlots'},
  999. {name:'https://other.example.test/BookingCalendar/RetrieveTimeSlots'},
  1000. {name:'not-a-url'},
  1001. ]};
  1002. const result = new Function('document','window','location','performance',script)(document,window,location,performance);
  1003. console.log(JSON.stringify({result,measured}));
  1004. """
  1005. for mode in ("normal", "many"):
  1006. with self.subTest(mode=mode):
  1007. result = subprocess.run([shutil.which("node"), "-e", fixture, gate.BOOK_FAILURE_STATE_SCRIPT, mode],
  1008. text=True, capture_output=True, timeout=10)
  1009. self.assertEqual(result.returncode, 0, result.stderr)
  1010. self.assertNotIn("private-runtime-identifier", result.stdout)
  1011. raw = json.loads(result.stdout)["result"]
  1012. self.assertTrue(raw["selectedDatesMatch"])
  1013. self.assertTrue(raw["firstSelectedIsTimeline"])
  1014. self.assertTrue(raw["finalGuarded"])
  1015. self.assertEqual(raw["timeSlotResourceEntries"], 1)
  1016. self.assertFalse(raw["slotStates"][1]["inViewport"])
  1017. self.assertTrue(raw["slotStates"][1]["cssVisible"])
  1018. self.assertTrue(raw["slotStates"][2]["inViewport"])
  1019. self.assertFalse(raw["slotStates"][2]["centerHit"])
  1020. self.assertEqual(len(raw["slotStates"]), 12 if mode == "many" else 3)
  1021. self.assertEqual(raw["slotStatesTruncated"], mode == "many")
  1022. _, accepted = self.capture_state(raw)
  1023. self.assertTrue(accepted["readSucceeded"])
  1024. class BookGateFormBoundaryScriptTests(unittest.TestCase):
  1025. def test_valid_boundary_uses_original_preflight_and_native_hidden_sync(self):
  1026. node = shutil.which("node")
  1027. if node is None:
  1028. self.fail("Node is required to validate the real preparation script")
  1029. config = preparation.build_calendar_gate_config(gate_env(), username=USERNAME, password=PASSWORD)
  1030. route = gate.resolve_route_config(config.free_config["apt_configs"], "slot.hkg.it.tourist")
  1031. script = gate._guarded_preflight_script(route, "/Services/Booking/4937")
  1032. harness = r"""
  1033. const location = {origin: 'https://prenotami.esteri.it', pathname: '/Services/Booking/4937',
  1034. href: 'https://prenotami.esteri.it/Services/Booking/4937'};
  1035. const hidden = {value: '0'}, companions = {value: '1'}, purposeHidden = {value: '0'};
  1036. const booking = {value: '0', options: [{value: '1', textContent: 'Single booking'}],
  1037. dispatchEvent: () => { hidden.value = '1'; companions.value = '0'; }};
  1038. const purpose = {value: '0', options: [{value: '42', textContent: 'Tourism'}], dispatchEvent: () => {}};
  1039. const privacy = {checked: false, click() { this.checked = true; }};
  1040. const form = {action: location.href, method: 'post', enctype: 'multipart/form-data', querySelectorAll: () => []};
  1041. const ids = {typeofbookingddl: booking, ddls_0: purpose, PrivacyCheck: privacy,
  1042. hiddenTipoPrenotazione: hidden, numAccSelected: companions, hiddenSelezionato_0: purposeHidden};
  1043. const selectors = {'#bookingForm': [form], '#otp-input': [{value: ''}], '#otp-send': [{disabled: false}],
  1044. '#btnAvanti': [{disabled: false}], 'input[name="cf-turnstile-response"]': [{value: 'fixture-only'}]};
  1045. const document = {getElementById: (id) => ids[id], querySelector: () => form,
  1046. querySelectorAll: (selector) => selectors[selector] || []};
  1047. const output = new Function('document', 'location', 'window', SCRIPT)(document, location, {location});
  1048. if (purposeHidden.value !== '0') throw Error('Must not write purpose hidden before native AVANTI');
  1049. process.stdout.write(JSON.stringify(output));
  1050. """.replace("SCRIPT", json.dumps(script))
  1051. completed = subprocess.run([node, "-e", harness], capture_output=True, text=True, timeout=10)
  1052. self.assertEqual(completed.returncode, 0, completed.stderr)
  1053. preparation.validate_booking_preflight(json.loads(completed.stdout))
  1054. def test_actual_script_checks_scope_before_reused_form_mutations(self):
  1055. node = shutil.which("node")
  1056. if node is None:
  1057. self.fail("Node is required to validate the real preparation boundary script")
  1058. config = preparation.build_calendar_gate_config(gate_env(), username=USERNAME, password=PASSWORD)
  1059. route = gate.resolve_route_config(config.free_config["apt_configs"], "slot.hkg.it.tourist")
  1060. script = gate._guarded_preflight_script(route, "/Services/Booking/4937")
  1061. harness = r"""
  1062. const script = SCRIPT;
  1063. const scenarios = ['wrongOrigin', 'wrongPath', 'noForm', 'twoForms', 'getForm',
  1064. 'wrongAction', 'queryAction', 'changedEnctype', 'upload'];
  1065. for (const scenario of scenarios) {
  1066. let mutationReads = 0;
  1067. const location = {origin: 'https://prenotami.esteri.it', pathname: '/Services/Booking/4937',
  1068. href: 'https://prenotami.esteri.it/Services/Booking/4937'};
  1069. const form = {method: 'post', enctype: 'multipart/form-data', action: location.href,
  1070. querySelectorAll: () => scenario === 'upload' ? [{}] : []};
  1071. if (scenario === 'wrongOrigin') location.origin = 'https://other.example';
  1072. if (scenario === 'wrongPath') location.pathname = '/BookingCalendar';
  1073. if (scenario === 'getForm') form.method = 'get';
  1074. if (scenario === 'wrongAction') form.action = 'https://other.example/Services/Booking/4937';
  1075. if (scenario === 'queryAction') form.action += '?changed=1';
  1076. if (scenario === 'changedEnctype') form.enctype = 'text/plain';
  1077. const document = {
  1078. querySelectorAll: () => scenario === 'noForm' ? [] : scenario === 'twoForms' ? [form, form] : [form],
  1079. querySelector: () => { mutationReads++; throw Error('Must stop before preflight'); }
  1080. };
  1081. const result = new Function('document', 'location', script)(document, location);
  1082. if (result.formReady !== false || mutationReads !== 0) throw Error(scenario);
  1083. }
  1084. process.stdout.write('FORM_BOUNDARY_OK');
  1085. """.replace("SCRIPT", json.dumps(script))
  1086. completed = subprocess.run([node, "-e", harness], capture_output=True, text=True, timeout=10)
  1087. self.assertEqual(completed.returncode, 0, completed.stderr)
  1088. self.assertEqual(completed.stdout, "FORM_BOUNDARY_OK")
  1089. if __name__ == "__main__":
  1090. unittest.main()