test_ita_plugin.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. import inspect
  2. import json
  3. import shutil
  4. import subprocess
  5. import sys
  6. import threading
  7. import types
  8. import unittest
  9. from datetime import date
  10. from pathlib import Path
  11. from tempfile import TemporaryDirectory
  12. from unittest.mock import Mock, patch
  13. from plugins.ita_plugin import (
  14. BOOKING_FORM_DISCOVERY_STOP_LABEL,
  15. BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
  16. PERSISTENT_BROWSER_PROFILE_KEY,
  17. SERVICE_LINK_WAIT_SECONDS,
  18. SERVICE_LIST_DIAGNOSTIC_SCRIPT,
  19. ItaAuthenticationChallengeError,
  20. ItaPlugin,
  21. ItaTargetServiceLinkMissingError,
  22. )
  23. try:
  24. from booker import OrderBookerGCO
  25. except ModuleNotFoundError as exc:
  26. if exc.name != "redis":
  27. raise
  28. redis_stub = types.ModuleType("redis")
  29. redis_stub.Redis = Mock
  30. with patch.dict(sys.modules, {"redis": redis_stub}):
  31. from booker import OrderBookerGCO
  32. from vs_types import (
  33. AppointmentType,
  34. AvailabilityStatus,
  35. BizLogicError,
  36. GroupConfig,
  37. SessionExpiredOrInvalidError,
  38. Task,
  39. VSAccount,
  40. VSPlgConfig,
  41. VSQueryResult,
  42. )
  43. class FakeChromiumOptions:
  44. def set_local_port(self, _port):
  45. return self
  46. def set_user_data_path(self, _path):
  47. return self
  48. def set_paths(self, **_kwargs):
  49. return self
  50. def set_argument(self, _argument):
  51. return self
  52. def headless(self, _enabled):
  53. return self
  54. class FakeWait:
  55. def doc_loaded(self):
  56. return None
  57. def load_start(self):
  58. return None
  59. class FakeRect:
  60. viewport_size = (1920, 1080)
  61. class FakeElement:
  62. def __init__(self, page, name):
  63. self.page = page
  64. self.name = name
  65. def input(self, value, clear=False):
  66. self.page.input_values[self.name] = {
  67. "value": value,
  68. "clear": clear,
  69. }
  70. class FakePage:
  71. URLS = {
  72. "landing": "https://prenotami.esteri.it/",
  73. "pingid": (
  74. "https://iam.esteri.it/signin/?realm=/external"
  75. "&state=sensitive-state"
  76. "&code_challenge=sensitive-challenge#/"
  77. ),
  78. "dashboard": "https://prenotami.esteri.it/UserArea",
  79. "services": "https://prenotami.esteri.it/Services",
  80. "radware": (
  81. "https://validate.perfdrive.com/"
  82. "8ab9454422ad153e7d4ce3a5b41556a7/"
  83. ),
  84. }
  85. def __init__(
  86. self,
  87. *,
  88. submit_succeeds=True,
  89. has_services_link=True,
  90. login_target="pingid",
  91. ):
  92. self.state = "landing"
  93. self.submit_succeeds = submit_succeeds
  94. self.has_services_link = has_services_link
  95. self.login_target = login_target
  96. self.wait = FakeWait()
  97. self.rect = FakeRect()
  98. self.clicked = []
  99. self.input_values = {}
  100. self.refresh_calls = 0
  101. self.quit_called = False
  102. self.quit_force = None
  103. @property
  104. def url(self):
  105. return self.URLS[self.state]
  106. @property
  107. def title(self):
  108. return {
  109. "landing": "Login",
  110. "pingid": "Sign in",
  111. "dashboard": "Home",
  112. "services": "Services",
  113. "radware": "Access Denied",
  114. }[self.state]
  115. @property
  116. def html(self):
  117. return ""
  118. def get(self, _url):
  119. self.state = "landing"
  120. def refresh(self):
  121. self.refresh_calls += 1
  122. def quit(self, force=False):
  123. self.quit_called = True
  124. self.quit_force = force
  125. def ele(self, selector, timeout=None):
  126. del timeout
  127. if selector == "tag:a@@href=/Language/ChangeLanguage?lang=2":
  128. return FakeElement(self, "language") if self.state == "landing" else None
  129. if selector == "#pingid-button" and self.state == "landing":
  130. return FakeElement(self, "login")
  131. if selector == "@name=callback_1" and self.state == "pingid":
  132. return FakeElement(self, "username")
  133. if selector == "@name=callback_2" and self.state == "pingid":
  134. return FakeElement(self, "password")
  135. if selector == "tag:button@type=submit" and self.state == "pingid":
  136. return FakeElement(self, "submit")
  137. if selector == ".app-menu" and self.state == "dashboard":
  138. return FakeElement(self, "app-menu")
  139. if (
  140. selector == "@href=/Services"
  141. and self.state == "dashboard"
  142. and self.has_services_link
  143. ):
  144. return FakeElement(self, "book")
  145. return None
  146. class FakeMouse:
  147. def __init__(self, page, debug=False):
  148. self.page = page
  149. self.debug = debug
  150. def move(self, _x, _y):
  151. return None
  152. def human_click_ele(self, element):
  153. if element is None:
  154. raise AssertionError("The state machine attempted to click a missing element")
  155. self.page.clicked.append(element.name)
  156. if element.name == "login":
  157. self.page.state = self.page.login_target
  158. elif element.name == "submit" and self.page.submit_succeeds:
  159. self.page.state = "dashboard"
  160. elif element.name == "book":
  161. self.page.state = "services"
  162. class FakeKeyboard:
  163. def __init__(self, page):
  164. self.page = page
  165. class FakeQueryWait:
  166. def __init__(self):
  167. self.load_start_calls = 0
  168. self.doc_loaded_calls = 0
  169. def load_start(self):
  170. self.load_start_calls += 1
  171. def doc_loaded(self):
  172. self.doc_loaded_calls += 1
  173. class FakeQueryElement:
  174. def __init__(
  175. self,
  176. page,
  177. name,
  178. attributes=None,
  179. *,
  180. text="",
  181. property_value=None,
  182. ):
  183. self.page = page
  184. self.name = name
  185. self.attributes = attributes or {}
  186. self.text = text
  187. self.value = property_value
  188. def attr(self, name):
  189. return self.attributes.get(name)
  190. class FakeQueryPage:
  191. URLS = {
  192. "services": "https://prenotami.esteri.it/Services",
  193. "user_area": "https://prenotami.esteri.it/UserArea",
  194. "no_slots": "https://prenotami.esteri.it/Services",
  195. "property_no_slots": "https://prenotami.esteri.it/Services",
  196. "visible_no_slots": "https://prenotami.esteri.it/Services",
  197. "unknown_popup": "https://prenotami.esteri.it/Services",
  198. "empty_warning": "https://prenotami.esteri.it/Services",
  199. "login": "https://iam.esteri.it/login/oauth2/authorize",
  200. "calendar": "https://prenotami.esteri.it/BookingCalendar",
  201. "unknown": "https://prenotami.esteri.it/Unexpected",
  202. }
  203. def __init__(
  204. self,
  205. outcome="no_slots",
  206. *,
  207. has_link=True,
  208. initial_state="services",
  209. service_id=1321,
  210. already_booked_notice_rows=0,
  211. ):
  212. self.outcome = outcome
  213. self.has_link = has_link
  214. self.state = initial_state
  215. self.service_id = service_id
  216. self.already_booked_notice_rows = already_booked_notice_rows
  217. self.wait = FakeQueryWait()
  218. self.clicked = []
  219. self.get_calls = []
  220. self.looked_up = []
  221. self.run_js_calls = []
  222. @property
  223. def url(self):
  224. if self.state in {"booking_form", "booking_path_without_form"}:
  225. return (
  226. "https://prenotami.esteri.it/Services/Booking/"
  227. f"{self.service_id}"
  228. )
  229. return self.URLS[self.state]
  230. def get(self, url):
  231. self.get_calls.append(url)
  232. if url != "https://prenotami.esteri.it/Services":
  233. raise AssertionError(f"Unexpected query navigation: {url}")
  234. self.state = "services"
  235. def run_js(self, script):
  236. self.run_js_calls.append(script)
  237. if "coordinate:ita-service-list-structure" in script:
  238. return {
  239. "path": "/Services",
  240. "ready_state": "complete",
  241. "table_count": 1,
  242. "row_count": 0,
  243. "booking_link_count": 0,
  244. "target_link_count": 0,
  245. "already_booked_notice_row_count": self.already_booked_notice_rows,
  246. }
  247. if self.state != "booking_form":
  248. return None
  249. return {
  250. "path": f"/Services/Booking/{self.service_id}",
  251. "form": {
  252. "method": "POST",
  253. "action_path": f"/Services/Booking/{self.service_id}",
  254. "untrusted": "must-not-survive",
  255. },
  256. "field_count": 2,
  257. "fields_truncated": False,
  258. "fields": [
  259. {
  260. "tag": "input",
  261. "type": "hidden",
  262. "id": "RequestToken",
  263. "name": "__RequestVerificationToken",
  264. "required": False,
  265. "value": "must-not-survive",
  266. },
  267. {
  268. "tag": "select",
  269. "type": None,
  270. "id": "BookingType",
  271. "name": "BookingType",
  272. "required": True,
  273. },
  274. ],
  275. "button_count": 1,
  276. "buttons_truncated": False,
  277. "buttons": [
  278. {
  279. "tag": "button",
  280. "type": "submit",
  281. "id": "btnAvanti",
  282. "name": None,
  283. "text": "Avanti",
  284. "value": "must-not-survive",
  285. }
  286. ],
  287. "untrusted": "must-not-survive",
  288. }
  289. def ele(self, selector, timeout=None):
  290. self.looked_up.append((selector, timeout))
  291. if selector == "#pingid-button" and self.state == "login":
  292. return FakeQueryElement(self, "login")
  293. if (
  294. selector
  295. == f"tag:a@@href=/Services/Booking/{self.service_id}"
  296. and self.state == "services"
  297. and self.has_link
  298. ):
  299. return FakeQueryElement(self, f"booking-{self.service_id}")
  300. if selector == "#WNotAvailable" and self.state == "no_slots":
  301. return FakeQueryElement(
  302. self,
  303. "not-available",
  304. {"value": "No appointments are currently available."},
  305. )
  306. if selector == "#WNotAvailable" and self.state == "property_no_slots":
  307. return FakeQueryElement(
  308. self,
  309. "property-not-available",
  310. property_value="No appointments are currently available.",
  311. )
  312. if selector == "#WNotAvailable" and self.state == "empty_warning":
  313. return FakeQueryElement(self, "empty-warning", {"value": " "})
  314. if selector == ".jconfirm-content" and self.state == "visible_no_slots":
  315. return FakeQueryElement(
  316. self,
  317. "visible-not-available",
  318. text=(
  319. " STANTE L’ELEVATA RICHIESTA\n"
  320. "i posti disponibili per il servizio scelto sono esauriti. "
  321. ),
  322. )
  323. if selector == ".jconfirm-content" and self.state == "unknown_popup":
  324. return FakeQueryElement(
  325. self,
  326. "unknown-popup",
  327. text="Il servizio richiede una nuova verifica.",
  328. )
  329. if selector == "#bookingForm" and self.state == "booking_form":
  330. return FakeQueryElement(self, "booking-form")
  331. return None
  332. class FakeQueryMouse:
  333. def __init__(self, page):
  334. self.page = page
  335. def human_click_ele(self, element):
  336. if element is None:
  337. raise AssertionError("Query attempted to click a missing element")
  338. self.page.clicked.append(element.name)
  339. self.page.state = self.page.outcome
  340. class ItaPluginRandomSleepTests(unittest.TestCase):
  341. def test_random_sleep_uses_generated_duration_within_requested_range(self):
  342. plugin = ItaPlugin.__new__(ItaPlugin)
  343. plugin.group_id = "test-group"
  344. plugin.logger = Mock()
  345. plugin.page = None
  346. plugin.root_workspace = "/nonexistent/ita-plugin-unit-test"
  347. plugin.tunnel = None
  348. with (
  349. patch("plugins.ita_plugin.random.uniform", return_value=4.25) as uniform,
  350. patch("plugins.ita_plugin.time.sleep") as sleep,
  351. ):
  352. plugin._random_sleep(3, 5)
  353. uniform.assert_called_once_with(3, 5)
  354. sleep.assert_called_once_with(4.25)
  355. plugin.logger.assert_called_once_with(
  356. "[ItaPlugin] [test-group] "
  357. "Anti-Rate-Limit: Sleeping for 4.25 seconds..."
  358. )
  359. class ItaPluginCreateSessionStateMachineTests(unittest.TestCase):
  360. @staticmethod
  361. def _config():
  362. return VSPlgConfig(
  363. account=VSAccount(
  364. id=0,
  365. username="offline-test@example.test",
  366. password="offline-password",
  367. )
  368. )
  369. def test_stops_at_authenticated_user_area_without_opening_services(self):
  370. fake_page = FakePage()
  371. config = self._config()
  372. logger = Mock()
  373. with TemporaryDirectory() as workspace:
  374. with patch(
  375. "plugins.ita_plugin.os.path.abspath",
  376. return_value=str(Path(workspace)),
  377. ):
  378. plugin = ItaPlugin("offline-state-machine")
  379. plugin.set_log(logger)
  380. plugin.set_config(config)
  381. with (
  382. patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
  383. patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
  384. patch("plugins.ita_plugin.HumanMouse", FakeMouse),
  385. patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
  386. patch("plugins.ita_plugin.time.sleep"),
  387. ):
  388. try:
  389. plugin.create_session()
  390. finally:
  391. plugin.cleanup()
  392. self.assertEqual(fake_page.state, "dashboard")
  393. self.assertGreater(plugin.session_create_time, 0)
  394. self.assertEqual(
  395. fake_page.clicked,
  396. ["login", "username", "password", "submit"],
  397. )
  398. self.assertEqual(
  399. fake_page.input_values,
  400. {
  401. "username": {
  402. "value": "offline-test@example.test",
  403. "clear": True,
  404. },
  405. "password": {
  406. "value": "offline-password",
  407. "clear": True,
  408. },
  409. },
  410. )
  411. self.assertEqual(fake_page.refresh_calls, 0)
  412. self.assertTrue(fake_page.quit_called)
  413. log_output = "\n".join(
  414. call.args[0] for call in logger.call_args_list if call.args
  415. )
  416. self.assertIn("https://iam.esteri.it/signin/", log_output)
  417. self.assertNotIn("sensitive-state", log_output)
  418. self.assertNotIn("sensitive-challenge", log_output)
  419. def test_never_resubmits_credentials_or_refreshes_after_login_submission(self):
  420. fake_page = FakePage(submit_succeeds=False)
  421. config = self._config()
  422. with TemporaryDirectory() as workspace:
  423. with patch(
  424. "plugins.ita_plugin.os.path.abspath",
  425. return_value=str(Path(workspace)),
  426. ):
  427. plugin = ItaPlugin("offline-stalled-login")
  428. plugin.set_log(Mock())
  429. plugin.set_config(config)
  430. with (
  431. patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
  432. patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
  433. patch("plugins.ita_plugin.HumanMouse", FakeMouse),
  434. patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
  435. patch("plugins.ita_plugin.time.sleep"),
  436. ):
  437. try:
  438. with self.assertRaisesRegex(
  439. BizLogicError,
  440. "Failed to create authenticated /UserArea session",
  441. ):
  442. plugin.create_session()
  443. finally:
  444. plugin.cleanup()
  445. self.assertEqual(fake_page.clicked.count("login"), 1)
  446. self.assertEqual(fake_page.clicked.count("username"), 1)
  447. self.assertEqual(fake_page.clicked.count("password"), 1)
  448. self.assertEqual(fake_page.clicked.count("submit"), 1)
  449. self.assertEqual(fake_page.refresh_calls, 0)
  450. def test_requires_user_area_services_link_as_authentication_marker(self):
  451. fake_page = FakePage(has_services_link=False)
  452. config = self._config()
  453. with TemporaryDirectory() as workspace:
  454. with patch(
  455. "plugins.ita_plugin.os.path.abspath",
  456. return_value=str(Path(workspace)),
  457. ):
  458. plugin = ItaPlugin("offline-incomplete-dashboard")
  459. plugin.set_log(Mock())
  460. plugin.set_config(config)
  461. with (
  462. patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
  463. patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
  464. patch("plugins.ita_plugin.HumanMouse", FakeMouse),
  465. patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
  466. patch("plugins.ita_plugin.time.sleep"),
  467. ):
  468. try:
  469. with self.assertRaisesRegex(
  470. BizLogicError,
  471. "Failed to create authenticated /UserArea session",
  472. ):
  473. plugin.create_session()
  474. finally:
  475. plugin.cleanup()
  476. self.assertEqual(fake_page.state, "dashboard")
  477. self.assertEqual(fake_page.clicked.count("submit"), 1)
  478. def test_create_session_source_has_no_language_or_services_navigation(self):
  479. create_session_source = inspect.getsource(ItaPlugin.create_session)
  480. self.assertNotIn("ChangeLanguage", create_session_source)
  481. self.assertNotIn("book_btn", create_session_source)
  482. def test_radware_validation_is_classified_before_credentials_or_refresh(self):
  483. fake_page = FakePage(login_target="radware")
  484. config = self._config()
  485. logger = Mock()
  486. with TemporaryDirectory() as workspace:
  487. with patch(
  488. "plugins.ita_plugin.os.path.abspath",
  489. return_value=str(Path(workspace)),
  490. ):
  491. plugin = ItaPlugin("offline-radware")
  492. plugin.set_log(logger)
  493. plugin.set_config(config)
  494. with (
  495. patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
  496. patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
  497. patch("plugins.ita_plugin.HumanMouse", FakeMouse),
  498. patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
  499. patch("plugins.ita_plugin.time.sleep"),
  500. ):
  501. try:
  502. with self.assertRaisesRegex(
  503. ItaAuthenticationChallengeError,
  504. "Radware browser validation",
  505. ):
  506. plugin.create_session()
  507. finally:
  508. plugin.cleanup()
  509. self.assertEqual(fake_page.clicked, ["login"])
  510. self.assertEqual(fake_page.input_values, {})
  511. self.assertEqual(fake_page.refresh_calls, 0)
  512. log_output = "\n".join(
  513. call.args[0] for call in logger.call_args_list if call.args
  514. )
  515. self.assertIn(
  516. "https://validate.perfdrive.com/<redacted-challenge>",
  517. log_output,
  518. )
  519. self.assertNotIn("8ab9454422ad153e7d4ce3a5b41556a7", log_output)
  520. class ItaPluginPersistentProfileTests(unittest.TestCase):
  521. @staticmethod
  522. def _new_plugin(*, transient_root: Path, profile_path: Path) -> ItaPlugin:
  523. with patch(
  524. "plugins.ita_plugin.os.path.abspath",
  525. return_value=str(transient_root),
  526. ):
  527. plugin = ItaPlugin("offline-persistent-profile")
  528. plugin.set_config(
  529. VSPlgConfig(
  530. account=VSAccount(
  531. id=0,
  532. username="offline-test@example.test",
  533. password="offline-password",
  534. ),
  535. free_config={
  536. PERSISTENT_BROWSER_PROFILE_KEY: str(profile_path),
  537. },
  538. )
  539. )
  540. return plugin
  541. def test_cleanup_preserves_explicit_persistent_profile(self):
  542. with TemporaryDirectory() as temp_dir:
  543. base = Path(temp_dir)
  544. profile_path = base / "persistent" / "profile-id"
  545. profile_path.mkdir(parents=True, mode=0o700)
  546. profile_path.chmod(0o700)
  547. marker = profile_path / "cookie-state"
  548. marker.write_text("offline", encoding="utf-8")
  549. transient_root = base / "transient"
  550. plugin = self._new_plugin(
  551. transient_root=transient_root,
  552. profile_path=profile_path,
  553. )
  554. plugin.cleanup()
  555. self.assertEqual(plugin.user_data_path, str(profile_path.resolve()))
  556. self.assertTrue(marker.exists())
  557. self.assertFalse(transient_root.exists())
  558. def test_default_cleanup_still_deletes_transient_profile(self):
  559. with TemporaryDirectory() as temp_dir:
  560. transient_root = Path(temp_dir) / "transient"
  561. with patch(
  562. "plugins.ita_plugin.os.path.abspath",
  563. return_value=str(transient_root),
  564. ):
  565. plugin = ItaPlugin("offline-transient-profile")
  566. marker = Path(plugin.user_data_path) / "cookie-state"
  567. marker.parent.mkdir(parents=True)
  568. marker.write_text("offline", encoding="utf-8")
  569. plugin.cleanup()
  570. self.assertFalse(transient_root.exists())
  571. def test_persistent_profile_is_exclusively_locked_until_cleanup(self):
  572. with TemporaryDirectory() as temp_dir:
  573. base = Path(temp_dir)
  574. profile_path = base / "persistent" / "profile-id"
  575. profile_path.mkdir(parents=True, mode=0o700)
  576. profile_path.chmod(0o700)
  577. first = self._new_plugin(
  578. transient_root=base / "transient-one",
  579. profile_path=profile_path,
  580. )
  581. second = self._new_plugin(
  582. transient_root=base / "transient-two",
  583. profile_path=profile_path,
  584. )
  585. try:
  586. first._acquire_persistent_profile_lock()
  587. with self.assertRaisesRegex(BizLogicError, "already in use"):
  588. second._acquire_persistent_profile_lock()
  589. finally:
  590. first.cleanup()
  591. try:
  592. second._acquire_persistent_profile_lock()
  593. self.assertIsNotNone(second._profile_lock_handle)
  594. finally:
  595. second.cleanup()
  596. def test_rejects_persistent_profile_inside_temporary_workspace(self):
  597. with TemporaryDirectory() as temp_dir:
  598. transient_root = Path(temp_dir) / "transient"
  599. profile_path = transient_root / "user_data"
  600. profile_path.mkdir(parents=True, mode=0o700)
  601. profile_path.chmod(0o700)
  602. with self.assertRaisesRegex(
  603. BizLogicError,
  604. "outside the temporary workspace",
  605. ):
  606. self._new_plugin(
  607. transient_root=transient_root,
  608. profile_path=profile_path,
  609. )
  610. @unittest.skipUnless(shutil.which("node"), "Node is required for the DOM-script fixture")
  611. class ItaServiceNoticeScriptTests(unittest.TestCase):
  612. def _inspect(self, rows):
  613. # Execute the production JS against a synthetic DOM, never a live tab.
  614. harness = r"""
  615. const payload = JSON.parse(require('fs').readFileSync(0, 'utf8'));
  616. const rows = payload.rows.map((cells) => ({cells: cells.map((cell) => ({
  617. innerText: cell.text,
  618. getClientRects: () => cell.noSize ? [] : [{}],
  619. style: {visibility: cell.visibility || 'visible'},
  620. }))}));
  621. const table = {querySelectorAll: (selector) => {
  622. if (selector !== 'tbody tr') throw Error('unexpected table selector');
  623. return rows;
  624. }};
  625. const document = {readyState: 'complete', querySelectorAll: (selector) => {
  626. if (selector === 'table') return [table];
  627. if (selector === 'a[href^="/Services/Booking/"]') return [];
  628. throw Error('unexpected document selector');
  629. }};
  630. const window = {location: {pathname: '/Services'}, getComputedStyle: (cell) => cell.style};
  631. process.stdout.write(JSON.stringify(new Function('document', 'window', payload.script)(document, window)));
  632. """
  633. result = subprocess.run(
  634. [shutil.which("node"), "-e", harness],
  635. input=json.dumps({"rows": rows, "script": SERVICE_LIST_DIAGNOSTIC_SCRIPT}),
  636. text=True, capture_output=True, check=True, timeout=10,
  637. )
  638. return json.loads(result.stdout)
  639. def test_only_exact_rendered_notice_matches(self):
  640. notice = "Prenotazione già effettuata per questo servizio"
  641. for cell, expected in (
  642. ({"text": notice}, 1),
  643. ({"text": " PRENOTAZIONE GIÀ\nEFFETTUATA PER QUESTO\u00a0SERVIZIO. "}, 1),
  644. ({"text": notice, "noSize": True}, 0),
  645. ({"text": notice, "visibility": "hidden"}, 0),
  646. ({"text": "Non " + notice}, 0),
  647. ({"text": "PRENOTA"}, 0),
  648. ({"text": "Annullata"}, 0),
  649. ({"text": "Unknown notice"}, 0),
  650. ):
  651. with self.subTest(cell=cell):
  652. self.assertEqual(self._inspect([[cell]])["already_booked_notice_row_count"], expected)
  653. def test_counts_rows_not_cells_and_does_not_export_row_content(self):
  654. notice = {"text": "Prenotazione già effettuata per questo servizio"}
  655. result = self._inspect([[notice, notice, {"text": "synthetic-private-row-value"}]])
  656. self.assertEqual(result["already_booked_notice_row_count"], 1)
  657. self.assertEqual(result["row_count"], 1)
  658. self.assertEqual(result["target_link_count"], 0)
  659. self.assertNotIn("synthetic-private-row-value", json.dumps(result))
  660. self.assertNotIn("Prenotazione", json.dumps(result))
  661. class ItaPluginQuerySafetyTests(unittest.TestCase):
  662. @staticmethod
  663. def _appointment_type(
  664. routing_key="slot.dub.it.tourist",
  665. *,
  666. city="Dublin",
  667. ):
  668. return AppointmentType(
  669. routing_key=routing_key,
  670. city=city,
  671. country="Italy",
  672. visa_type="Tourist",
  673. )
  674. @staticmethod
  675. def _plugin(
  676. page,
  677. *,
  678. service_id=1321,
  679. routing_key="slot.dub.it.tourist",
  680. query_mode="services_probe",
  681. capability="services_probe_only",
  682. lookahead_months=3,
  683. ):
  684. plugin = ItaPlugin.__new__(ItaPlugin)
  685. plugin.group_id = "offline-query"
  686. plugin.logger = Mock()
  687. plugin.page = page
  688. plugin.mouse = FakeQueryMouse(page)
  689. route = {
  690. "service_id": service_id,
  691. "capability": capability,
  692. }
  693. if capability == "single_schengen_tourism":
  694. route.update(
  695. {
  696. "calendar_scan": {
  697. "lookahead_months": lookahead_months,
  698. },
  699. "form": {
  700. "booking_type_control_id": "typeofbookingddl",
  701. "booking_type_value": "1",
  702. "booking_type_labels": ["Single booking"],
  703. "purpose_control_id": "ddls_0",
  704. "purpose_value": "42",
  705. "purpose_labels": ["Tourism"],
  706. },
  707. }
  708. )
  709. plugin.free_config = {
  710. "query_mode": query_mode,
  711. "final_submit_enabled": False,
  712. "apt_configs": {
  713. routing_key: route,
  714. },
  715. }
  716. plugin.ita_url = "https://prenotami.esteri.it"
  717. plugin.root_workspace = "/nonexistent/ita-plugin-query-test"
  718. plugin.tunnel = None
  719. plugin._calendar_query_route_key = (
  720. routing_key if query_mode == "calendar" else None
  721. )
  722. return plugin
  723. def test_returns_none_available_only_for_non_empty_w_not_available(self):
  724. page = FakeQueryPage(outcome="no_slots")
  725. plugin = self._plugin(page)
  726. apt_type = self._appointment_type()
  727. result = plugin.query(apt_type)
  728. self.assertFalse(result.success)
  729. self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
  730. self.assertEqual(result.apt_type, apt_type)
  731. self.assertEqual(page.clicked, ["booking-1321"])
  732. self.assertEqual(page.wait.load_start_calls, 1)
  733. self.assertEqual(page.wait.doc_loaded_calls, 2)
  734. def test_returns_none_available_for_property_only_w_not_available(self):
  735. page = FakeQueryPage(outcome="property_no_slots")
  736. plugin = self._plugin(page)
  737. result = plugin.query(self._appointment_type())
  738. self.assertFalse(result.success)
  739. self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
  740. self.assertEqual(page.clicked, ["booking-1321"])
  741. def test_returns_none_available_for_verified_visible_italian_notice(self):
  742. page = FakeQueryPage(outcome="visible_no_slots")
  743. plugin = self._plugin(page)
  744. result = plugin.query(self._appointment_type())
  745. self.assertFalse(result.success)
  746. self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
  747. self.assertEqual(page.clicked, ["booking-1321"])
  748. def test_unknown_visible_notice_fails_closed(self):
  749. page = FakeQueryPage(outcome="unknown_popup")
  750. plugin = self._plugin(page)
  751. with self.assertRaisesRegex(BizLogicError, "unrecognized visible"):
  752. plugin.query(self._appointment_type())
  753. self.assertEqual(page.clicked, ["booking-1321"])
  754. def test_changed_notice_is_not_guessed_as_no_availability(self):
  755. plugin = self._plugin(FakeQueryPage())
  756. status = plugin._classify_service_notice(
  757. "I posti disponibili per il servizio scelto non sono esauriti."
  758. )
  759. self.assertIsNone(status)
  760. def test_reloads_services_before_each_no_slot_probe(self):
  761. page = FakeQueryPage(outcome="no_slots")
  762. plugin = self._plugin(page)
  763. apt_type = self._appointment_type()
  764. first_result = plugin.query(apt_type)
  765. second_result = plugin.query(apt_type)
  766. self.assertFalse(first_result.success)
  767. self.assertFalse(second_result.success)
  768. self.assertEqual(
  769. page.get_calls,
  770. [
  771. "https://prenotami.esteri.it/Services",
  772. "https://prenotami.esteri.it/Services",
  773. ],
  774. )
  775. self.assertEqual(page.clicked, ["booking-1321", "booking-1321"])
  776. self.assertEqual(page.wait.load_start_calls, 2)
  777. self.assertEqual(page.wait.doc_loaded_calls, 4)
  778. def test_empty_w_not_available_is_not_treated_as_no_slots(self):
  779. page = FakeQueryPage(outcome="empty_warning")
  780. plugin = self._plugin(page)
  781. with self.assertRaisesRegex(BizLogicError, "non-empty"):
  782. plugin.query(self._appointment_type())
  783. self.assertEqual(page.clicked, ["booking-1321"])
  784. def test_booking_form_branch_returns_bls_style_weak_signal(self):
  785. page = FakeQueryPage(outcome="booking_form")
  786. plugin = self._plugin(page)
  787. result = plugin.query(self._appointment_type())
  788. self.assertTrue(result.success)
  789. self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
  790. self.assertIsNone(result.earliest_date)
  791. self.assertEqual(result.availability, [])
  792. self.assertEqual(page.clicked, ["booking-1321"])
  793. def test_booking_form_state_can_be_reprobed_on_the_next_query_cycle(self):
  794. page = FakeQueryPage(outcome="booking_form")
  795. plugin = self._plugin(page)
  796. apt_type = self._appointment_type()
  797. first_result = plugin.query(apt_type)
  798. second_result = plugin.query(apt_type)
  799. self.assertTrue(first_result.success)
  800. self.assertTrue(second_result.success)
  801. self.assertEqual(
  802. page.get_calls,
  803. [
  804. "https://prenotami.esteri.it/Services",
  805. "https://prenotami.esteri.it/Services",
  806. ],
  807. )
  808. self.assertEqual(page.clicked, ["booking-1321", "booking-1321"])
  809. def test_booking_path_without_form_fails_closed(self):
  810. page = FakeQueryPage(outcome="booking_path_without_form")
  811. plugin = self._plugin(page)
  812. with self.assertRaisesRegex(BizLogicError, "without #bookingForm"):
  813. plugin.query(self._appointment_type())
  814. self.assertEqual(page.clicked, ["booking-1321"])
  815. def test_missing_target_link_is_a_structure_error_not_no_slots(self):
  816. page = FakeQueryPage(has_link=False)
  817. plugin = self._plugin(page)
  818. with self.assertRaisesRegex(
  819. ItaTargetServiceLinkMissingError,
  820. "target service link is missing",
  821. ):
  822. plugin.query(self._appointment_type())
  823. self.assertEqual(page.clicked, [])
  824. self.assertIn(
  825. ("tag:a@@href=/Services/Booking/1321", SERVICE_LINK_WAIT_SECONDS),
  826. page.looked_up,
  827. )
  828. self.assertEqual(
  829. plugin.last_service_list_structure,
  830. {
  831. "path": "/Services",
  832. "ready_state": "complete",
  833. "table_count": 1,
  834. "row_count": 0,
  835. "booking_link_count": 0,
  836. "target_link_count": 0,
  837. "already_booked_notice_row_count": 0,
  838. },
  839. )
  840. def test_missing_link_with_booked_notice_reports_context_without_attribution(self):
  841. page = FakeQueryPage(has_link=False, already_booked_notice_rows=1)
  842. plugin = self._plugin(page)
  843. with self.assertRaises(ItaTargetServiceLinkMissingError) as raised:
  844. plugin.query(self._appointment_type())
  845. self.assertIn("Services contains an already-booked notice", str(raised.exception))
  846. self.assertIn("not bound to the configured service ID", str(raised.exception))
  847. self.assertEqual(plugin.last_service_list_structure["already_booked_notice_row_count"], 1)
  848. self.assertEqual(page.clicked, [])
  849. self.assertEqual(page.get_calls, ["https://prenotami.esteri.it/Services"])
  850. def test_existing_other_service_booking_does_not_block_present_target_link(self):
  851. page = FakeQueryPage(outcome="booking_form", already_booked_notice_rows=1)
  852. plugin = self._plugin(page)
  853. result = plugin.query(self._appointment_type())
  854. self.assertTrue(result.success)
  855. self.assertEqual(page.clicked, ["booking-1321"])
  856. self.assertFalse(any("service-list-structure" in script for script in page.run_js_calls))
  857. def test_invalid_notice_counts_do_not_claim_an_existing_booking(self):
  858. for raw_count in (None, True, "1", -1, {}, []):
  859. with self.subTest(raw_count=raw_count):
  860. page = FakeQueryPage(has_link=False, already_booked_notice_rows=raw_count)
  861. plugin = self._plugin(page)
  862. with self.assertRaises(ItaTargetServiceLinkMissingError) as raised:
  863. plugin.query(self._appointment_type())
  864. self.assertNotIn("already-booked notice", str(raised.exception))
  865. self.assertEqual(page.clicked, [])
  866. def test_book_propagates_existing_notice_without_creating_a_success(self):
  867. page = FakeQueryPage(has_link=False, already_booked_notice_rows=1)
  868. plugin = self._plugin(page)
  869. trigger = VSQueryResult(apt_type=self._appointment_type())
  870. with self.assertRaisesRegex(ItaTargetServiceLinkMissingError, "already-booked notice"):
  871. plugin.book(trigger)
  872. self.assertIsNone(plugin.last_booking_precommit)
  873. self.assertEqual(page.clicked, [])
  874. def test_invalid_route_service_id_is_a_configuration_error(self):
  875. page = FakeQueryPage()
  876. plugin = self._plugin(page, service_id=0)
  877. with self.assertRaisesRegex(
  878. BizLogicError,
  879. "route configuration rejected.*positive_integer_required",
  880. ):
  881. plugin.query(self._appointment_type())
  882. self.assertEqual(page.clicked, [])
  883. def test_second_sede_uses_the_same_query_path_without_a_city_branch(self):
  884. routing_key = "slot.hkg.it.tourist"
  885. page = FakeQueryPage(
  886. outcome="booking_form",
  887. service_id=4937,
  888. )
  889. plugin = self._plugin(
  890. page,
  891. service_id=4937,
  892. routing_key=routing_key,
  893. )
  894. result = plugin.query(
  895. self._appointment_type(routing_key, city="Hong Kong")
  896. )
  897. self.assertTrue(result.success)
  898. self.assertEqual(page.clicked, ["booking-4937"])
  899. def test_calendar_mode_returns_vfs_style_earliest_date_only(self):
  900. routing_key = "slot.sample.it.tourist"
  901. page = FakeQueryPage(initial_state="calendar", service_id=9001)
  902. plugin = self._plugin(
  903. page,
  904. service_id=9001,
  905. routing_key=routing_key,
  906. query_mode="calendar",
  907. capability="single_schengen_tourism",
  908. lookahead_months=12,
  909. )
  910. apt_type = self._appointment_type(
  911. routing_key,
  912. city="Sample City",
  913. )
  914. scan = types.SimpleNamespace(
  915. earliest_available_date=date(2026, 10, 12)
  916. )
  917. with patch(
  918. "plugins.ita_plugin.scan_until_first_available_month",
  919. return_value=scan,
  920. ) as scanner:
  921. result = plugin.query(apt_type)
  922. scanner.assert_called_once_with(
  923. page,
  924. lookahead_months=12,
  925. log=plugin._log,
  926. )
  927. self.assertTrue(result.success)
  928. self.assertEqual(
  929. result.availability_status,
  930. AvailabilityStatus.Available,
  931. )
  932. self.assertEqual(
  933. result.earliest_date.strftime("%Y-%m-%d"),
  934. "2026-10-12",
  935. )
  936. self.assertEqual(len(result.availability), 1)
  937. self.assertEqual(
  938. result.availability[0].date.strftime("%Y-%m-%d"),
  939. "2026-10-12",
  940. )
  941. self.assertEqual(result.availability[0].times, [])
  942. self.assertEqual(page.clicked, [])
  943. self.assertIs(plugin.last_calendar_query_scan, scan)
  944. def test_calendar_diagnostic_does_not_survive_a_failed_query(self):
  945. routing_key = "slot.sample.it.tourist"
  946. page = FakeQueryPage(initial_state="calendar", service_id=9001)
  947. plugin = self._plugin(
  948. page,
  949. service_id=9001,
  950. routing_key=routing_key,
  951. query_mode="calendar",
  952. capability="single_schengen_tourism",
  953. )
  954. plugin.last_calendar_query_scan = object()
  955. plugin._calendar_query_route_key = None
  956. with self.assertRaisesRegex(BizLogicError, "route continuity"):
  957. plugin.query(self._appointment_type(routing_key, city="Sample City"))
  958. self.assertIsNone(plugin.last_calendar_query_scan)
  959. def test_calendar_mode_returns_none_only_after_scanner_exhaustion(self):
  960. routing_key = "slot.sample.it.tourist"
  961. page = FakeQueryPage(initial_state="calendar", service_id=9001)
  962. plugin = self._plugin(
  963. page,
  964. service_id=9001,
  965. routing_key=routing_key,
  966. query_mode="calendar",
  967. capability="single_schengen_tourism",
  968. )
  969. apt_type = self._appointment_type(
  970. routing_key,
  971. city="Sample City",
  972. )
  973. with patch(
  974. "plugins.ita_plugin.scan_until_first_available_month",
  975. return_value=types.SimpleNamespace(
  976. earliest_available_date=None
  977. ),
  978. ):
  979. result = plugin.query(apt_type)
  980. self.assertFalse(result.success)
  981. self.assertEqual(
  982. result.availability_status,
  983. AvailabilityStatus.NoneAvailable,
  984. )
  985. self.assertIsNone(result.earliest_date)
  986. self.assertEqual(result.availability, [])
  987. def test_calendar_mode_requires_a_route_confirmed_calendar_session(self):
  988. routing_key = "slot.sample.it.tourist"
  989. page = FakeQueryPage(initial_state="user_area", service_id=9001)
  990. plugin = self._plugin(
  991. page,
  992. service_id=9001,
  993. routing_key=routing_key,
  994. query_mode="calendar",
  995. capability="single_schengen_tourism",
  996. )
  997. plugin._calendar_query_route_key = None
  998. with patch(
  999. "plugins.ita_plugin.scan_until_first_available_month"
  1000. ) as scanner:
  1001. with self.assertRaisesRegex(
  1002. BizLogicError,
  1003. "preparation is not complete",
  1004. ):
  1005. plugin.query(
  1006. self._appointment_type(
  1007. routing_key,
  1008. city="Sample City",
  1009. )
  1010. )
  1011. scanner.assert_not_called()
  1012. def test_calendar_mode_rejects_a_different_prepared_route(self):
  1013. routing_key = "slot.sample.it.tourist"
  1014. page = FakeQueryPage(initial_state="calendar", service_id=9001)
  1015. plugin = self._plugin(
  1016. page,
  1017. service_id=9001,
  1018. routing_key=routing_key,
  1019. query_mode="calendar",
  1020. capability="single_schengen_tourism",
  1021. )
  1022. plugin._calendar_query_route_key = "slot.other.it.tourist"
  1023. with patch(
  1024. "plugins.ita_plugin.scan_until_first_available_month"
  1025. ) as scanner:
  1026. with self.assertRaisesRegex(
  1027. BizLogicError,
  1028. "route continuity",
  1029. ):
  1030. plugin.query(
  1031. self._appointment_type(
  1032. routing_key,
  1033. city="Sample City",
  1034. )
  1035. )
  1036. scanner.assert_not_called()
  1037. def test_calendar_mode_rejects_a_probe_only_route(self):
  1038. page = FakeQueryPage(initial_state="calendar")
  1039. plugin = self._plugin(page, query_mode="calendar")
  1040. with self.assertRaisesRegex(
  1041. BizLogicError,
  1042. "single_schengen_tourism",
  1043. ):
  1044. plugin.query(self._appointment_type())
  1045. def test_login_redirect_is_reported_as_expired_session(self):
  1046. page = FakeQueryPage(initial_state="login")
  1047. plugin = self._plugin(page)
  1048. with self.assertRaises(SessionExpiredOrInvalidError):
  1049. plugin.query(self._appointment_type())
  1050. self.assertEqual(page.clicked, [])
  1051. def test_query_source_contains_no_otp_or_submission_path(self):
  1052. query_source = inspect.getsource(ItaPlugin.query)
  1053. forbidden_fragments = (
  1054. "otp-send",
  1055. "otp-input",
  1056. "123456",
  1057. "PrivacyCheck",
  1058. "btnAvanti",
  1059. "InsertNewBooking",
  1060. "_perform_request",
  1061. )
  1062. for fragment in forbidden_fragments:
  1063. with self.subTest(fragment=fragment):
  1064. self.assertNotIn(fragment, query_source)
  1065. class ItaPluginBookDiscoveryTests(unittest.TestCase):
  1066. @staticmethod
  1067. def _appointment_type():
  1068. return AppointmentType(
  1069. routing_key="slot.dub.it.tourist",
  1070. city="Dublin",
  1071. country="Italy",
  1072. visa_type="Tourist",
  1073. )
  1074. @classmethod
  1075. def _weak_signal(cls):
  1076. return VSQueryResult(
  1077. success=False,
  1078. apt_type=cls._appointment_type(),
  1079. availability_status=AvailabilityStatus.NoneAvailable,
  1080. )
  1081. @staticmethod
  1082. def _plugin(page):
  1083. plugin = ItaPlugin.__new__(ItaPlugin)
  1084. plugin.group_id = "offline-book-discovery"
  1085. plugin.logger = Mock()
  1086. plugin.page = page
  1087. plugin.mouse = FakeQueryMouse(page)
  1088. plugin.free_config = {
  1089. "query_mode": "services_probe",
  1090. "final_submit_enabled": False,
  1091. "apt_configs": {
  1092. "slot.dub.it.tourist": {
  1093. "service_id": 1321,
  1094. "capability": "services_probe_only",
  1095. }
  1096. },
  1097. }
  1098. plugin.ita_url = "https://prenotami.esteri.it"
  1099. plugin.root_workspace = "/nonexistent/ita-plugin-book-test"
  1100. plugin.tunnel = None
  1101. return plugin
  1102. def test_book_rechecks_once_and_returns_false_when_user_has_no_slot(self):
  1103. page = FakeQueryPage(outcome="no_slots", initial_state="user_area")
  1104. plugin = self._plugin(page)
  1105. result = plugin.book(self._weak_signal(), user_inputs={})
  1106. self.assertFalse(result.success)
  1107. self.assertEqual(result.label, BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
  1108. self.assertEqual(page.clicked, ["booking-1321"])
  1109. self.assertEqual(page.run_js_calls, [])
  1110. def test_book_reads_allowlisted_structure_and_stops_before_avanti(self):
  1111. page = FakeQueryPage(outcome="booking_form", initial_state="user_area")
  1112. plugin = self._plugin(page)
  1113. result = plugin.book(self._weak_signal(), user_inputs={})
  1114. self.assertFalse(result.success)
  1115. self.assertEqual(result.label, BOOKING_FORM_DISCOVERY_STOP_LABEL)
  1116. self.assertEqual(page.clicked, ["booking-1321"])
  1117. self.assertEqual(len(page.run_js_calls), 1)
  1118. structure = plugin.last_booking_form_structure
  1119. self.assertEqual(structure["path"], "/Services/Booking/1321")
  1120. self.assertEqual(structure["form"]["method"], "POST")
  1121. self.assertEqual(structure["field_count"], 2)
  1122. self.assertNotIn("value", structure["fields"][0])
  1123. self.assertNotIn("untrusted", str(structure))
  1124. def test_book_fails_closed_when_form_metadata_has_an_unexpected_path(self):
  1125. page = FakeQueryPage(outcome="booking_form", initial_state="user_area")
  1126. page.state = "booking_form"
  1127. structure = page.run_js("fixture")
  1128. page.state = "user_area"
  1129. structure["path"] = "/Unexpected"
  1130. page.run_js_calls.clear()
  1131. page.run_js = Mock(return_value=structure)
  1132. plugin = self._plugin(page)
  1133. with self.assertRaisesRegex(BizLogicError, "unexpected path"):
  1134. plugin.book(self._weak_signal(), user_inputs={})
  1135. self.assertEqual(page.clicked, ["booking-1321"])
  1136. self.assertEqual(page.run_js.call_count, 1)
  1137. def test_book_source_contains_no_form_submission_calendar_or_otp_path(self):
  1138. book_source = inspect.getsource(ItaPlugin.book)
  1139. forbidden_fragments = (
  1140. "GenerateOTP",
  1141. "get_email_verify_code",
  1142. "fetch_mail_content",
  1143. "PrivacyCheck",
  1144. "btnAvanti",
  1145. "BookingCalendar",
  1146. "InsertNewBooking",
  1147. "_perform_request",
  1148. ".submit(",
  1149. ".click(",
  1150. )
  1151. for fragment in forbidden_fragments:
  1152. with self.subTest(fragment=fragment):
  1153. self.assertNotIn(fragment, book_source)
  1154. class FakeRetainedSignalRedis:
  1155. def __init__(self, payload, clock, *, ttl):
  1156. self.payload = json.dumps(payload)
  1157. self.clock = clock
  1158. self.ttl = ttl
  1159. def get(self, _name):
  1160. if self.clock["now"] <= self.ttl:
  1161. return self.payload
  1162. return None
  1163. def delete(self, *_names):
  1164. return 0
  1165. class CountingItaOrderBooker(OrderBookerGCO):
  1166. def _execute_book_job(self, task, query_result):
  1167. del task, query_result
  1168. self.book_calls += 1
  1169. class ItaSignalReuseTests(unittest.TestCase):
  1170. @staticmethod
  1171. def _appointment_type():
  1172. return AppointmentType(
  1173. routing_key="slot.dub.it.tourist",
  1174. city="Dublin",
  1175. country="Italy",
  1176. visa_type="Tourist",
  1177. )
  1178. def test_retained_thirty_second_signal_triggers_one_book_call(self):
  1179. apt_type = self._appointment_type()
  1180. weak_result = VSQueryResult(
  1181. success=True,
  1182. apt_type=apt_type,
  1183. availability_status=AvailabilityStatus.NoneAvailable,
  1184. )
  1185. payload = {
  1186. "apt_type": apt_type.model_dump(),
  1187. "query_result": weak_result.to_snapshot_payload(),
  1188. }
  1189. clock = {"now": 0.0}
  1190. task = Task(
  1191. instance=Mock(),
  1192. next_run=0.0,
  1193. task_ref=1,
  1194. acceptable_routing_keys=[apt_type.routing_key],
  1195. source_queue=apt_type.routing_key,
  1196. book_allowed=True,
  1197. )
  1198. config = GroupConfig(
  1199. identifier="pernotami.ie.it",
  1200. appointment_types=[apt_type],
  1201. booker={
  1202. "account_source": "order",
  1203. "target_instances": 1,
  1204. "booking_cooldown": 45,
  1205. },
  1206. )
  1207. booker = CountingItaOrderBooker.__new__(CountingItaOrderBooker)
  1208. booker.m_cfg = config
  1209. booker.m_logger = Mock()
  1210. booker.m_tasks = [task]
  1211. booker.m_lock = threading.RLock()
  1212. booker.m_stop_event = threading.Event()
  1213. booker.m_task_data_cache = {}
  1214. booker.redis_client = FakeRetainedSignalRedis(payload, clock, ttl=30)
  1215. booker.book_calls = 0
  1216. def fake_sleep(seconds):
  1217. clock["now"] += seconds
  1218. if clock["now"] > 31:
  1219. booker.m_stop_event.set()
  1220. booker_time = OrderBookerGCO._booking_trigger_loop.__globals__["time"]
  1221. with (
  1222. patch.object(booker_time, "sleep", side_effect=fake_sleep),
  1223. patch.object(booker_time, "time", side_effect=lambda: clock["now"]),
  1224. ):
  1225. booker._booking_trigger_loop()
  1226. self.assertEqual(booker.book_calls, 1)
  1227. self.assertGreater(task.next_run, 30)
  1228. def test_italy_config_keeps_existing_single_worker_cooldown_contract(self):
  1229. repo_root = Path(__file__).resolve().parents[1]
  1230. booker_groups = json.loads(
  1231. (repo_root / "config" / "config_booker.json").read_text()
  1232. )
  1233. sentinel_groups = json.loads(
  1234. (repo_root / "config" / "config_sentinel.json").read_text()
  1235. )
  1236. booker_group = next(
  1237. group
  1238. for group in booker_groups
  1239. if group["identifier"] == "pernotami.ie.it"
  1240. )
  1241. sentinel_group = next(
  1242. group
  1243. for group in sentinel_groups
  1244. if group["identifier"] == "pernotami.ie.it"
  1245. )
  1246. self.assertEqual(booker_group["booker"]["target_instances"], 1)
  1247. self.assertEqual(sentinel_group["sentinel"]["target_instances"], 1)
  1248. self.assertGreater(
  1249. booker_group["booker"]["booking_cooldown"],
  1250. sentinel_group["sentinel"]["signal_ttl"],
  1251. )
  1252. self.assertGreater(
  1253. sentinel_group["sentinel"]["query_wait"]["random_min"],
  1254. booker_group["booker"]["booking_cooldown"],
  1255. )
  1256. if __name__ == "__main__":
  1257. unittest.main()