test_debug_ita_query_book.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. """Real framework creation/publication/dispatch/execution, synthetic I/O only.
  2. No test-owned signal schema, expiry rule, account dispatcher or retry policy.
  3. The already-existing Redis fixture simulates a retained server key. Snapshot
  4. encoding/decoding, account binding, route/date/cooldown decisions and public
  5. Italy Query/Book remain the real implementations.
  6. """
  7. import contextlib
  8. import copy
  9. from datetime import date
  10. import io
  11. import itertools
  12. import json
  13. import tempfile
  14. from pathlib import Path
  15. from types import SimpleNamespace
  16. import unittest
  17. from unittest.mock import Mock, patch
  18. from tools import debug_ita_query_book as cli
  19. from test.test_ita_plugin import OrderBookerGCO, FakeRetainedSignalRedis
  20. from sentinel import SentinelGCO
  21. from test import test_ita_calendar_book_flow as book_flow
  22. from test.test_ita_query_recovery import RecoveryPage, prepared_plugin
  23. from vs_types import AvailabilityStatus, GroupConfig, QueryWaitMode
  24. class ExistingFrameworkJointTests(unittest.TestCase):
  25. def setUp(self):
  26. # Fail closed if a future test accidentally stops isolating I/O.
  27. for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
  28. "requests.sessions.Session.request", "subprocess.Popen"):
  29. self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
  30. self.clock = {"now": 1000.0}
  31. self.retained = None
  32. self.query_page = RecoveryPage()
  33. self.query_page.plans = [[(2026, 8, []), (2026, 9, []), (2026, 10, [13, 20])]] * 10
  34. self.query, self.route = prepared_plugin(self.query_page)
  35. self.apt = self.route.appointment_type()
  36. self.apt.weight = 1
  37. self.query._transient_user_data_path = "/nonexistent/ita-framework-query"
  38. self.query.free_config.update(otp_mode="manual", final_submit_enabled=False)
  39. self.query.query = Mock(wraps=self.query.query)
  40. # Existing fixture is already on Calendar; restore its prepared marker
  41. # after the framework's real set_config clears per-session state.
  42. self.query.create_session = Mock(side_effect=lambda:
  43. self.query._record_calendar_query_prepared_route(self.query._resolve_route(self.apt)))
  44. self.query.cleanup = Mock()
  45. self.query._cleanup_attempted = True
  46. self.inputs = {"username": "applicant@example.test", "password": "synthetic-applicant-password",
  47. "expected_start_date": "2026-08-01", "expected_end_date": "2026-10-31"}
  48. self.order = {"id": 991, "order_id": "SYNTHETIC-ORDER", "status": "processing",
  49. "user_inputs": copy.deepcopy(self.inputs)}
  50. self.cloud = Mock()
  51. self.cloud.get_next_account.return_value = {
  52. "id": 21, "username": "pool-query@example.test", "password": "synthetic-pool-password"}
  53. self.cloud.get_vas_task_pop.return_value = self.order
  54. self.redis = Mock()
  55. self.redis.setex.side_effect = self.capture_redis_write
  56. self.redis.get.side_effect = lambda key: (
  57. self.retained.get(key) if self.retained is not None and key == self.signal_key else None)
  58. self.redis.delete.side_effect = self.delete_redis_key
  59. self.signal_key = "vs:signal:" + self.apt.routing_key
  60. self.executor = Mock()
  61. self.log = Mock()
  62. # Existing test pattern: isolate only method dependencies, not methods.
  63. # Use each loaded class's globals to avoid import-cache/stub ambiguity.
  64. dependencies = {
  65. "SafeRedisClient": Mock(return_value=self.redis),
  66. "VSCloudApi": SimpleNamespace(Instance=lambda: self.cloud, lock_account=Mock()),
  67. "time": SimpleNamespace(time=lambda: self.clock["now"], sleep=lambda _seconds: None),
  68. }
  69. for cls in (SentinelGCO, OrderBookerGCO):
  70. self.enterContext(patch.dict(cls.__init__.__globals__, dependencies))
  71. self.enterContext(patch.dict(OrderBookerGCO._execute_book_job.__globals__,
  72. ThreadPool=SimpleNamespace(getInstance=lambda: self.executor)))
  73. self.final = self.enterContext(patch("plugins.ita_workflow.submit_final",
  74. side_effect=AssertionError("Final submission forbidden")))
  75. # Query month navigation uses only the synthetic page above.
  76. self.enterContext(patch("plugins.ita_calendar_query.time.sleep"))
  77. self.query_config = GroupConfig(
  78. identifier="offline-query", need_account=True, appointment_types=[self.apt],
  79. plugin_config={"plugin_name": "ita_plugin"}, free_config=copy.deepcopy(self.query.free_config),
  80. sentinel={"account_pool_id": "fixture.query.pool", "account_cd": 10800,
  81. "signal_ttl": 30, "query_wait": {"mode": QueryWaitMode.Fixed, "fixed_wait": 1}})
  82. self.book_plugin, self.book_page = self.new_book_plugin()
  83. self.book_config = GroupConfig(
  84. identifier="offline-book", need_account=True, appointment_types=[self.apt],
  85. plugin_config={"plugin_name": "ita_plugin"}, free_config=copy.deepcopy(self.book_plugin.free_config),
  86. booker={"account_source": "order", "target_instances": 1, "booking_cooldown": 45})
  87. self.sentinel = SentinelGCO(self.query_config, {}, self.log)
  88. self.booker = OrderBookerGCO(self.book_config, {}, self.log)
  89. self.sentinel.m_factory.create = Mock(return_value=self.query)
  90. self.booker.m_factory.create = Mock(return_value=self.book_plugin)
  91. self.booker._execute_book_job = Mock(wraps=self.booker._execute_book_job)
  92. # Real GCO stop/cleanup is exercised; browser cleanup remains a fixture.
  93. self.addCleanup(self.sentinel.stop)
  94. self.addCleanup(self.booker.stop)
  95. def new_book_plugin(self):
  96. page = book_flow.FlowPage([book_flow.month("2026-10", {13: 0, 14: 1})])
  97. plugin, _, _ = book_flow.prepared_plugin(page, routing_key=self.apt.routing_key)
  98. plugin.free_config.update(otp_mode="cloud", final_submit_enabled=False)
  99. plugin.is_healthy = True
  100. plugin._cleanup_attempted = True
  101. plugin.cleanup = Mock()
  102. # Login/OTP are already independently tested; this fixture starts at
  103. # the prepared Calendar but binds it AFTER real order account wiring.
  104. plugin.create_session = Mock(side_effect=lambda:
  105. plugin._record_calendar_book_prepared_route(plugin._resolve_route(self.apt)))
  106. plugin.book = Mock(wraps=plugin.book)
  107. return plugin, page
  108. def capture_redis_write(self, key, ttl, payload):
  109. self.assertEqual(key, self.signal_key)
  110. # Reuse existing retained-key fixture, not a new signal/TTL algorithm.
  111. self.retained = FakeRetainedSignalRedis(json.loads(payload), self.clock,
  112. ttl=self.clock["now"] + ttl)
  113. return True
  114. def delete_redis_key(self, key):
  115. if key == self.signal_key:
  116. self.retained = None
  117. return 1
  118. def spawn(self):
  119. self.sentinel._spawn_sentinel_worker()
  120. self.booker._spawn_worker(self.apt.routing_key)
  121. def publish_once(self, *, positive=True):
  122. # Bound the EXISTING loop to one cycle; do not reimplement its body.
  123. with patch.object(self.sentinel.m_stop_event, "is_set", side_effect=[False, True]):
  124. self.sentinel._monitor_loop()
  125. if positive:
  126. self.assertIsNotNone(self.retained, self.log.call_args_list)
  127. self.assertIsNotNone(self.query.last_calendar_query_scan.earliest_available_date)
  128. def trigger_once(self, page=None):
  129. with book_flow.browser_navigation(page or self.book_page), \
  130. patch.object(self.booker.m_stop_event, "is_set", side_effect=[False, True]):
  131. # Existing Thread creation and joins run as-is inside this loop.
  132. self.booker._booking_trigger_loop()
  133. def assert_no_final_or_success_report(self):
  134. self.final.assert_not_called()
  135. self.executor.enqueue.assert_not_called()
  136. self.cloud.update_vas_task.assert_not_called()
  137. self.cloud.push_weixin_text.assert_not_called()
  138. def test_real_framework_pool_query_json_order_book_rechecks_current_inventory(self):
  139. self.spawn()
  140. self.assertEqual(len(self.sentinel.m_tasks), 1)
  141. self.assertEqual(len(self.booker.m_tasks), 1)
  142. self.cloud.get_next_account.assert_called_once_with("fixture.query.pool", 10800)
  143. self.cloud.get_vas_task_pop.assert_called_once_with("auto." + self.apt.routing_key)
  144. self.assertEqual(self.query.config.account.username, "pool-query@example.test")
  145. self.assertEqual(self.query.config.account.id, 21)
  146. self.assertEqual(self.book_plugin.config.account.username, self.inputs["username"])
  147. self.assertEqual(self.book_plugin.config.account.password, self.inputs["password"])
  148. self.assertFalse(self.sentinel.m_tasks[0].book_allowed)
  149. self.assertEqual(self.booker.m_tasks[0].task_ref, 991)
  150. self.assertEqual(self.booker.m_tasks[0].acceptable_routing_keys, [self.apt.routing_key])
  151. self.assertIsNot(self.query.page, self.book_plugin.page)
  152. self.publish_once()
  153. self.query.query.assert_called_once_with(self.apt)
  154. self.redis.setex.assert_called_once()
  155. key, ttl, raw = self.redis.setex.call_args.args
  156. self.assertEqual((key, ttl), (self.signal_key, 30))
  157. payload = json.loads(raw)
  158. self.assertEqual(set(payload), {"group_id", "apt_type", "query_result", "timestamp"})
  159. self.assertEqual(payload["group_id"], self.query_config.identifier)
  160. self.assertEqual(payload["apt_type"], self.apt.model_dump())
  161. self.assertEqual(payload["query_result"]["earliest_date"], "2026-10-13")
  162. self.assertEqual(payload["query_result"]["availability_status"], "Available")
  163. self.assertNotIn("success", payload["query_result"])
  164. self.assertNotIn("password", raw)
  165. self.assertNotIn("pool-query", raw)
  166. self.assertEqual(self.query_page.forward_clicks, [(2026, 9), (2026, 10)])
  167. self.trigger_once()
  168. self.booker._execute_book_job.assert_called_once()
  169. self.book_plugin.book.assert_called_once()
  170. trigger, inputs = self.book_plugin.book.call_args.args
  171. self.assertEqual(trigger.apt_type, self.apt)
  172. self.assertIs(trigger.availability_status, AvailabilityStatus.Available)
  173. self.assertFalse(trigger.success) # Actual framework decode default.
  174. self.assertEqual(trigger.earliest_date.date(), date(2026, 10, 13))
  175. self.assertEqual(inputs, self.inputs)
  176. self.assertEqual(self.book_plugin.last_booking_precommit.candidate.day, date(2026, 10, 14))
  177. self.assertEqual(self.book_page.refreshes, 2) # Existing stale-hint fallback.
  178. self.assertGreater(len(self.book_page.requests), 0)
  179. self.assert_no_final_or_success_report()
  180. self.sentinel.stop()
  181. self.booker.stop()
  182. self.query.cleanup.assert_called_once()
  183. self.book_plugin.cleanup.assert_called_once()
  184. def test_no_account_or_login_failure_does_not_create_query_task(self):
  185. self.cloud.get_next_account.side_effect = RuntimeError("synthetic pool failure")
  186. self.sentinel._spawn_sentinel_worker()
  187. self.assertEqual(self.sentinel.m_tasks, [])
  188. self.sentinel.m_factory.create.assert_not_called()
  189. self.cloud.get_next_account.reset_mock(side_effect=True)
  190. self.query.create_session.side_effect = RuntimeError("synthetic login failure")
  191. self.sentinel._spawn_sentinel_worker()
  192. self.assertEqual(self.sentinel.m_tasks, [])
  193. self.query.cleanup.assert_called_once()
  194. self.assertGreater(self.sentinel.m_spawn_cooldown_until, self.clock["now"])
  195. def test_no_order_does_not_take_pool_account_for_book(self):
  196. self.cloud.get_vas_task_pop.return_value = None
  197. self.booker._spawn_worker(self.apt.routing_key)
  198. self.assertEqual(self.booker.m_tasks, [])
  199. self.booker.m_factory.create.assert_not_called()
  200. self.cloud.get_next_account.assert_not_called()
  201. def test_order_login_failure_uses_existing_cleanup_without_query_account_fallback(self):
  202. self.book_plugin.create_session.side_effect = RuntimeError("synthetic login failure")
  203. self.booker._spawn_worker(self.apt.routing_key)
  204. self.assertEqual(self.booker.m_tasks, [])
  205. self.assertEqual(self.booker.m_task_data_cache, {})
  206. self.book_plugin.cleanup.assert_called_once()
  207. self.cloud.get_next_account.assert_not_called()
  208. def test_no_availability_does_not_publish_or_trigger_book(self):
  209. self.query_page.outcomes = ["none"]
  210. self.spawn()
  211. self.publish_once(positive=False)
  212. self.trigger_once()
  213. self.redis.setex.assert_not_called()
  214. self.book_plugin.book.assert_not_called()
  215. self.cloud.slot_refresh_success.assert_called_once()
  216. self.assert_no_final_or_success_report()
  217. def test_bad_query_protocol_does_not_publish_a_positive_signal(self):
  218. self.query_page.outcomes = ["malformed"]
  219. self.spawn()
  220. self.publish_once(positive=False)
  221. self.trigger_once()
  222. self.redis.setex.assert_not_called()
  223. self.cloud.slot_refresh_fail.assert_called_once()
  224. self.book_plugin.book.assert_not_called()
  225. def test_server_expired_signal_does_not_trigger_book(self):
  226. self.spawn()
  227. self.publish_once()
  228. self.clock["now"] += self.query_config.sentinel.signal_ttl + 1
  229. self.trigger_once()
  230. self.book_plugin.book.assert_not_called()
  231. def test_same_signal_obeys_existing_task_cooldown_not_new_one_shot_rule(self):
  232. self.query_config.sentinel.signal_ttl = 180
  233. self.spawn()
  234. self.publish_once()
  235. self.trigger_once()
  236. self.clock["now"] += 1
  237. self.trigger_once()
  238. self.book_plugin.book.assert_called_once()
  239. self.clock["now"] += self.book_config.booker.booking_cooldown
  240. self.trigger_once()
  241. self.assertEqual(self.book_plugin.book.call_count, 2)
  242. self.assert_no_final_or_success_report()
  243. def test_unmatched_routing_key_is_filtered_by_real_trigger_loop(self):
  244. self.spawn()
  245. self.publish_once()
  246. self.booker.m_tasks[0].acceptable_routing_keys = ["slot.other.it.tourist"]
  247. self.trigger_once()
  248. self.book_plugin.book.assert_not_called()
  249. def test_date_outside_order_end_is_filtered_before_book(self):
  250. self.order["user_inputs"]["expected_end_date"] = "2026-10-12"
  251. self.spawn()
  252. self.publish_once()
  253. self.trigger_once()
  254. self.book_plugin.book.assert_not_called()
  255. def test_order_start_bound_reaches_real_book_selection(self):
  256. self.order["user_inputs"]["expected_start_date"] = "2026-10-15"
  257. self.spawn()
  258. self.publish_once()
  259. self.trigger_once()
  260. self.book_plugin.book.assert_called_once()
  261. self.assertIsNone(self.book_plugin.last_booking_precommit)
  262. self.assert_no_final_or_success_report()
  263. def test_paused_order_is_removed_without_book(self):
  264. self.spawn()
  265. self.publish_once()
  266. self.order["status"] = "pause"
  267. self.trigger_once()
  268. self.book_plugin.book.assert_not_called()
  269. self.assertEqual(self.booker.m_tasks, [])
  270. self.book_plugin.cleanup.assert_called_once()
  271. def test_corrupt_redis_payload_uses_existing_delete_branch(self):
  272. self.spawn()
  273. self.publish_once()
  274. self.retained.payload = "invalid-json"
  275. self.trigger_once()
  276. self.redis.delete.assert_called_once_with(self.signal_key)
  277. self.book_plugin.book.assert_not_called()
  278. def test_one_shared_signal_can_trigger_two_separately_bound_orders(self):
  279. self.spawn()
  280. other, other_page = self.new_book_plugin()
  281. other_order = copy.deepcopy(self.order)
  282. other_order.update(id=992, order_id="SYNTHETIC-OTHER")
  283. other_order["user_inputs"]["username"] = "second-applicant@example.test"
  284. self.cloud.get_vas_task_pop.return_value = other_order
  285. self.booker.m_factory.create.return_value = other
  286. self.booker._spawn_worker(self.apt.routing_key)
  287. self.publish_once()
  288. # Both fixtures start directly in the positive month; no month-click
  289. # adapter is needed for this two-thread test, only no-delay sleeps.
  290. with patch.object(self.booker.m_stop_event, "is_set", side_effect=[False, True]):
  291. self.booker._booking_trigger_loop()
  292. self.book_plugin.book.assert_called_once()
  293. other.book.assert_called_once()
  294. self.assertEqual(other.config.account.username, "second-applicant@example.test")
  295. self.assertIsNot(self.book_page, other_page)
  296. self.assertEqual(other.last_booking_precommit.candidate.day, date(2026, 10, 14))
  297. self.assertEqual(self.booker._execute_book_job.call_count, 2)
  298. self.cloud.get_next_account.assert_called_once()
  299. self.assert_no_final_or_success_report()
  300. def test_later_negative_query_keeps_existing_signal_until_redis_expiry(self):
  301. self.spawn()
  302. self.publish_once()
  303. original = self.retained.payload
  304. self.query_page.outcomes = ["none"]
  305. self.clock["now"] += 2
  306. self.publish_once(positive=False)
  307. self.assertEqual(self.query.query.call_count, 2)
  308. self.redis.setex.assert_called_once()
  309. self.redis.delete.assert_not_called()
  310. self.assertEqual(self.retained.payload, original)
  311. class OfflineCliTests(unittest.TestCase):
  312. def test_old_live_flag_is_rejected_before_loading_tests(self):
  313. with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames") as load, \
  314. contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as caught:
  315. cli.main(["--run"])
  316. self.assertEqual(caught.exception.code, 2)
  317. load.assert_not_called()
  318. def test_cli_runs_only_existing_framework_suite_and_reports_offline(self):
  319. result = SimpleNamespace(testsRun=26, failures=[], errors=[], skipped=[], wasSuccessful=lambda: True)
  320. with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames") as load, \
  321. patch.object(cli.unittest, "TextTestRunner") as runner, \
  322. contextlib.redirect_stdout(io.StringIO()) as output:
  323. runner.return_value.run.return_value = result
  324. self.assertEqual(cli.main([]), 0)
  325. load.assert_called_once_with(cli.TEST_NAMES)
  326. summary = json.loads(output.getvalue().split("ITA_QUERY_BOOK_FRAMEWORK_RESULT=")[1])
  327. self.assertTrue(summary["passed"])
  328. self.assertFalse(summary["liveAcceptance"])
  329. self.assertEqual(summary["externalBoundaries"], "simulated")
  330. def test_empty_skipped_or_failed_suite_does_not_pass(self):
  331. for count, skipped, successful in ((0, [], True), (1, ["fixture"], True), (1, [], False)):
  332. result = SimpleNamespace(testsRun=count, failures=[], errors=[], skipped=skipped,
  333. wasSuccessful=lambda: successful)
  334. with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames"), \
  335. patch.object(cli.unittest, "TextTestRunner") as runner, \
  336. contextlib.redirect_stdout(io.StringIO()):
  337. runner.return_value.run.return_value = result
  338. self.assertEqual(cli.main(["--offline"]), 1)
  339. class LocalHarnessTests(unittest.TestCase):
  340. """Same real GCO fixtures; site/pool/Redis are synthetic in offline runs."""
  341. def setUp(self):
  342. from tools import ita_query_book_local as local
  343. self.local = local
  344. self.fixture = ExistingFrameworkJointTests()
  345. self.fixture.setUp()
  346. self.addCleanup(self.fixture.doCleanups)
  347. self.enterContext(contextlib.redirect_stdout(io.StringIO()))
  348. self.enterContext(patch.object(local, "validate_cloud_otp_environment"))
  349. f = self.fixture
  350. f.cloud.get_next_account.return_value.update(pool_name="fixture.query.pool", status="active")
  351. self.applicant = local.VSAccount(username=f.inputs["username"], password=f.inputs["password"])
  352. self.cloud = local.LocalCloudBoundary(f.cloud, f.query_config,
  353. SimpleNamespace(routing_key=f.route.routing_key, mail=None),
  354. SimpleNamespace(model_dump=lambda: {}), self.applicant,
  355. {key: f.inputs[key] for key in ("expected_start_date", "expected_end_date")})
  356. self.enterContext(patch.object(local, "CalendarRequestAudit", return_value=Mock(**{
  357. "settled_snapshot.return_value": {"otpRequests": 0, "avantiPosts": 0,
  358. "availabilityRequests": 1, "timeSlotRequests": 1, "finalRequests": 0}})))
  359. self.enterContext(patch.object(local.SentinelGCO, "_is_within_active_hours", return_value=True))
  360. self.enterContext(patch.object(local.OrderBookerGCO, "_is_within_active_hours", return_value=True))
  361. # Factories still belong to the GCO. Substitute only browser creation.
  362. real_observe = local.observe_factory
  363. def synthetic_factory(gco, role, stack, observed):
  364. gco.m_factory.create = Mock(return_value=f.query if role == "query" else f.book_plugin)
  365. return real_observe(gco, role, stack, observed)
  366. self.enterContext(patch.object(local, "observe_factory", side_effect=synthetic_factory))
  367. self.enterContext(book_flow.browser_navigation(f.book_page))
  368. def run_case(self):
  369. return self.local.run_framework_once(self.fixture.query_config, self.fixture.book_config,
  370. self.fixture.route, self.cloud, {})
  371. def test_one_real_framework_iteration_preserves_pool_order_signal_and_selection(self):
  372. report = self.run_case()
  373. self.assertTrue(report["passed"], report)
  374. self.assertEqual(report["outcome"], "pre_final")
  375. self.assertEqual((report["queryCalls"], report["bookCalls"]), (1, 1))
  376. self.assertTrue(report["signalPublished"])
  377. self.assertTrue(report["signalReadByBooker"])
  378. self.assertTrue(report["selectionVerified"])
  379. self.assertTrue(report["cleanupVerified"])
  380. self.assertFalse(report["cloudOrders"])
  381. self.fixture.cloud.get_next_account.assert_called_once_with("fixture.query.pool", 10800)
  382. self.fixture.cloud.get_vas_task_pop.assert_not_called()
  383. self.fixture.cloud.update_vas_task.assert_not_called()
  384. self.fixture.cloud.slot_snapshot_report.assert_not_called()
  385. self.assertNotEqual(self.fixture.query.config.account.username, self.fixture.book_plugin.config.account.username)
  386. self.assertEqual(self.fixture.book_plugin.config.account.username, self.applicant.username)
  387. self.assertEqual(self.fixture.book_plugin.book.call_args.args[1], self.cloud.order["user_inputs"])
  388. def test_no_availability_does_not_call_book(self):
  389. self.fixture.query_page.plans = [[(2026, 8, []), (2026, 9, []), (2026, 10, [])]] * 2
  390. report = self.run_case()
  391. self.assertFalse(report["passed"])
  392. self.assertEqual(report["outcome"], "no_availability")
  393. self.assertEqual(report["bookCalls"], 0)
  394. self.assertFalse(report["signalPublished"])
  395. self.assertTrue(report["cleanupVerified"])
  396. def test_failed_redis_write_is_not_a_successful_handoff(self):
  397. self.fixture.redis.setex.side_effect = lambda *_: False
  398. report = self.run_case()
  399. self.assertFalse(report["passed"])
  400. self.assertEqual(report["reason"], "redis_publication_failed")
  401. self.assertEqual(report["bookCalls"], 0)
  402. def test_expired_signal_does_not_trigger_or_get_republished(self):
  403. self.fixture.redis.get.side_effect = lambda *_: None
  404. report = self.run_case()
  405. self.assertTrue(report["signalPublished"])
  406. self.assertFalse(report["signalReadByBooker"])
  407. self.assertEqual(report["bookCalls"], 0)
  408. self.assertEqual(report["outcome"], "not_triggered_expired_or_date_filtered")
  409. self.fixture.redis.setex.assert_called_once()
  410. def test_order_date_range_filters_real_trigger_without_calling_book(self):
  411. self.cloud.order["user_inputs"]["expected_end_date"] = "2026-09-30"
  412. report = self.run_case()
  413. self.assertEqual(report["bookCalls"], 0)
  414. self.assertTrue(report["signalReadByBooker"])
  415. self.assertFalse(report["passed"])
  416. def test_pool_failure_is_redacted_and_does_not_retry(self):
  417. self.fixture.cloud.get_next_account.side_effect = RuntimeError("secret-password-and-body")
  418. report = self.run_case()
  419. self.assertEqual(report["reason"], "pool_allocation_failed")
  420. self.assertEqual(self.cloud.pool_calls, 1)
  421. self.assertNotIn("secret-password", json.dumps(report))
  422. self.assertTrue(report["cleanupVerified"])
  423. def test_same_account_cannot_masquerade_as_dual_account_acceptance(self):
  424. self.fixture.cloud.get_next_account.return_value["username"] = self.applicant.username
  425. report = self.run_case()
  426. self.assertFalse(report["passed"])
  427. self.assertEqual(report["reason"], "query_and_book_accounts_same_choose_other_applicant")
  428. self.assertEqual(report["queryCalls"], 0)
  429. def test_cloud_order_and_reporting_methods_are_not_forwarded(self):
  430. for name in ("update_vas_task", "push_weixin_text", "get_vas_task", "return_vas_task_to_queue"):
  431. with self.assertRaises(self.local.LocalAcceptanceError):
  432. getattr(self.cloud, name)
  433. getattr(self.fixture.cloud, name).assert_not_called()
  434. def test_unexpected_final_request_fails_even_after_selection(self):
  435. self.local.CalendarRequestAudit.return_value.settled_snapshot.return_value["finalRequests"] = 1
  436. report = self.run_case()
  437. self.assertFalse(report["passed"])
  438. self.assertEqual(report["reason"], "unexpected_final_request_do_not_rerun")
  439. def test_book_exception_does_not_escape_as_success_or_leak_body(self):
  440. self.fixture.book_plugin.book.side_effect = RuntimeError("secret-otp-body")
  441. report = self.run_case()
  442. self.assertEqual(report["reason"], "book_failed")
  443. self.assertEqual(report["bookErrorType"], "RuntimeError")
  444. self.assertNotIn("secret-otp", json.dumps(report))
  445. self.assertTrue(report["cleanupVerified"])
  446. def test_final_success_cannot_be_reported_by_prefinal_test(self):
  447. from vs_types import VSBookResult
  448. self.fixture.book_plugin.book.side_effect = None
  449. self.fixture.book_plugin.book.return_value = VSBookResult(success=True)
  450. report = self.run_case()
  451. self.assertFalse(report["passed"])
  452. self.assertEqual(report["reason"], "unexpected_book_success_before_final")
  453. self.fixture.cloud.update_vas_task.assert_not_called()
  454. self.assertGreater(self.cloud.forbidden_calls, 0)
  455. def test_book_login_failure_does_not_allocate_pool_account(self):
  456. self.fixture.book_plugin.create_session.side_effect = RuntimeError("secret-provider-response")
  457. report = self.run_case()
  458. self.assertEqual(report["reason"], "applicant_session_not_created")
  459. self.fixture.cloud.get_next_account.assert_not_called()
  460. self.assertTrue(report["cleanupVerified"])
  461. def test_interrupt_during_query_cleans_both_sessions_without_book(self):
  462. self.fixture.query.query.side_effect = KeyboardInterrupt()
  463. report = self.run_case()
  464. self.assertEqual(report["outcome"], "interrupted")
  465. self.assertTrue(report["cleanupVerified"])
  466. self.assertEqual(report["bookCalls"], 0)
  467. def test_cleanup_failure_invalidates_otherwise_successful_selection(self):
  468. self.fixture.book_plugin.cleanup.side_effect = RuntimeError("synthetic-cleanup-failure")
  469. report = self.run_case()
  470. self.assertTrue(report["selectionVerified"])
  471. self.assertFalse(report["passed"])
  472. self.assertFalse(report["cleanupVerified"])
  473. def test_repeated_otp_is_not_accepted_as_single_round(self):
  474. self.local.CalendarRequestAudit.return_value.settled_snapshot.return_value["otpRequests"] = 2
  475. report = self.run_case()
  476. self.assertFalse(report["passed"])
  477. self.assertEqual(report["reason"], "unexpected_repeated_preparation")
  478. class LocalFinalTests(unittest.TestCase):
  479. """Native GCO + production Book/final core + real receipt parsers;
  480. only browser/site responses, accounts and Redis are synthetic.
  481. """
  482. def setUp(self):
  483. from plugins import ita_workflow
  484. from plugins.ita_calendar_session import CalendarRequestAudit
  485. from plugins.ita_booking_final import VerifiedSubmission, SubmissionSignal
  486. from test.test_debug_ita_production_query_gate import FakeAuditPage, FakeDriver
  487. from test.test_ita_final_read_port import Browser
  488. from test.test_ita_reservation import confirmed_listing, confirmed_detail
  489. # Save the real function before the pre-final fixture's guard patch.
  490. production_submit = ita_workflow.submit_final
  491. LocalHarnessTests.setUp(self)
  492. self.fixture.final.side_effect = production_submit
  493. self.fixture.book_config.free_config["final_submit_enabled"] = True
  494. self.browser = Browser()
  495. self.fixture.book_page.browser = self.browser
  496. self.fixture.book_page.url += "?selectedService=Visti%20Nazionali%20e%20Schengen"
  497. self.dispatches = 0
  498. self.create_receipt = True
  499. self.submit_signal = SubmissionSignal.ACCEPTED
  500. self.tmp = self.enterContext(tempfile.TemporaryDirectory())
  501. self.input = self.enterContext(patch("builtins.input", side_effect=AssertionError("Automatic Book must not request input")))
  502. self.control = self.local.LocalFinalSubmission(self.applicant,
  503. self.fixture.book_plugin._resolve_route(self.fixture.apt), root=self.tmp)
  504. self.native = Mock(side_effect=self.dispatch)
  505. # Keep REAL audit registration, callback ownership, counting and settle
  506. # logic. Mocking both nested audits previously hid the live collision.
  507. self.audits = []
  508. page = self.fixture.book_page
  509. page.driver = FakeDriver()
  510. page.run_cdp = Mock(return_value={})
  511. page.final_requests = 0
  512. self.emit_book_request = lambda path: FakeAuditPage.emit(page, path)
  513. original_packet = page.response_packet
  514. def response_packet(path, *args, **kwargs):
  515. self.emit_book_request(path)
  516. return original_packet(path, *args, **kwargs)
  517. page.response_packet = response_packet
  518. def audit(page, **kwargs):
  519. result = CalendarRequestAudit(page, **kwargs)
  520. result.start = Mock(wraps=result.start)
  521. result.stop = Mock(wraps=result.stop)
  522. self.audits.append(result)
  523. return result
  524. self.local.CalendarRequestAudit.side_effect = audit
  525. clock = itertools.count(0, 0.1)
  526. self.enterContext(patch.object(ita_workflow.preparation, "time", SimpleNamespace(
  527. monotonic=lambda: next(clock), sleep=lambda _seconds: None)))
  528. def native_factory(page, target, current):
  529. self.native.submitted_selection = VerifiedSubmission(target)
  530. return self.native
  531. self.enterContext(patch.object(ita_workflow, "NativeFinalSubmitter", side_effect=native_factory))
  532. self.new_listing = confirmed_listing()
  533. self.new_detail = confirmed_detail()
  534. self.new_listing["tables"][0]["rows"][1].update(date="14 ottobre 2026", time="10:26")
  535. self.new_detail["fields"].update(Data="14 ottobre 2026", Ora="10:26")
  536. def dispatch(self):
  537. self.assertTrue(self.control.claim_path.exists())
  538. self.dispatches += 1
  539. self.emit_book_request("/BookingCalendar/InsertNewBooking")
  540. if self.create_receipt:
  541. self.browser.raw = self.new_listing
  542. self.browser.receipts[self.new_listing["tables"][0]["rows"][1]["detailUrl"]] = self.new_detail
  543. return self.submit_signal
  544. def run_case(self):
  545. return self.local.run_framework_once(self.fixture.query_config, self.fixture.book_config,
  546. self.fixture.route, self.cloud, {}, final_control=self.control)
  547. def test_one_final_returns_standard_success_and_local_notification_without_cloud_write(self):
  548. report = self.run_case()
  549. self.assertTrue(report["passed"], report)
  550. self.assertEqual(report["contract"], self.local.FINAL_CONTRACT)
  551. self.assertEqual(report["outcome"], "confirmed")
  552. self.assertTrue(report["bookingConfirmed"])
  553. self.assertTrue(report["bookResultSuccess"])
  554. self.assertTrue(report["successHandledLocally"])
  555. self.assertEqual(report["selectedTime"], "10:05 - 11:05")
  556. self.assertEqual(report["confirmedTime"], "10:26")
  557. self.assertEqual(report["queryRequests"]["finalRequests"], 0)
  558. self.assertEqual(report["bookRequests"]["finalRequests"], 1)
  559. self.assertTrue(report["cleanupVerified"])
  560. self.assertEqual(self.dispatches, 1)
  561. self.assertEqual((report["queryCalls"], report["bookCalls"]), (1, 1))
  562. self.fixture.cloud.update_vas_task.assert_not_called()
  563. self.fixture.executor.enqueue.assert_not_called()
  564. self.assertNotIn("CONFIRMED-SYNTHETIC", json.dumps(report))
  565. self.assertEqual(len(self.audits), 2) # One owner per Query/Book page.
  566. for audit in self.audits:
  567. audit.start.assert_called_once()
  568. audit.stop.assert_called_once()
  569. self.assertEqual(audit.driver.immediate_event_handlers, {})
  570. def test_automatic_submission_never_reads_stdin(self):
  571. report = self.run_case()
  572. self.assertEqual(report["outcome"], "confirmed", report)
  573. self.assertTrue(report["passed"])
  574. self.assertTrue(self.control.claim_path.exists())
  575. self.native.assert_called_once()
  576. self.input.assert_not_called()
  577. def test_active_baseline_blocks_before_claim_and_preserves_existing_booking(self):
  578. self.browser.raw = self.new_listing
  579. self.browser.receipts[self.new_listing["tables"][0]["rows"][1]["detailUrl"]] = self.new_detail
  580. report = self.run_case()
  581. self.assertFalse(report["passed"], report)
  582. self.assertFalse(report["possiblySubmitted"])
  583. self.assertFalse(self.control.claim_path.exists())
  584. self.native.assert_not_called()
  585. def test_missing_receipt_is_unknown_local_pause_no_cloud_update_or_retry(self):
  586. self.create_receipt = False
  587. report = self.run_case()
  588. self.assertFalse(report["passed"])
  589. self.assertEqual(report["outcome"], "unknown_do_not_retry", report)
  590. self.assertEqual(self.cloud.order["status"], "pause")
  591. self.assertEqual(report["bookRequests"]["finalRequests"], 1)
  592. self.assertTrue(self.control.claim_path.exists())
  593. self.assertEqual(self.dispatches, 1)
  594. self.fixture.cloud.update_vas_task.assert_not_called()
  595. def test_cleanup_failure_does_not_erase_confirmed_booking_or_allow_retry(self):
  596. self.fixture.book_plugin.cleanup.side_effect = RuntimeError("fixture-cleanup")
  597. report = self.run_case()
  598. self.assertFalse(report["passed"], report)
  599. self.assertTrue(report["bookingConfirmed"], report)
  600. self.assertEqual(report["outcome"], "confirmed")
  601. self.assertTrue(self.control.claim_path.exists())
  602. self.assertEqual(self.dispatches, 1)
  603. def test_unknown_response_with_verified_request_and_receipt_is_confirmed(self):
  604. from plugins.ita_booking_final import SubmissionSignal
  605. self.submit_signal = SubmissionSignal.UNKNOWN
  606. self.assertTrue(self.run_case()["passed"])
  607. def test_crash_during_native_call_retains_claim_and_never_retries(self):
  608. self.native.side_effect = RuntimeError("synthetic-private-response")
  609. report = self.run_case()
  610. self.assertFalse(report["passed"])
  611. self.assertEqual(report["outcome"], "unknown_do_not_retry")
  612. self.assertTrue(report["possiblySubmitted"])
  613. self.assertTrue(self.control.claim_path.exists())
  614. self.native.assert_called_once()
  615. self.assertNotIn("private-response", json.dumps(report))
  616. def test_restart_is_blocked_before_second_pool_allocation(self):
  617. from plugins.ita_booking_final import FinalBookingError
  618. self.assertTrue(self.run_case()["passed"])
  619. with self.assertRaises(FinalBookingError):
  620. self.local.LocalFinalSubmission(self.applicant, self.control.route, root=self.tmp)
  621. self.assertEqual(self.cloud.pool_calls, 1)
  622. self.native.assert_called_once()
  623. def test_negative_book_inventory_never_prompts_or_submits(self):
  624. self.fixture.book_page.passes = [[book_flow.month("2026-10", {})]]
  625. self.fixture.book_page.month_spec = self.fixture.book_page.passes[0][0]
  626. report = self.run_case()
  627. self.assertFalse(report["passed"])
  628. self.input.assert_not_called()
  629. self.native.assert_not_called()
  630. self.assertFalse(self.control.claim_path.exists())
  631. class LocalFinalCompositionTests(unittest.TestCase):
  632. def setUp(self):
  633. from tools import ita_query_book_local as local
  634. self.local = local
  635. self.tmp = self.enterContext(tempfile.TemporaryDirectory())
  636. self.applicant = SimpleNamespace(username="Applicant@example.test")
  637. self.route = SimpleNamespace(service_id=9001, routing_key="slot.fixture.it.tourist")
  638. def control(self, applicant=None, route=None):
  639. return self.local.LocalFinalSubmission(applicant or self.applicant, route or self.route, root=self.tmp)
  640. def test_claim_reuses_exclusive_helper_and_blocks_restarts_and_routing_aliases(self):
  641. from plugins.ita_booking_final import FinalBookingError
  642. control = self.control()
  643. self.local.claim_once(control.claim_path)
  644. for account, route in ((self.applicant, self.route),
  645. (SimpleNamespace(username=" applicant@EXAMPLE.test "),
  646. SimpleNamespace(service_id=9001, routing_key="alias"))):
  647. with self.assertRaises(FinalBookingError):
  648. self.control(account, route)
  649. self.assertNotIn("applicant", str(control.claim_path))
  650. self.assertNotIn("example.test", control.claim_path.read_text())
  651. self.assertNotEqual(control.claim_path, self.control(SimpleNamespace(username="other@example.test")).claim_path)
  652. def test_stale_or_wrong_owner_is_rejected_before_production_submission(self):
  653. control = self.control()
  654. production = Mock()
  655. with self.assertRaises(self.local.LocalAcceptanceError):
  656. control.submit(Mock(), self.route, {}, production)
  657. production.assert_not_called()
  658. def test_partial_claim_and_symlink_block_without_removal(self):
  659. from plugins.ita_booking_final import FinalBookingError
  660. control = self.control()
  661. control.claim_path.parent.mkdir(parents=True)
  662. control.claim_path.touch()
  663. with self.assertRaises(FinalBookingError):
  664. self.control()
  665. other = self.control(SimpleNamespace(username="other@example.test"))
  666. other.claim_path.symlink_to(Path(self.tmp) / "missing")
  667. with self.assertRaises(FinalBookingError):
  668. self.control(SimpleNamespace(username="other@example.test"))
  669. self.assertTrue(other.claim_path.is_symlink())
  670. def test_noninteractive_configured_run_never_prompts_and_retains_exit_contract(self):
  671. args = SimpleNamespace(submit_once=True, local_run=True, local_preflight=False, book_account_file="fixture")
  672. group = SimpleNamespace(sentinel=SimpleNamespace(account_pool_id="fixture"))
  673. route = SimpleNamespace(routing_key="fixture", mail=None)
  674. applicant = SimpleNamespace(username="applicant@example.test", password="fixture-password")
  675. result = {"passed": False, "outcome": "unknown_do_not_retry", "possiblySubmitted": True}
  676. with contextlib.redirect_stdout(io.StringIO()), \
  677. patch.object(self.local, "load_settings", return_value=(group, route, Mock(), {})), \
  678. patch("sys.stdin.isatty", return_value=False), \
  679. patch("builtins.input", side_effect=AssertionError("No interactive input")) as prompt, \
  680. patch.object(self.local, "check_dependencies", return_value=("fixture", "fixture")), \
  681. patch.object(self.local, "load_local_account", return_value=applicant), \
  682. patch.object(self.local, "validate_cloud_otp_environment"), \
  683. patch.object(self.local, "LocalFinalSubmission"), \
  684. patch.object(self.local, "build_groups", return_value=(Mock(), Mock())), \
  685. patch.object(self.local, "LocalCloudBoundary"), \
  686. patch.object(self.local.VSCloudApi, "Instance"), \
  687. patch.object(self.local, "private_redis", return_value=contextlib.nullcontext({})), \
  688. patch.object(self.local, "run_framework_once", return_value=result):
  689. self.assertEqual(self.local.main_local(args), 4)
  690. result.update(passed=True, outcome="confirmed")
  691. self.assertEqual(self.local.main_local(args), 0)
  692. prompt.assert_not_called()
  693. class LocalConfigurationTests(unittest.TestCase):
  694. def setUp(self):
  695. from tools import ita_query_book_local as local
  696. self.local = local
  697. self.enterContext(contextlib.redirect_stdout(io.StringIO()))
  698. def settings_fixture(self):
  699. args = SimpleNamespace(config="synthetic.json", group="synthetic-group", proxy="http://127.0.0.1:6268",
  700. expected_start_date=None, expected_end_date=None)
  701. group = {"identifier": args.group, "plugin_config": {"plugin_name": "ita_plugin"},
  702. "sentinel": {"account_pool_id": "synthetic-pool", "signal_ttl": 30},
  703. "appointment_types": [{"routing_key": "slot.other.it.tourist", "weight": 1}],
  704. "free_config": {"query_mode": "calendar", "otp_mode": "cloud", "final_submit_enabled": False,
  705. "apt_configs": {"slot.other.it.tourist": {
  706. "service_id": 9001, "capability": "single_schengen_tourism",
  707. "calendar_scan": {"lookahead_months": 3},
  708. "form": {"booking_type_control_id": "typeofbookingddl", "booking_type_value": "1",
  709. "booking_type_labels": ["Single booking"], "purpose_control_id": "ddls_0",
  710. "purpose_value": "42", "purpose_labels": ["Tourism"]},
  711. "mail": {"authorization_source": "account"}}}}}
  712. return args, group
  713. def test_real_settings_parser_accepts_other_region_without_fixed_mailbox(self):
  714. args, group = self.settings_fixture()
  715. with patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
  716. patch.object(self.local.configure, "TEST_ACCOUNT", None), \
  717. patch.object(self.local, "validate_cloud_otp_logging"):
  718. source, route, proxy, preferences = self.local.load_settings(args)
  719. self.assertEqual(route.service_id, 9001)
  720. self.assertEqual(source.sentinel.account_pool_id, "synthetic-pool")
  721. self.assertEqual(route.mail.mailbox_for("second@example.test"), "second@example.test")
  722. self.assertEqual(proxy.port, 6268)
  723. self.assertEqual(preferences, {})
  724. def test_invalid_settings_cannot_reach_dependencies_or_pool(self):
  725. args, template = self.settings_fixture()
  726. for changes in ({"query_mode": "services_probe"}, {"otp_mode": "manual"}, {"final_submit_enabled": True}):
  727. group = copy.deepcopy(template)
  728. group["free_config"].update(changes)
  729. with self.subTest(changes=changes), \
  730. patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
  731. patch.object(self.local.configure, "TEST_ACCOUNT", None), \
  732. patch.object(self.local, "validate_cloud_otp_logging"), \
  733. self.assertRaises(self.local.LocalAcceptanceError):
  734. self.local.load_settings(args)
  735. def test_public_proxy_and_reversed_date_range_are_rejected_before_run(self):
  736. args, group = self.settings_fixture()
  737. for proxy, start, end in (("http://remote.example.test:6268", None, None),
  738. (args.proxy, "2026-10-31", "2026-10-01")):
  739. args.proxy, args.expected_start_date, args.expected_end_date = proxy, start, end
  740. with patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
  741. patch.object(self.local.configure, "TEST_ACCOUNT", None), \
  742. patch.object(self.local, "validate_cloud_otp_logging"), self.assertRaises(Exception):
  743. self.local.load_settings(args)
  744. def test_successful_preflight_never_prompts_allocates_or_launches(self):
  745. args = SimpleNamespace(local_preflight=True)
  746. group = SimpleNamespace(sentinel=SimpleNamespace(account_pool_id="synthetic-pool"))
  747. route = SimpleNamespace(routing_key="synthetic-route")
  748. with patch.object(self.local, "load_settings", return_value=(group, route, Mock(), {})), \
  749. patch.object(self.local, "check_dependencies", return_value=("redis-server", "/synthetic/chrome")), \
  750. patch.object(self.local, "_get_credentials") as credentials, \
  751. patch.object(self.local.VSCloudApi, "Instance") as api, \
  752. patch.object(self.local, "private_redis") as private_redis:
  753. self.assertEqual(self.local.main_local(args), 0)
  754. credentials.assert_not_called()
  755. api.assert_not_called()
  756. private_redis.assert_not_called()
  757. def test_default_cli_never_starts_local_run_and_explicit_mode_is_forwarded(self):
  758. with patch.object(self.local, "main_local", return_value=7) as live:
  759. self.assertEqual(cli.main(["--local-run", "--group", "my-route-group"]), 7)
  760. self.assertEqual(live.call_args.args[0].group, "my-route-group")
  761. self.assertTrue(live.call_args.args[0].local_run)
  762. def test_preflight_checks_dependencies_before_api_or_credentials(self):
  763. args = SimpleNamespace(local_preflight=True)
  764. with patch.object(self.local, "load_settings", return_value=(Mock(), Mock(), Mock(), {})), \
  765. patch.object(self.local, "check_dependencies", side_effect=self.local.LocalAcceptanceError("missing_dependency")), \
  766. patch.object(self.local, "_get_credentials") as credentials, \
  767. patch.object(self.local.VSCloudApi, "Instance") as api:
  768. self.assertEqual(self.local.main_local(args), 1)
  769. credentials.assert_not_called()
  770. api.assert_not_called()
  771. def test_group_copy_preserves_service_and_ttl_not_production_config(self):
  772. group = GroupConfig(identifier="source", sentinel={"account_pool_id": "test-pool", "signal_ttl": 37},
  773. appointment_types=[{"routing_key": "slot.other.it.tourist", "weight": 1}],
  774. free_config={"query_mode": "calendar", "otp_mode": "cloud", "final_submit_enabled": False,
  775. "persistent_browser_profile_path": "/never-touch", "apt_configs": {"some-route": {"service_id": 999}}})
  776. before = group.model_dump()
  777. query, book = self.local.build_groups(group, "synthetic")
  778. self.assertEqual(group.model_dump(), before)
  779. self.assertEqual(query.sentinel.signal_ttl, 37)
  780. self.assertEqual(query.sentinel.account_pool_id, "test-pool")
  781. self.assertEqual(query.free_config["apt_configs"], before["free_config"]["apt_configs"])
  782. self.assertEqual(book.booker.account_source, "order")
  783. self.assertEqual(book.free_config["query_mode"], "services_probe")
  784. self.assertNotIn("persistent_browser_profile_path", query.free_config)
  785. self.assertFalse(book.free_config["final_submit_enabled"])
  786. def test_final_flag_only_enables_applicant_copy_and_requires_live_cli(self):
  787. group = GroupConfig(identifier="source", free_config={"final_submit_enabled": False})
  788. group.appointment_types = [SimpleNamespace(weight=1)]
  789. query, book = self.local.build_groups(group, "fixture", submit_once=True)
  790. self.assertFalse(group.free_config["final_submit_enabled"])
  791. self.assertFalse(query.free_config["final_submit_enabled"])
  792. self.assertTrue(book.free_config["final_submit_enabled"])
  793. with patch.object(self.local, "main_local", return_value=0) as live:
  794. for args in (["--submit-once"], ["--local-preflight", "--submit-once"], ["--offline", "--submit-once"]):
  795. with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
  796. cli.main(args)
  797. live.assert_not_called()
  798. self.assertEqual(cli.main(["--local-run", "--submit-once"]), 0)
  799. self.assertTrue(live.call_args.args[0].submit_once)
  800. def test_final_requires_explicit_live_mode_before_pool_or_browser(self):
  801. args = SimpleNamespace(submit_once=True, local_run=False)
  802. with patch.object(self.local, "load_settings", return_value=(Mock(), Mock(), Mock(), {})), \
  803. patch.object(self.local, "check_dependencies") as dependencies, \
  804. patch.object(self.local.VSCloudApi, "Instance") as api:
  805. self.assertEqual(self.local.main_local(args), 1)
  806. dependencies.assert_not_called()
  807. api.assert_not_called()
  808. def test_private_redis_is_owned_socket_only_no_shared_flush(self):
  809. process = Mock()
  810. process.poll.return_value = None
  811. with patch.object(self.local.subprocess, "Popen", return_value=process) as popen, \
  812. patch.object(self.local.redis, "Redis") as redis:
  813. redis.return_value.ping.return_value = True
  814. with self.local.private_redis("/synthetic/redis-server") as config:
  815. self.assertTrue(config["unix_socket_path"].startswith("/tmp/ita-qb-"))
  816. self.assertNotIn("host", config)
  817. command = popen.call_args.args[0]
  818. self.assertEqual(command[command.index("--port") + 1], "0")
  819. self.assertEqual(command[command.index("--save") + 1], "")
  820. self.assertEqual(command[command.index("--appendonly") + 1], "no")
  821. process.terminate.assert_called_once()
  822. process.wait.assert_called_once_with(timeout=5)
  823. redis.return_value.flushdb.assert_not_called()
  824. redis.return_value.flushall.assert_not_called()
  825. self.assertFalse(self.local.Path(config["unix_socket_path"]).parent.exists())
  826. def test_private_redis_cleanup_also_runs_when_test_fails(self):
  827. process = Mock()
  828. process.poll.return_value = None
  829. with patch.object(self.local.subprocess, "Popen", return_value=process), \
  830. patch.object(self.local.redis, "Redis") as redis:
  831. redis.return_value.ping.return_value = True
  832. with self.assertRaisesRegex(RuntimeError, "synthetic"):
  833. with self.local.private_redis("/synthetic/redis-server"):
  834. raise RuntimeError("synthetic")
  835. process.terminate.assert_called_once()
  836. def test_private_redis_startup_failure_closes_client_and_never_yields(self):
  837. process = Mock()
  838. process.poll.return_value = 1
  839. with patch.object(self.local.subprocess, "Popen", return_value=process), \
  840. patch.object(self.local.redis, "Redis") as redis:
  841. with self.assertRaisesRegex(self.local.LocalAcceptanceError, "private_redis_exited"):
  842. with self.local.private_redis("/synthetic/redis-server"):
  843. self.fail("Dead Redis cannot be used")
  844. redis.return_value.close.assert_called_once()
  845. class LocalRedisIntegrationTests(unittest.TestCase):
  846. """Opt-in class: real disposable Redis, synthetic website/account I/O.
  847. Not included in the CLI's --offline TEST_NAMES, which promises no subprocesses.
  848. """
  849. def run_real_redis_case(self, *, expire=False):
  850. import shutil
  851. import socket
  852. import time
  853. from tools import ita_query_book_local as local
  854. from utils.safe_redis_cli import SafeRedisClient
  855. executable = shutil.which("redis-server")
  856. if not executable:
  857. self.skipTest("redis-server is needed for the explicitly selected Redis integration test")
  858. original_connect = socket.socket.connect
  859. real_sleep = time.sleep
  860. with local.private_redis(executable) as config:
  861. case = LocalHarnessTests()
  862. case.setUp()
  863. try:
  864. def socket_only(connection, address):
  865. if address != config["unix_socket_path"]:
  866. raise AssertionError("Redis integration attempted non-owned socket")
  867. return original_connect(connection, address)
  868. case.enterContext(patch.object(socket.socket, "connect", socket_only))
  869. for cls in (local.SentinelGCO, local.OrderBookerGCO):
  870. case.enterContext(patch.dict(cls.__init__.__globals__, {"SafeRedisClient": SafeRedisClient}))
  871. if expire:
  872. case.fixture.query_config.sentinel.signal_ttl = 1
  873. read = SafeRedisClient.get
  874. def after_expiry(client, key):
  875. real_sleep(1.1) # Fixture mocks time.sleep; use actual server wall clock here.
  876. return read(client, key)
  877. case.enterContext(patch.object(SafeRedisClient, "get", after_expiry))
  878. report = local.run_framework_once(case.fixture.query_config, case.fixture.book_config,
  879. case.fixture.route, case.cloud, config)
  880. finally:
  881. case.doCleanups()
  882. self.assertFalse(local.Path(config["unix_socket_path"]).parent.exists())
  883. return report
  884. def test_real_framework_publishes_and_consumes_real_redis(self):
  885. report = self.run_real_redis_case()
  886. self.assertTrue(report["passed"], report)
  887. self.assertTrue(report["signalPublished"])
  888. self.assertTrue(report["signalReadByBooker"])
  889. self.assertEqual(report["bookCalls"], 1)
  890. def test_real_redis_expiry_prevents_book_without_republishing(self):
  891. report = self.run_real_redis_case(expire=True)
  892. self.assertTrue(report["signalPublished"])
  893. self.assertFalse(report["signalReadByBooker"])
  894. self.assertEqual(report["bookCalls"], 0)
  895. self.assertFalse(report["passed"])
  896. if __name__ == "__main__":
  897. unittest.main()