test_debug_ita_calendar_gate.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. import ast
  2. import hashlib
  3. import json
  4. import unittest
  5. from contextlib import redirect_stdout
  6. from io import StringIO
  7. from pathlib import Path
  8. from types import SimpleNamespace
  9. from unittest.mock import patch
  10. from plugins.ita_plugin import CALENDAR_GUARD_SCRIPT
  11. from plugins.ita_plugin import InventoryState, resolve_route_config
  12. from tools.debug_ita_calendar_gate import (
  13. BookingPreflightStage,
  14. CalendarGateError,
  15. CalendarGateEvidence,
  16. CalendarMonthScanResult,
  17. CalendarNextMonthUnavailableError,
  18. CalendarProbeResult,
  19. NEXT_MONTH_CONTROL_SCRIPT,
  20. OneShotAction,
  21. QCAL_TOOL_CONTRACT_VERSION,
  22. QCAL_TOOL_SOURCE_FINGERPRINT,
  23. ReservationSnapshot,
  24. _click_next_month,
  25. _enter_otp,
  26. _read_manual_otp,
  27. build_calendar_gate_config,
  28. listen_once,
  29. parse_availability_packet,
  30. read_reservation_snapshot,
  31. resolve_qcal_forward_months,
  32. run_calendar_gate,
  33. safe_avanti_failure_diagnostic,
  34. safe_next_month_diagnostic,
  35. safe_preflight_diagnostic,
  36. scan_calendar_horizon,
  37. validate_avanti_packet,
  38. validate_booking_preflight,
  39. validate_next_month_snapshot,
  40. validate_otp_packet,
  41. wait_for_booking_preflight,
  42. )
  43. def gate_env():
  44. return {
  45. "ITA_ROUTING_KEY": "slot.hkg.it.tourist",
  46. "ITA_SERVICE_ID": "4937",
  47. "ITA_CITY": "Hong Kong",
  48. "ITA_VISA_TYPE": "Tourist",
  49. "ITA_CALENDAR_LOOKAHEAD_MONTHS": "3",
  50. "ITA_BOOKING_TYPE_CONTROL_ID": "typeofbookingddl",
  51. "ITA_BOOKING_TYPE_VALUE": "1",
  52. "ITA_BOOKING_TYPE_LABELS": "Prenotazione Singola|Single booking",
  53. "ITA_PURPOSE_CONTROL_ID": "ddls_0",
  54. "ITA_PURPOSE_VALUE": "42",
  55. "ITA_PURPOSE_LABELS": "Turismo|Tourism",
  56. }
  57. def booking_preflight_snapshot(**changes):
  58. snapshot = {
  59. "pathMatches": True,
  60. "formPresent": True,
  61. "bookingTypeOptionMatched": True,
  62. "purposeOptionMatched": True,
  63. "bookingVisibleMatches": True,
  64. "bookingHiddenMatches": True,
  65. "companionsHiddenIsZero": True,
  66. "purposeVisibleMatches": True,
  67. "purposeHiddenIsPreSubmit": True,
  68. "privacyChecked": True,
  69. "otpInputCount": 1,
  70. "otpValuePresent": False,
  71. "otpButtonCount": 1,
  72. "otpDisabled": False,
  73. "avantiButtonCount": 1,
  74. "avantiDisabled": False,
  75. "turnstileCount": 1,
  76. "turnstileTokenPresent": True,
  77. "unknownRequiredCount": 0,
  78. }
  79. snapshot.update(changes)
  80. return snapshot
  81. class FakeResponse:
  82. def __init__(self, status, *, url="", raw_body="", headers=None):
  83. self.status = status
  84. self.url = url
  85. self.raw_body = raw_body
  86. self.headers = headers or {}
  87. class FakePacket:
  88. def __init__(
  89. self,
  90. *,
  91. method,
  92. url,
  93. status,
  94. response_url="",
  95. raw_body="",
  96. headers=None,
  97. post_data=None,
  98. ):
  99. self.method = method
  100. self.url = url
  101. self.response = FakeResponse(
  102. status,
  103. url=response_url,
  104. raw_body=raw_body,
  105. headers=headers,
  106. )
  107. self.request = SimpleNamespace(postData=post_data)
  108. class FakeListener:
  109. def __init__(self, packet=None):
  110. self.packet = packet
  111. self.starts = []
  112. self.waits = []
  113. self.stop_count = 0
  114. def start(self, target, method=None):
  115. self.starts.append((target, method))
  116. def wait(self, timeout=None):
  117. self.waits.append(timeout)
  118. return self.packet
  119. def stop(self):
  120. self.stop_count += 1
  121. class FakeReservationTab:
  122. def __init__(self, outputs):
  123. self.outputs = list(outputs)
  124. self.wait = SimpleNamespace(doc_loaded=lambda: None)
  125. self.close_count = 0
  126. def run_js(self, _script):
  127. if len(self.outputs) > 1:
  128. return self.outputs.pop(0)
  129. return self.outputs[0]
  130. def close(self):
  131. self.close_count += 1
  132. class CalendarGateConfigTests(unittest.TestCase):
  133. def test_builds_one_explicit_live_route_with_final_disabled(self):
  134. config = build_calendar_gate_config(
  135. gate_env(),
  136. username="offline@example.test",
  137. password="not-a-real-password",
  138. )
  139. free_config = config.free_config
  140. route = resolve_route_config(
  141. free_config["apt_configs"],
  142. "slot.hkg.it.tourist",
  143. )
  144. self.assertEqual(free_config["query_mode"], "services_probe")
  145. self.assertIs(free_config["final_submit_enabled"], False)
  146. self.assertEqual(route.service_id, 4937)
  147. self.assertEqual(route.capability.value, "single_schengen_tourism")
  148. self.assertEqual(route.calendar_scan.lookahead_months, 3)
  149. self.assertEqual(route.booking_type.control_id, "typeofbookingddl")
  150. self.assertEqual(route.booking_type.value, "1")
  151. self.assertEqual(route.purpose.value, "42")
  152. def test_missing_any_live_route_field_fails_closed(self):
  153. for missing in (
  154. "ITA_CALENDAR_LOOKAHEAD_MONTHS",
  155. "ITA_BOOKING_TYPE_CONTROL_ID",
  156. "ITA_BOOKING_TYPE_LABELS",
  157. "ITA_PURPOSE_VALUE",
  158. ):
  159. with self.subTest(missing=missing):
  160. env = gate_env()
  161. env.pop(missing)
  162. with self.assertRaisesRegex(CalendarGateError, missing):
  163. build_calendar_gate_config(
  164. env,
  165. username="offline@example.test",
  166. password="not-a-real-password",
  167. )
  168. def test_resolves_a_separate_bounded_discovery_horizon(self):
  169. self.assertEqual(resolve_qcal_forward_months({}), 1)
  170. self.assertEqual(
  171. resolve_qcal_forward_months({"ITA_QCAL_FORWARD_MONTHS": "12"}),
  172. 12,
  173. )
  174. for invalid in ("0", "13", "invalid", "1.5"):
  175. with self.subTest(invalid=invalid):
  176. with self.assertRaisesRegex(
  177. CalendarGateError,
  178. "ITA_QCAL_FORWARD_MONTHS",
  179. ):
  180. resolve_qcal_forward_months(
  181. {"ITA_QCAL_FORWARD_MONTHS": invalid}
  182. )
  183. class GateValueObjectTests(unittest.TestCase):
  184. def test_reservation_snapshot_requires_nonnegative_plain_integers(self):
  185. self.assertEqual(
  186. ReservationSnapshot(reservations=0, waitlist=1).total,
  187. 1,
  188. )
  189. for kwargs in (
  190. {"reservations": -1, "waitlist": 0},
  191. {"reservations": True, "waitlist": 0},
  192. {"reservations": 0, "waitlist": "0"},
  193. ):
  194. with self.subTest(kwargs=kwargs):
  195. with self.assertRaises(CalendarGateError):
  196. ReservationSnapshot(**kwargs)
  197. def test_gate_evidence_passes_only_the_exact_qcal_contract(self):
  198. empty = ReservationSnapshot(0, 0)
  199. evidence = CalendarGateEvidence(
  200. before=empty,
  201. after=empty,
  202. otp_requests=1,
  203. avanti_posts=1,
  204. availability_requests=2,
  205. final_requests=0,
  206. calendar_ready=True,
  207. )
  208. self.assertTrue(evidence.passed)
  209. variants = (
  210. {"after": ReservationSnapshot(1, 0)},
  211. {"otp_requests": 0},
  212. {"avanti_posts": 2},
  213. {"availability_requests": 1},
  214. {"final_requests": 1},
  215. {"calendar_ready": False},
  216. )
  217. for changes in variants:
  218. with self.subTest(changes=changes):
  219. values = {
  220. "before": evidence.before,
  221. "after": evidence.after,
  222. "otp_requests": evidence.otp_requests,
  223. "avanti_posts": evidence.avanti_posts,
  224. "availability_requests": evidence.availability_requests,
  225. "final_requests": evidence.final_requests,
  226. "calendar_ready": evidence.calendar_ready,
  227. }
  228. values.update(changes)
  229. self.assertFalse(CalendarGateEvidence(**values).passed)
  230. def test_one_shot_action_marks_attempt_before_calling(self):
  231. calls = []
  232. guard = OneShotAction("OTP")
  233. self.assertEqual(guard.run(lambda: calls.append("called") or 7), 7)
  234. self.assertEqual(calls, ["called"])
  235. with self.assertRaisesRegex(CalendarGateError, "OTP.*already attempted"):
  236. guard.run(lambda: calls.append("second"))
  237. self.assertEqual(calls, ["called"])
  238. failing = OneShotAction("AVANTI")
  239. with self.assertRaisesRegex(RuntimeError, "ambiguous"):
  240. failing.run(
  241. lambda: (_ for _ in ()).throw(RuntimeError("ambiguous"))
  242. )
  243. with self.assertRaisesRegex(CalendarGateError, "already attempted"):
  244. failing.run(lambda: None)
  245. class NetworkContractTests(unittest.TestCase):
  246. def test_listener_always_stops_and_performs_one_action(self):
  247. packet = object()
  248. listener = FakeListener(packet)
  249. page = SimpleNamespace(listen=listener)
  250. actions = []
  251. result = listen_once(
  252. page,
  253. target="/safe-endpoint",
  254. method="POST",
  255. action=lambda: actions.append("one"),
  256. timeout=9,
  257. )
  258. self.assertIs(result, packet)
  259. self.assertEqual(actions, ["one"])
  260. self.assertEqual(listener.starts, [("/safe-endpoint", "POST")])
  261. self.assertEqual(listener.waits, [9])
  262. self.assertEqual(listener.stop_count, 1)
  263. failing_listener = FakeListener(None)
  264. failing_page = SimpleNamespace(listen=failing_listener)
  265. with self.assertRaisesRegex(CalendarGateError, "not observed"):
  266. listen_once(
  267. failing_page,
  268. target="/safe-endpoint",
  269. method="GET",
  270. action=lambda: None,
  271. timeout=1,
  272. )
  273. self.assertEqual(failing_listener.stop_count, 1)
  274. raising_listener = FakeListener(packet)
  275. raising_page = SimpleNamespace(listen=raising_listener)
  276. with self.assertRaisesRegex(RuntimeError, "action failed"):
  277. listen_once(
  278. raising_page,
  279. target="/safe-endpoint",
  280. method="POST",
  281. action=lambda: (_ for _ in ()).throw(
  282. RuntimeError("action failed")
  283. ),
  284. timeout=1,
  285. )
  286. self.assertEqual(raising_listener.stop_count, 1)
  287. def test_otp_requires_exact_get_route_status_and_json_string(self):
  288. packet = FakePacket(
  289. method="GET",
  290. url=(
  291. "https://prenotami.esteri.it/BookingCalendar/GenerateOTP"
  292. "?ServiceID=4937"
  293. ),
  294. status=200,
  295. raw_body='"SENT"',
  296. )
  297. validate_otp_packet(packet, service_id=4937)
  298. bad_packets = (
  299. FakePacket(
  300. method="POST",
  301. url=packet.url,
  302. status=200,
  303. raw_body='"SENT"',
  304. ),
  305. FakePacket(
  306. method="GET",
  307. url=packet.url,
  308. status=201,
  309. raw_body='"SENT"',
  310. ),
  311. FakePacket(
  312. method="GET",
  313. url=packet.url,
  314. status=200,
  315. raw_body="SENT",
  316. ),
  317. FakePacket(
  318. method="GET",
  319. url=packet.url.replace("4937", "1321"),
  320. status=200,
  321. raw_body='"SENT"',
  322. ),
  323. )
  324. for bad in bad_packets:
  325. with self.subTest(packet=bad):
  326. with self.assertRaises(CalendarGateError):
  327. validate_otp_packet(bad, service_id=4937)
  328. def test_avanti_accepts_direct_302_to_the_observed_calendar(self):
  329. packet = FakePacket(
  330. method="POST",
  331. url="https://prenotami.esteri.it/Services/Booking/4937",
  332. status=302,
  333. headers={
  334. "Location": (
  335. "/BookingCalendar?selectedService="
  336. "Visti%20Nazionali%20e%20Schengen"
  337. )
  338. },
  339. )
  340. mode = validate_avanti_packet(
  341. packet,
  342. booking_path="/Services/Booking/4937",
  343. final_page_url=(
  344. "https://prenotami.esteri.it/BookingCalendar"
  345. "?selectedService=Visti"
  346. ),
  347. )
  348. self.assertEqual(mode, "direct_302")
  349. def test_avanti_accepts_only_a_triply_consistent_followed_200(self):
  350. packet = FakePacket(
  351. method="POST",
  352. url="https://prenotami.esteri.it/Services/Booking/4937",
  353. status=200,
  354. response_url=(
  355. "https://prenotami.esteri.it/BookingCalendar"
  356. "?selectedService=Visti"
  357. ),
  358. )
  359. mode = validate_avanti_packet(
  360. packet,
  361. booking_path="/Services/Booking/4937",
  362. final_page_url="https://prenotami.esteri.it/BookingCalendar",
  363. )
  364. self.assertEqual(mode, "followed_redirect_200")
  365. def test_avanti_rejects_inconsistent_redirect_evidence(self):
  366. cases = (
  367. {
  368. "status": 200,
  369. "response_url": "https://prenotami.esteri.it/Services",
  370. "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
  371. },
  372. {
  373. "status": 200,
  374. "response_url": "https://example.test/BookingCalendar",
  375. "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
  376. },
  377. {
  378. "status": 200,
  379. "response_url": (
  380. "https://prenotami.esteri.it:444/BookingCalendar"
  381. ),
  382. "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
  383. },
  384. {
  385. "status": 200,
  386. "response_url": "https://prenotami.esteri.it/BookingCalendar",
  387. "final_page_url": "https://prenotami.esteri.it/Services",
  388. },
  389. {
  390. "status": 201,
  391. "response_url": "https://prenotami.esteri.it/BookingCalendar",
  392. "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
  393. },
  394. )
  395. for case in cases:
  396. with self.subTest(case=case):
  397. bad = FakePacket(
  398. method="POST",
  399. url=(
  400. "https://prenotami.esteri.it/Services/Booking/4937"
  401. ),
  402. status=case["status"],
  403. response_url=case["response_url"],
  404. )
  405. with self.assertRaises(CalendarGateError):
  406. validate_avanti_packet(
  407. bad,
  408. booking_path="/Services/Booking/4937",
  409. final_page_url=case["final_page_url"],
  410. )
  411. def test_avanti_rejects_bad_direct_redirects_and_requests(self):
  412. for method, request_url, location in (
  413. (
  414. "POST",
  415. "https://prenotami.esteri.it/Services/Booking/4937",
  416. "/Services",
  417. ),
  418. (
  419. "POST",
  420. "https://prenotami.esteri.it/Services/Booking/4937",
  421. "https://example.test/BookingCalendar",
  422. ),
  423. (
  424. "POST",
  425. "https://prenotami.esteri.it/Services/Booking/4937?retry=1",
  426. "/BookingCalendar",
  427. ),
  428. (
  429. "GET",
  430. "https://prenotami.esteri.it/Services/Booking/4937",
  431. "/BookingCalendar",
  432. ),
  433. (
  434. "POST",
  435. "https://prenotami.esteri.it/Services/Booking/1321",
  436. "/BookingCalendar",
  437. ),
  438. (
  439. "POST",
  440. "https://example.test/Services/Booking/4937",
  441. "/BookingCalendar",
  442. ),
  443. (
  444. "POST",
  445. "https://prenotami.esteri.it/Services/Booking/4937",
  446. "",
  447. ),
  448. ):
  449. with self.subTest(
  450. method=method,
  451. request_url=request_url,
  452. location=location,
  453. ):
  454. packet = FakePacket(
  455. method=method,
  456. url=request_url,
  457. status=302,
  458. headers={"Location": location},
  459. )
  460. with self.assertRaises(CalendarGateError):
  461. validate_avanti_packet(
  462. packet,
  463. booking_path="/Services/Booking/4937",
  464. final_page_url=(
  465. "https://prenotami.esteri.it/BookingCalendar"
  466. ),
  467. )
  468. def test_avanti_failure_diagnostic_is_strictly_allowlisted(self):
  469. packet = FakePacket(
  470. method="POST",
  471. url="https://prenotami.esteri.it/Services/Booking/4937",
  472. status=200,
  473. response_url=(
  474. "https://prenotami.esteri.it/Services/Booking/4937"
  475. "?private-response-query"
  476. ),
  477. raw_body="private-response-body",
  478. headers={
  479. "Location": (
  480. "/BookingCalendar?private-location-query"
  481. )
  482. },
  483. post_data="private-form-data",
  484. )
  485. raw = {
  486. "path": "/Services/Booking/4937",
  487. "bookingFormPresent": True,
  488. "otpValuePresent": True,
  489. "otpInvalidVisible": False,
  490. "avantiDisabled": False,
  491. "turnstileTokenPresent": False,
  492. "visibleValidationCount": 1,
  493. "visibleConfirmCount": 0,
  494. "finalRequestCount": 0,
  495. "mustNotLeak": "private-runtime-value",
  496. }
  497. diagnostic = safe_avanti_failure_diagnostic(
  498. packet,
  499. raw,
  500. booking_path="/Services/Booking/4937",
  501. )
  502. self.assertEqual(
  503. set(diagnostic),
  504. {
  505. "outcome",
  506. "contract",
  507. "sourceFingerprint",
  508. "snapshotType",
  509. "bookingPostObserved",
  510. "requestMatches",
  511. "responseStatus",
  512. "responsePath",
  513. "locationPath",
  514. "browserPath",
  515. "bookingFormPresent",
  516. "otpValuePresent",
  517. "otpInvalidVisible",
  518. "avantiDisabled",
  519. "turnstileReady",
  520. "visibleValidationCount",
  521. "visibleConfirmCount",
  522. "finalRequestCount",
  523. },
  524. )
  525. self.assertEqual(diagnostic["outcome"], "booking_form_returned")
  526. self.assertIs(diagnostic["bookingPostObserved"], True)
  527. self.assertIs(diagnostic["requestMatches"], True)
  528. self.assertEqual(
  529. diagnostic["responseStatus"],
  530. {"type": "int", "value": 200},
  531. )
  532. self.assertEqual(diagnostic["responsePath"], "booking")
  533. self.assertEqual(diagnostic["locationPath"], "calendar")
  534. self.assertEqual(diagnostic["browserPath"], "booking")
  535. self.assertEqual(
  536. diagnostic["otpValuePresent"],
  537. {"type": "bool", "value": True},
  538. )
  539. serialized = json.dumps(diagnostic)
  540. for private_value in (
  541. "private-response-query",
  542. "private-response-body",
  543. "private-location-query",
  544. "private-form-data",
  545. "private-runtime-value",
  546. ):
  547. self.assertNotIn(private_value, serialized)
  548. def test_avanti_failure_diagnostic_degrades_unknown_values(self):
  549. diagnostic = safe_avanti_failure_diagnostic(
  550. None,
  551. "private-runtime-value",
  552. booking_path="/Services/Booking/4937",
  553. )
  554. self.assertEqual(
  555. diagnostic["outcome"],
  556. "booking_post_not_observed",
  557. )
  558. self.assertIs(diagnostic["bookingPostObserved"], False)
  559. self.assertEqual(diagnostic["responsePath"], "missing")
  560. self.assertEqual(diagnostic["browserPath"], "missing")
  561. self.assertEqual(
  562. diagnostic["otpValuePresent"],
  563. {"type": "NoneType", "value": None},
  564. )
  565. self.assertNotIn(
  566. "private-runtime-value",
  567. json.dumps(diagnostic),
  568. )
  569. def test_availability_packet_reuses_the_strict_protocol_parser(self):
  570. inner = json.dumps(
  571. [
  572. {
  573. "DateLibere": "01/10/2026 00:00:00",
  574. "SlotLiberi": 0,
  575. "SlotRimanenti": -1,
  576. },
  577. {
  578. "DateLibere": "02/10/2026 00:00:00",
  579. "SlotLiberi": 1,
  580. "SlotRimanenti": 0,
  581. },
  582. ]
  583. )
  584. packet = FakePacket(
  585. method="POST",
  586. url=(
  587. "https://prenotami.esteri.it/BookingCalendar/"
  588. "RetrieveCalendarAvailability"
  589. ),
  590. status=200,
  591. raw_body=json.dumps(inner),
  592. post_data=json.dumps(
  593. {"_Servizio": "runtime-only", "selectedDay": "01/10/2026"}
  594. ),
  595. )
  596. result = parse_availability_packet(packet)
  597. self.assertEqual(result.item_count, 2)
  598. self.assertEqual(result.available_count, 1)
  599. self.assertEqual(result.selected_day, "01/10/2026")
  600. self.assertEqual(result.selected_month, (2026, 10))
  601. self.assertEqual(result.days[0].state, InventoryState.UNAVAILABLE)
  602. self.assertEqual(result.days[1].state, InventoryState.AVAILABLE)
  603. packet.request.postData = json.dumps(
  604. {
  605. "_Servizio": "runtime-only",
  606. "selectedDay": "01/10/2026",
  607. "guessed": True,
  608. }
  609. )
  610. with self.assertRaisesRegex(CalendarGateError, "request keys"):
  611. parse_availability_packet(packet)
  612. class NextMonthControlTests(unittest.TestCase):
  613. def test_snapshot_requires_one_actionable_control_and_exact_shape(self):
  614. ready = {
  615. "pathMatches": True,
  616. "candidateCount": 4,
  617. "actionableCount": 1,
  618. "clicked": False,
  619. }
  620. self.assertIs(
  621. validate_next_month_snapshot(
  622. ready,
  623. expected_clicked=False,
  624. ),
  625. ready,
  626. )
  627. unready = {**ready, "actionableCount": 0}
  628. validate_next_month_snapshot(
  629. unready,
  630. expected_clicked=False,
  631. allow_unready=True,
  632. )
  633. for changed, message in (
  634. ({**ready, "actionableCount": 2}, "uniquely actionable"),
  635. ({**ready, "candidateCount": True}, "candidateCount"),
  636. ({**ready, "clicked": True}, "acknowledgement"),
  637. ({**ready, "private": "value"}, "unexpected fields"),
  638. ):
  639. with self.subTest(changed=changed):
  640. with self.assertRaisesRegex(CalendarGateError, message):
  641. validate_next_month_snapshot(
  642. changed,
  643. expected_clicked=False,
  644. )
  645. def test_click_waits_then_atomically_clicks_once(self):
  646. outputs = [
  647. {
  648. "pathMatches": True,
  649. "candidateCount": 4,
  650. "actionableCount": 0,
  651. "clicked": False,
  652. },
  653. {
  654. "pathMatches": True,
  655. "candidateCount": 4,
  656. "actionableCount": 1,
  657. "clicked": False,
  658. },
  659. {
  660. "pathMatches": True,
  661. "candidateCount": 4,
  662. "actionableCount": 1,
  663. "clicked": True,
  664. },
  665. ]
  666. calls = []
  667. def run_js(script, should_click):
  668. calls.append((script, should_click))
  669. return outputs.pop(0)
  670. stdout = StringIO()
  671. with redirect_stdout(stdout):
  672. with patch("tools.debug_ita_calendar_gate.time.sleep"):
  673. _click_next_month(
  674. SimpleNamespace(run_js=run_js),
  675. timeout=1,
  676. )
  677. self.assertEqual(
  678. [should_click for _script, should_click in calls],
  679. [False, False, True],
  680. )
  681. self.assertTrue(
  682. all(script == NEXT_MONTH_CONTROL_SCRIPT for script, _ in calls)
  683. )
  684. self.assertEqual(
  685. stdout.getvalue().count("ITA_QCAL_NEXT_MONTH_DIAGNOSTIC="),
  686. 1,
  687. )
  688. self.assertIn('"clicked": {"type": "bool", "value": true}', stdout.getvalue())
  689. def test_click_uses_a_distinct_error_for_an_unavailable_boundary(self):
  690. with self.assertRaises(CalendarNextMonthUnavailableError):
  691. _click_next_month(
  692. SimpleNamespace(run_js=lambda _script, _click: None),
  693. timeout=0,
  694. )
  695. def test_diagnostic_allowlist_never_serializes_unknown_values(self):
  696. raw = {
  697. "pathMatches": True,
  698. "candidateCount": 4,
  699. "actionableCount": 1,
  700. "clicked": False,
  701. "private": "private-runtime-value",
  702. }
  703. diagnostic = safe_next_month_diagnostic(raw)
  704. self.assertEqual(
  705. set(diagnostic),
  706. {
  707. "contract",
  708. "sourceFingerprint",
  709. "snapshotType",
  710. "pathMatches",
  711. "candidateCount",
  712. "actionableCount",
  713. "clicked",
  714. },
  715. )
  716. self.assertNotIn("private-runtime-value", json.dumps(diagnostic))
  717. class CalendarHorizonScanTests(unittest.TestCase):
  718. @staticmethod
  719. def packet(month: int, available: bool = False) -> FakePacket:
  720. slots_free = 1 if available else 0
  721. slots_remaining = 0 if available else -1
  722. inner = json.dumps(
  723. [
  724. {
  725. "DateLibere": f"01/{month:02d}/2026 00:00:00",
  726. "SlotLiberi": slots_free,
  727. "SlotRimanenti": slots_remaining,
  728. }
  729. ]
  730. )
  731. return FakePacket(
  732. method="POST",
  733. url=(
  734. "https://prenotami.esteri.it/BookingCalendar/"
  735. "RetrieveCalendarAvailability"
  736. ),
  737. status=200,
  738. raw_body=json.dumps(inner),
  739. post_data=json.dumps(
  740. {
  741. "_Servizio": "runtime-only",
  742. "selectedDay": f"01/{month:02d}/2026",
  743. }
  744. ),
  745. )
  746. def test_scans_the_initial_month_plus_the_forward_limit(self):
  747. packets = [
  748. self.packet(8),
  749. self.packet(9, available=True),
  750. self.packet(10),
  751. ]
  752. actions = []
  753. guards = []
  754. def fake_listen(_page, *, action, **_kwargs):
  755. action()
  756. return packets.pop(0)
  757. stdout = StringIO()
  758. with redirect_stdout(stdout):
  759. with patch(
  760. "tools.debug_ita_calendar_gate.listen_once",
  761. side_effect=fake_listen,
  762. ), patch(
  763. "tools.debug_ita_calendar_gate._refresh_calendar",
  764. side_effect=lambda _page: actions.append("refresh"),
  765. ), patch(
  766. "tools.debug_ita_calendar_gate._click_next_month",
  767. side_effect=lambda _page: actions.append("next"),
  768. ), patch(
  769. "tools.debug_ita_calendar_gate._calendar_guard",
  770. side_effect=lambda _page: guards.append("guard"),
  771. ), patch("tools.debug_ita_calendar_gate.time.sleep"):
  772. result = scan_calendar_horizon(
  773. SimpleNamespace(),
  774. forward_months=2,
  775. )
  776. self.assertEqual(actions, ["refresh", "next", "next"])
  777. self.assertEqual(guards, ["guard", "guard", "guard"])
  778. self.assertEqual(result.forward_clicks, 2)
  779. self.assertEqual(result.availability_requests, 3)
  780. self.assertEqual(result.stop_reason, "forward_limit_reached")
  781. self.assertEqual(result.probes[1].available_count, 1)
  782. self.assertEqual(result.probes[-1].available_count, 0)
  783. self.assertEqual(result.safe_dict()["monthsWithAvailability"], 1)
  784. self.assertEqual(
  785. result.safe_dict()["earliestAvailableDate"],
  786. "2026-09-01",
  787. )
  788. self.assertEqual(result.safe_dict()["furthestMonth"], "2026-10")
  789. self.assertIn("ITA_QCAL_MONTH_SCAN_RESULT=", stdout.getvalue())
  790. def test_stops_cleanly_when_the_native_next_control_is_unavailable(self):
  791. packets = [self.packet(8)]
  792. def fake_listen(_page, *, action, **_kwargs):
  793. action()
  794. return packets.pop(0)
  795. with patch(
  796. "tools.debug_ita_calendar_gate.listen_once",
  797. side_effect=fake_listen,
  798. ), patch(
  799. "tools.debug_ita_calendar_gate._refresh_calendar",
  800. ), patch(
  801. "tools.debug_ita_calendar_gate._click_next_month",
  802. side_effect=CalendarNextMonthUnavailableError("bounded-stop"),
  803. ), patch(
  804. "tools.debug_ita_calendar_gate._calendar_guard",
  805. ), patch("tools.debug_ita_calendar_gate.time.sleep"):
  806. result = scan_calendar_horizon(
  807. SimpleNamespace(),
  808. forward_months=12,
  809. )
  810. self.assertEqual(result.forward_clicks, 0)
  811. self.assertEqual(result.stop_reason, "next_control_unavailable")
  812. self.assertTrue(result.safe_dict()["nextControlUnavailable"])
  813. def test_result_rejects_skipped_or_excess_months(self):
  814. august = CalendarProbeResult(
  815. days=(),
  816. selected_day="01/08/2026",
  817. )
  818. october = CalendarProbeResult(
  819. days=(),
  820. selected_day="01/10/2026",
  821. )
  822. with self.assertRaisesRegex(CalendarGateError, "exactly one month"):
  823. CalendarMonthScanResult(
  824. probes=(august, october),
  825. requested_forward_months=2,
  826. stop_reason="next_control_unavailable",
  827. )
  828. with self.assertRaisesRegex(CalendarGateError, "ended before"):
  829. CalendarMonthScanResult(
  830. probes=(august,),
  831. requested_forward_months=2,
  832. stop_reason="forward_limit_reached",
  833. )
  834. def test_result_accepts_an_exact_cross_year_transition(self):
  835. december = CalendarProbeResult(
  836. days=(),
  837. selected_day="01/12/2026",
  838. )
  839. january = CalendarProbeResult(
  840. days=(),
  841. selected_day="01/01/2027",
  842. )
  843. result = CalendarMonthScanResult(
  844. probes=(december, january),
  845. requested_forward_months=1,
  846. stop_reason="forward_limit_reached",
  847. )
  848. self.assertEqual(result.safe_dict()["startMonth"], "2026-12")
  849. self.assertEqual(result.safe_dict()["furthestMonth"], "2027-01")
  850. self.assertIsNone(result.safe_dict()["earliestAvailableDate"])
  851. class BookingPreflightTests(unittest.TestCase):
  852. def test_diagnostic_is_stage_specific_and_strictly_allowlisted(self):
  853. raw = booking_preflight_snapshot(otpDisabled=1)
  854. raw["mustNotLeak"] = "private-runtime-value"
  855. diagnostic = safe_preflight_diagnostic(
  856. raw,
  857. stage=BookingPreflightStage.AFTER_OTP_SEND,
  858. outcome="rejected",
  859. )
  860. self.assertEqual(
  861. set(diagnostic),
  862. {
  863. "contract",
  864. "sourceFingerprint",
  865. "outcome",
  866. "stage",
  867. "snapshotType",
  868. "otpDisabled",
  869. "otpValuePresent",
  870. "avantiDisabled",
  871. "turnstileReady",
  872. },
  873. )
  874. self.assertEqual(
  875. diagnostic["contract"],
  876. QCAL_TOOL_CONTRACT_VERSION,
  877. )
  878. self.assertEqual(
  879. diagnostic["sourceFingerprint"],
  880. QCAL_TOOL_SOURCE_FINGERPRINT,
  881. )
  882. self.assertEqual(diagnostic["stage"], "after_otp_send")
  883. self.assertEqual(
  884. diagnostic["otpDisabled"],
  885. {"type": "int", "value": None},
  886. )
  887. self.assertEqual(
  888. diagnostic["otpValuePresent"],
  889. {"type": "bool", "value": False},
  890. )
  891. self.assertNotIn(
  892. "private-runtime-value",
  893. json.dumps(diagnostic),
  894. )
  895. invalid_outcome = safe_preflight_diagnostic(
  896. raw,
  897. stage=BookingPreflightStage.AFTER_OTP_SEND,
  898. outcome="private-runtime-value",
  899. )
  900. self.assertEqual(invalid_outcome["outcome"], "invalid")
  901. self.assertNotIn(
  902. "private-runtime-value",
  903. json.dumps(invalid_outcome),
  904. )
  905. def test_rejected_preflight_logs_shape_without_runtime_values(self):
  906. raw = booking_preflight_snapshot(otpDisabled=1)
  907. raw["mustNotLeak"] = "private-runtime-value"
  908. page = SimpleNamespace(run_js=lambda _script: raw)
  909. stdout = StringIO()
  910. with redirect_stdout(stdout):
  911. with self.assertRaisesRegex(CalendarGateError, "otpDisabled"):
  912. wait_for_booking_preflight(
  913. page,
  914. script="safe-script",
  915. stage=BookingPreflightStage.AFTER_OTP_SEND,
  916. timeout=1,
  917. )
  918. output = stdout.getvalue()
  919. self.assertIn("ITA_QCAL_PREFLIGHT_DIAGNOSTIC=", output)
  920. self.assertIn('"stage": "after_otp_send"', output)
  921. self.assertIn('"type": "int"', output)
  922. self.assertNotIn("private-runtime-value", output)
  923. def test_preflight_requires_exact_safe_shape_without_reading_tokens(self):
  924. raw = booking_preflight_snapshot()
  925. validate_booking_preflight(raw)
  926. for key in (
  927. "pathMatches",
  928. "purposeHiddenIsPreSubmit",
  929. "privacyChecked",
  930. "turnstileTokenPresent",
  931. "otpDisabled",
  932. "otpValuePresent",
  933. "avantiDisabled",
  934. ):
  935. with self.subTest(key=key):
  936. changed = dict(raw)
  937. changed[key] = key in {
  938. "otpDisabled",
  939. "otpValuePresent",
  940. "avantiDisabled",
  941. }
  942. with self.assertRaisesRegex(CalendarGateError, key):
  943. validate_booking_preflight(changed)
  944. changed = dict(raw)
  945. changed["unknownRequiredCount"] = 1
  946. with self.assertRaisesRegex(CalendarGateError, "unknownRequiredCount"):
  947. validate_booking_preflight(changed)
  948. def test_post_otp_accepts_cooldown_without_relaxing_structure(self):
  949. cooldown = booking_preflight_snapshot(
  950. otpDisabled=True,
  951. otpValuePresent=True,
  952. )
  953. with self.assertRaisesRegex(CalendarGateError, "otpDisabled"):
  954. validate_booking_preflight(cooldown)
  955. validate_booking_preflight(
  956. cooldown,
  957. stage=BookingPreflightStage.AFTER_OTP_SEND,
  958. )
  959. validate_booking_preflight(
  960. booking_preflight_snapshot(otpValuePresent=True),
  961. stage=BookingPreflightStage.AFTER_OTP_SEND,
  962. )
  963. for key, value in (
  964. ("otpDisabled", None),
  965. ("otpValuePresent", False),
  966. ("otpButtonCount", 0),
  967. ("formPresent", False),
  968. ("unknownRequiredCount", 1),
  969. ):
  970. with self.subTest(key=key):
  971. changed = dict(cooldown)
  972. changed[key] = value
  973. with self.assertRaisesRegex(CalendarGateError, key):
  974. validate_booking_preflight(
  975. changed,
  976. stage=BookingPreflightStage.AFTER_OTP_SEND,
  977. )
  978. def test_dynamic_wait_rechecks_token_without_relaxing_structure(self):
  979. base = booking_preflight_snapshot(
  980. avantiDisabled=True,
  981. turnstileTokenPresent=False,
  982. )
  983. ready = dict(base)
  984. ready["avantiDisabled"] = False
  985. ready["turnstileTokenPresent"] = True
  986. outputs = [base, ready]
  987. page = SimpleNamespace(run_js=lambda _script: outputs.pop(0))
  988. with patch("tools.debug_ita_calendar_gate.time.sleep"):
  989. result = wait_for_booking_preflight(
  990. page,
  991. script="safe-script",
  992. timeout=1,
  993. )
  994. self.assertIs(result, ready)
  995. def test_post_otp_wait_accepts_disabled_send_button(self):
  996. base = booking_preflight_snapshot(
  997. otpDisabled=True,
  998. otpValuePresent=True,
  999. avantiDisabled=True,
  1000. turnstileTokenPresent=False,
  1001. )
  1002. ready = dict(base)
  1003. ready["avantiDisabled"] = False
  1004. ready["turnstileTokenPresent"] = True
  1005. outputs = [base, ready]
  1006. page = SimpleNamespace(run_js=lambda _script: outputs.pop(0))
  1007. stdout = StringIO()
  1008. with redirect_stdout(stdout):
  1009. with patch("tools.debug_ita_calendar_gate.time.sleep"):
  1010. result = wait_for_booking_preflight(
  1011. page,
  1012. script="safe-script",
  1013. stage=BookingPreflightStage.AFTER_OTP_SEND,
  1014. timeout=1,
  1015. )
  1016. self.assertIs(result, ready)
  1017. self.assertIn('"outcome": "ready"', stdout.getvalue())
  1018. self.assertIn('"stage": "after_otp_send"', stdout.getvalue())
  1019. self.assertIn('"type": "bool"', stdout.getvalue())
  1020. class OtpEntryTests(unittest.TestCase):
  1021. def test_manual_otp_is_visible_and_still_validated(self):
  1022. prompt = StringIO()
  1023. with patch("builtins.input", return_value="123456") as input_mock:
  1024. with redirect_stdout(prompt):
  1025. result = _read_manual_otp()
  1026. self.assertEqual(result, "123456")
  1027. input_mock.assert_called_once_with(
  1028. "Italy booking OTP "
  1029. "(visible; terminal scrollback may retain it): "
  1030. )
  1031. self.assertNotIn("123456", prompt.getvalue())
  1032. for invalid in ("", "123", "1234567890123", "12a456"):
  1033. with self.subTest(invalid=invalid):
  1034. with patch("builtins.input", return_value=invalid):
  1035. with self.assertRaisesRegex(
  1036. CalendarGateError,
  1037. "OTP must be 4-12 digits",
  1038. ):
  1039. _read_manual_otp()
  1040. def test_otp_entry_focuses_before_typing_and_compares_in_page(self):
  1041. events = []
  1042. class FakeOtpElement:
  1043. def input(self, value, clear=False):
  1044. events.append(("input", value, clear))
  1045. def run_js(self, script, value):
  1046. events.append(("compare", script, value))
  1047. return True
  1048. otp_element = FakeOtpElement()
  1049. plugin = SimpleNamespace(
  1050. page=SimpleNamespace(
  1051. ele=lambda selector, timeout=0: (
  1052. otp_element if selector == "#otp-input" else None
  1053. )
  1054. ),
  1055. mouse=SimpleNamespace(
  1056. human_click_ele=lambda element: events.append(
  1057. ("click", element)
  1058. )
  1059. ),
  1060. )
  1061. stdout = StringIO()
  1062. with redirect_stdout(stdout):
  1063. _enter_otp(plugin, "123456")
  1064. self.assertEqual(events[0], ("click", otp_element))
  1065. self.assertEqual(events[1], ("input", "123456", True))
  1066. self.assertEqual(events[2][0], "compare")
  1067. self.assertIn("this.value === arguments[0]", events[2][1])
  1068. self.assertEqual(events[2][2], "123456")
  1069. self.assertIn(
  1070. "ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true",
  1071. stdout.getvalue(),
  1072. )
  1073. self.assertNotIn("123456", stdout.getvalue())
  1074. def test_otp_entry_fails_before_avanti_when_readback_differs(self):
  1075. otp_element = SimpleNamespace(
  1076. input=lambda _value, clear=False: None,
  1077. run_js=lambda _script, _value: False,
  1078. )
  1079. plugin = SimpleNamespace(
  1080. page=SimpleNamespace(ele=lambda _selector, timeout=0: otp_element),
  1081. mouse=SimpleNamespace(human_click_ele=lambda _element: None),
  1082. )
  1083. with self.assertRaisesRegex(
  1084. CalendarGateError,
  1085. "OTP DOM write verification failed",
  1086. ):
  1087. _enter_otp(plugin, "123456")
  1088. class ToolContractTests(unittest.TestCase):
  1089. def test_contract_is_logged_before_route_or_credentials_are_read(self):
  1090. tool_path = (
  1091. Path(__file__).resolve().parents[1]
  1092. / "tools"
  1093. / "debug_ita_calendar_gate.py"
  1094. )
  1095. shared_path = (
  1096. Path(__file__).resolve().parents[1]
  1097. / "plugins"
  1098. / "ita_plugin.py"
  1099. )
  1100. plugin_path = tool_path.parents[1] / "plugins" / "ita_plugin.py"
  1101. protocol_path = tool_path.parents[1] / "plugins" / "ita_plugin.py"
  1102. expected_fingerprint = hashlib.sha256(
  1103. tool_path.read_bytes()
  1104. + (tool_path.parents[1] / "plugins" / "ita_plugin.py").read_bytes()
  1105. + shared_path.read_bytes()
  1106. + plugin_path.read_bytes() + protocol_path.read_bytes()
  1107. + (tool_path.parents[1] / "plugins" / "ita_plugin.py").read_bytes()
  1108. + (tool_path.parents[1] / "tools" / "debug_ita_soak.py").read_bytes()
  1109. + (tool_path.parents[1] / "toolkit" / "backoff.py").read_bytes()
  1110. ).hexdigest()[:12]
  1111. self.assertEqual(
  1112. QCAL_TOOL_SOURCE_FINGERPRINT,
  1113. expected_fingerprint,
  1114. )
  1115. stdout = StringIO()
  1116. with patch(
  1117. "tools.debug_ita_calendar_gate.resolve_debug_route",
  1118. side_effect=CalendarGateError("offline-stop"),
  1119. ):
  1120. with redirect_stdout(stdout):
  1121. with self.assertRaisesRegex(
  1122. CalendarGateError,
  1123. "offline-stop",
  1124. ):
  1125. run_calendar_gate({})
  1126. self.assertEqual(
  1127. stdout.getvalue().strip(),
  1128. "ITA_QCAL_TOOL_CONTRACT "
  1129. f"version={QCAL_TOOL_CONTRACT_VERSION} "
  1130. f"source_sha256={QCAL_TOOL_SOURCE_FINGERPRINT}",
  1131. )
  1132. class ReservationSnapshotTests(unittest.TestCase):
  1133. def test_reads_both_initialized_datatables_and_always_closes_tab(self):
  1134. loading = {
  1135. "path": "/Reservation",
  1136. "authenticated": True,
  1137. "tableCount": 2,
  1138. "ready": False,
  1139. "reservations": None,
  1140. "waitlist": None,
  1141. }
  1142. ready = {
  1143. **loading,
  1144. "ready": True,
  1145. "reservations": 2,
  1146. "waitlist": 1,
  1147. }
  1148. tab = FakeReservationTab([loading, ready, ready])
  1149. opened_urls = []
  1150. page = SimpleNamespace(
  1151. new_tab=lambda url: opened_urls.append(url) or tab
  1152. )
  1153. with patch("tools.debug_ita_calendar_gate.time.sleep"):
  1154. result = read_reservation_snapshot(
  1155. page,
  1156. timeout=1,
  1157. settle_seconds=0,
  1158. )
  1159. self.assertEqual(result, ReservationSnapshot(2, 1))
  1160. self.assertEqual(opened_urls, ["https://prenotami.esteri.it/Reservation"])
  1161. self.assertEqual(tab.close_count, 1)
  1162. def test_invalid_counts_fail_and_close_tab(self):
  1163. tab = FakeReservationTab(
  1164. [
  1165. {
  1166. "path": "/Reservation",
  1167. "authenticated": True,
  1168. "tableCount": 2,
  1169. "ready": True,
  1170. "reservations": True,
  1171. "waitlist": 0,
  1172. }
  1173. ]
  1174. )
  1175. page = SimpleNamespace(new_tab=lambda _url: tab)
  1176. with self.assertRaises(CalendarGateError):
  1177. read_reservation_snapshot(
  1178. page,
  1179. timeout=1,
  1180. settle_seconds=0,
  1181. )
  1182. self.assertEqual(tab.close_count, 1)
  1183. class SourceSafetyTests(unittest.TestCase):
  1184. def test_gate_source_never_clicks_or_submits_the_final_control(self):
  1185. path = (
  1186. Path(__file__).resolve().parents[1]
  1187. / "tools"
  1188. / "debug_ita_calendar_gate.py"
  1189. )
  1190. source = path.read_text(encoding="utf-8")
  1191. tree = ast.parse(source)
  1192. violations = []
  1193. one_shot_calls = []
  1194. for node in ast.walk(tree):
  1195. if not isinstance(node, ast.Call):
  1196. continue
  1197. function = node.func
  1198. function_name = (
  1199. function.attr
  1200. if isinstance(function, ast.Attribute)
  1201. else function.id
  1202. if isinstance(function, ast.Name)
  1203. else ""
  1204. )
  1205. string_arguments = {
  1206. child.value
  1207. for child in ast.walk(node)
  1208. if isinstance(child, ast.Constant)
  1209. and isinstance(child.value, str)
  1210. }
  1211. if function_name in {"submit", "click"} and any(
  1212. "btnPrenotaNoOtp" in value
  1213. or "InsertNewBooking" in value
  1214. for value in string_arguments
  1215. ):
  1216. violations.append((function_name, node.lineno))
  1217. if function_name == "human_click_ele" and any(
  1218. "btnPrenotaNoOtp" in value
  1219. for value in string_arguments
  1220. ):
  1221. violations.append((function_name, node.lineno))
  1222. if function_name == "run" and isinstance(function, ast.Attribute):
  1223. if isinstance(function.value, ast.Name):
  1224. one_shot_calls.append(function.value.id)
  1225. self.assertEqual(violations, [])
  1226. self.assertEqual(one_shot_calls.count("otp_guard"), 1)
  1227. self.assertEqual(one_shot_calls.count("avanti_guard"), 1)
  1228. self.assertIn("button.disabled = true", CALENDAR_GUARD_SCRIPT)
  1229. self.assertIn('OneShotAction("OTP")', source)
  1230. self.assertIn('OneShotAction("AVANTI")', source)
  1231. self.assertIn(
  1232. '#datetimepicker',
  1233. NEXT_MONTH_CONTROL_SCRIPT,
  1234. )
  1235. self.assertIn(
  1236. 'th.dtpicker-next',
  1237. NEXT_MONTH_CONTROL_SCRIPT,
  1238. )
  1239. for forbidden_selector in (
  1240. "btnPrenotaNoOtp",
  1241. "InsertNewBooking",
  1242. ".fascia",
  1243. ".events a",
  1244. "a.next",
  1245. "data-action",
  1246. "fetch(",
  1247. "XMLHttpRequest",
  1248. ):
  1249. self.assertNotIn(
  1250. forbidden_selector,
  1251. NEXT_MONTH_CONTROL_SCRIPT,
  1252. )
  1253. if __name__ == "__main__":
  1254. unittest.main()