| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861 |
- """Real framework creation/publication/dispatch/execution, synthetic I/O only.
- No test-owned signal schema, expiry rule, account dispatcher or retry policy.
- The already-existing Redis fixture simulates a retained server key. Snapshot
- encoding/decoding, account binding, route/date/cooldown decisions and public
- Italy Query/Book remain the real implementations.
- """
- import contextlib
- import copy
- from datetime import date
- import io
- import itertools
- import json
- import tempfile
- from pathlib import Path
- from types import SimpleNamespace
- import unittest
- from unittest.mock import Mock, patch
- from tools import debug_ita_query_book as cli
- from test.ita.test_ita_plugin import OrderBookerGCO, FakeRetainedSignalRedis
- from sentinel import SentinelGCO
- from test.ita import test_ita_calendar_book_flow as book_flow
- from test.ita.test_ita_query_recovery import RecoveryPage, prepared_plugin
- from vs_types import AvailabilityStatus, GroupConfig, QueryWaitMode
- class ExistingFrameworkJointTests(unittest.TestCase):
- def setUp(self):
- # Fail closed if a future test accidentally stops isolating I/O.
- for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
- "requests.sessions.Session.request", "subprocess.Popen"):
- self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
- self.clock = {"now": 1000.0}
- self.retained = None
- self.query_page = RecoveryPage()
- self.query_page.plans = [[(2026, 8, []), (2026, 9, []), (2026, 10, [13, 20])]] * 10
- self.query, self.route = prepared_plugin(self.query_page)
- self.apt = self.route.appointment_type()
- self.apt.weight = 1
- self.query._transient_user_data_path = "/nonexistent/ita-framework-query"
- self.query.free_config.update(otp_mode="manual", final_submit_enabled=False)
- self.query.query = Mock(wraps=self.query.query)
- # Existing fixture is already on Calendar; restore its prepared marker
- # after the framework's real set_config clears per-session state.
- self.query.create_session = Mock(side_effect=lambda:
- self.query._record_calendar_prepared_route(self.query._resolve_route(self.apt), role="query"))
- self.query.cleanup = Mock()
- self.inputs = {"username": "applicant@example.test", "password": "synthetic-applicant-password",
- "expected_start_date": "2026-08-01", "expected_end_date": "2026-10-31"}
- self.order = {"id": 991, "order_id": "SYNTHETIC-ORDER", "status": "processing",
- "user_inputs": copy.deepcopy(self.inputs)}
- self.cloud = Mock()
- self.cloud.get_next_account.return_value = {
- "id": 21, "username": "pool-query@example.test", "password": "synthetic-pool-password"}
- self.cloud.get_vas_task_pop.return_value = self.order
- self.redis = Mock()
- self.redis.setex.side_effect = self.capture_redis_write
- self.redis.get.side_effect = lambda key: (
- self.retained.get(key) if self.retained is not None and key == self.signal_key else None)
- self.redis.delete.side_effect = self.delete_redis_key
- self.signal_key = "vs:signal:" + self.apt.routing_key
- self.executor = Mock()
- self.log = Mock()
- # Existing test pattern: isolate only method dependencies, not methods.
- # Use each loaded class's globals to avoid import-cache/stub ambiguity.
- dependencies = {
- "SafeRedisClient": Mock(return_value=self.redis),
- "VSCloudApi": SimpleNamespace(Instance=lambda: self.cloud, lock_account=Mock()),
- "time": SimpleNamespace(time=lambda: self.clock["now"], sleep=lambda _seconds: None),
- }
- for cls in (SentinelGCO, OrderBookerGCO):
- self.enterContext(patch.dict(cls.__init__.__globals__, dependencies))
- self.enterContext(patch.dict(OrderBookerGCO._execute_book_job.__globals__,
- ThreadPool=SimpleNamespace(getInstance=lambda: self.executor)))
- self.final = self.enterContext(patch("plugins.ita_plugin.submit_final",
- side_effect=AssertionError("Final submission forbidden")))
- # Query month navigation uses only the synthetic page above.
- self.enterContext(patch("plugins.ita_plugin.time.sleep"))
- self.query_config = GroupConfig(
- identifier="offline-query", need_account=True, appointment_types=[self.apt],
- plugin_config={"plugin_name": "ita_plugin"}, free_config=copy.deepcopy(self.query.free_config),
- sentinel={"account_pool_id": "fixture.query.pool", "account_cd": 10800,
- "signal_ttl": 30, "query_wait": {"mode": QueryWaitMode.Fixed, "fixed_wait": 1}})
- self.book_plugin, self.book_page = self.new_book_plugin()
- self.book_config = GroupConfig(
- identifier="offline-book", need_account=True, appointment_types=[self.apt],
- plugin_config={"plugin_name": "ita_plugin"}, free_config=copy.deepcopy(self.book_plugin.free_config),
- booker={"account_source": "order", "target_instances": 1, "booking_cooldown": 45})
- self.sentinel = SentinelGCO(self.query_config, {}, self.log)
- self.booker = OrderBookerGCO(self.book_config, {}, self.log)
- self.sentinel.m_factory.create = Mock(return_value=self.query)
- self.booker.m_factory.create = Mock(return_value=self.book_plugin)
- self.booker._execute_book_job = Mock(wraps=self.booker._execute_book_job)
- # Real GCO stop/cleanup is exercised; browser cleanup remains a fixture.
- self.addCleanup(self.sentinel.stop)
- self.addCleanup(self.booker.stop)
- def new_book_plugin(self):
- page = book_flow.FlowPage([book_flow.month("2026-10", {13: 0, 14: 1})])
- plugin, _, _ = book_flow.prepared_plugin(page, routing_key=self.apt.routing_key)
- plugin.free_config.update(otp_mode="cloud", final_submit_enabled=False)
- plugin.is_healthy = True
- plugin.cleanup = Mock()
- # Login/OTP are already independently tested; this fixture starts at
- # the prepared Calendar but binds it AFTER real order account wiring.
- plugin.create_session = Mock(side_effect=lambda:
- plugin._record_calendar_prepared_route(plugin._resolve_route(self.apt), role="book"))
- original_book = plugin.book
- plugin.observed_approval = None
- def observed_book(trigger, inputs):
- result, plugin.observed_approval = book_flow.book_with_approval(
- plugin, trigger, inputs, call=original_book,
- )
- return result
- plugin.book = Mock(side_effect=observed_book)
- return plugin, page
- def capture_redis_write(self, key, ttl, payload):
- self.assertEqual(key, self.signal_key)
- # Reuse existing retained-key fixture, not a new signal/TTL algorithm.
- self.retained = FakeRetainedSignalRedis(json.loads(payload), self.clock,
- ttl=self.clock["now"] + ttl)
- return True
- def delete_redis_key(self, key):
- if key == self.signal_key:
- self.retained = None
- return 1
- def spawn(self):
- self.sentinel._spawn_sentinel_worker()
- self.booker._spawn_worker(self.apt.routing_key)
- def publish_once(self, *, positive=True):
- # Bound the EXISTING loop to one cycle; do not reimplement its body.
- with patch.object(self.sentinel.m_stop_event, "is_set", side_effect=[False, True]):
- self.sentinel._monitor_loop()
- if positive:
- self.assertIsNotNone(self.retained, self.log.call_args_list)
- def trigger_once(self, page=None):
- with book_flow.browser_navigation(page or self.book_page), \
- patch.object(self.booker.m_stop_event, "is_set", side_effect=[False, True]):
- # Existing Thread creation and joins run as-is inside this loop.
- self.booker._booking_trigger_loop()
- def assert_no_final_or_success_report(self):
- self.final.assert_not_called()
- self.executor.enqueue.assert_not_called()
- self.cloud.update_vas_task.assert_not_called()
- self.cloud.push_weixin_text.assert_not_called()
- def test_real_framework_pool_query_json_order_book_rechecks_current_inventory(self):
- self.spawn()
- self.assertEqual(len(self.sentinel.m_tasks), 1)
- self.assertEqual(len(self.booker.m_tasks), 1)
- self.cloud.get_next_account.assert_called_once_with("fixture.query.pool", 10800)
- self.cloud.get_vas_task_pop.assert_called_once_with("auto." + self.apt.routing_key)
- self.assertEqual(self.query.config.account.username, "pool-query@example.test")
- self.assertEqual(self.query.config.account.id, 21)
- self.assertEqual(self.book_plugin.config.account.username, self.inputs["username"])
- self.assertEqual(self.book_plugin.config.account.password, self.inputs["password"])
- self.assertFalse(self.sentinel.m_tasks[0].book_allowed)
- self.assertEqual(self.booker.m_tasks[0].task_ref, 991)
- self.assertEqual(self.booker.m_tasks[0].acceptable_routing_keys, [self.apt.routing_key])
- self.assertIsNot(self.query.page, self.book_plugin.page)
- self.publish_once()
- self.query.query.assert_called_once_with(self.apt)
- self.redis.setex.assert_called_once()
- key, ttl, raw = self.redis.setex.call_args.args
- self.assertEqual((key, ttl), (self.signal_key, 30))
- payload = json.loads(raw)
- self.assertEqual(set(payload), {"group_id", "apt_type", "query_result", "timestamp"})
- self.assertEqual(payload["group_id"], self.query_config.identifier)
- self.assertEqual(payload["apt_type"], self.apt.model_dump())
- self.assertEqual(payload["query_result"]["earliest_date"], "2026-10-13")
- self.assertEqual(payload["query_result"]["availability_status"], "Available")
- self.assertNotIn("success", payload["query_result"])
- self.assertNotIn("password", raw)
- self.assertNotIn("pool-query", raw)
- self.assertEqual(self.query_page.forward_clicks, [(2026, 9), (2026, 10)])
- self.trigger_once()
- self.booker._execute_book_job.assert_called_once()
- self.book_plugin.book.assert_called_once()
- trigger, inputs = self.book_plugin.book.call_args.args
- self.assertEqual(trigger.apt_type, self.apt)
- self.assertIs(trigger.availability_status, AvailabilityStatus.Available)
- self.assertFalse(trigger.success) # Actual framework decode default.
- self.assertEqual(trigger.earliest_date.date(), date(2026, 10, 13))
- self.assertEqual(inputs, self.inputs)
- self.assertEqual(self.book_plugin.observed_approval.candidate.day, date(2026, 10, 14))
- self.assertEqual(self.book_page.refreshes, 1) # Applicant inventory is scanned once.
- self.assertGreater(len(self.book_page.requests), 0)
- self.assert_no_final_or_success_report()
- self.sentinel.stop()
- self.booker.stop()
- self.query.cleanup.assert_called_once()
- self.book_plugin.cleanup.assert_called_once()
- def test_no_account_or_login_failure_does_not_create_query_task(self):
- self.cloud.get_next_account.side_effect = RuntimeError("synthetic pool failure")
- self.sentinel._spawn_sentinel_worker()
- self.assertEqual(self.sentinel.m_tasks, [])
- self.sentinel.m_factory.create.assert_not_called()
- self.cloud.get_next_account.reset_mock(side_effect=True)
- self.query.create_session.side_effect = RuntimeError("synthetic login failure")
- self.sentinel._spawn_sentinel_worker()
- self.assertEqual(self.sentinel.m_tasks, [])
- self.query.cleanup.assert_called_once()
- self.assertGreater(self.sentinel.m_spawn_cooldown_until, self.clock["now"])
- def test_no_order_does_not_take_pool_account_for_book(self):
- self.cloud.get_vas_task_pop.return_value = None
- self.booker._spawn_worker(self.apt.routing_key)
- self.assertEqual(self.booker.m_tasks, [])
- self.booker.m_factory.create.assert_not_called()
- self.cloud.get_next_account.assert_not_called()
- def test_order_login_failure_uses_existing_cleanup_without_query_account_fallback(self):
- self.book_plugin.create_session.side_effect = RuntimeError("synthetic login failure")
- self.booker._spawn_worker(self.apt.routing_key)
- self.assertEqual(self.booker.m_tasks, [])
- self.assertEqual(self.booker.m_task_data_cache, {})
- self.book_plugin.cleanup.assert_called_once()
- self.cloud.get_next_account.assert_not_called()
- def test_no_availability_does_not_publish_or_trigger_book(self):
- self.query_page.outcomes = ["none"]
- self.spawn()
- self.publish_once(positive=False)
- self.trigger_once()
- self.redis.setex.assert_not_called()
- self.book_plugin.book.assert_not_called()
- self.cloud.slot_refresh_success.assert_called_once()
- self.assert_no_final_or_success_report()
- def test_bad_query_protocol_does_not_publish_a_positive_signal(self):
- self.query_page.outcomes = ["malformed"]
- self.spawn()
- self.publish_once(positive=False)
- self.trigger_once()
- self.redis.setex.assert_not_called()
- self.cloud.slot_refresh_fail.assert_called_once()
- self.book_plugin.book.assert_not_called()
- def test_server_expired_signal_does_not_trigger_book(self):
- self.spawn()
- self.publish_once()
- self.clock["now"] += self.query_config.sentinel.signal_ttl + 1
- self.trigger_once()
- self.book_plugin.book.assert_not_called()
- def test_same_signal_obeys_existing_task_cooldown_not_new_one_shot_rule(self):
- self.query_config.sentinel.signal_ttl = 180
- self.spawn()
- self.publish_once()
- self.trigger_once()
- self.clock["now"] += 1
- self.trigger_once()
- self.book_plugin.book.assert_called_once()
- self.clock["now"] += self.book_config.booker.booking_cooldown
- self.trigger_once()
- self.assertEqual(self.book_plugin.book.call_count, 2)
- self.assert_no_final_or_success_report()
- def test_unmatched_routing_key_is_filtered_by_real_trigger_loop(self):
- self.spawn()
- self.publish_once()
- self.booker.m_tasks[0].acceptable_routing_keys = ["slot.other.it.tourist"]
- self.trigger_once()
- self.book_plugin.book.assert_not_called()
- def test_date_outside_order_end_is_filtered_before_book(self):
- self.order["user_inputs"]["expected_end_date"] = "2026-10-12"
- self.spawn()
- self.publish_once()
- self.trigger_once()
- self.book_plugin.book.assert_not_called()
- def test_order_start_bound_reaches_real_book_selection(self):
- self.order["user_inputs"]["expected_start_date"] = "2026-10-15"
- self.spawn()
- self.publish_once()
- self.trigger_once()
- self.book_plugin.book.assert_called_once()
- self.assertIsNone(self.book_plugin.observed_approval)
- self.assert_no_final_or_success_report()
- def test_paused_order_is_removed_without_book(self):
- self.spawn()
- self.publish_once()
- self.order["status"] = "pause"
- self.trigger_once()
- self.book_plugin.book.assert_not_called()
- self.assertEqual(self.booker.m_tasks, [])
- self.book_plugin.cleanup.assert_called_once()
- def test_corrupt_redis_payload_uses_existing_delete_branch(self):
- self.spawn()
- self.publish_once()
- self.retained.payload = "invalid-json"
- self.trigger_once()
- self.redis.delete.assert_called_once_with(self.signal_key)
- self.book_plugin.book.assert_not_called()
- def test_one_shared_signal_can_trigger_two_separately_bound_orders(self):
- self.spawn()
- other, other_page = self.new_book_plugin()
- other_order = copy.deepcopy(self.order)
- other_order.update(id=992, order_id="SYNTHETIC-OTHER")
- other_order["user_inputs"]["username"] = "second-applicant@example.test"
- self.cloud.get_vas_task_pop.return_value = other_order
- self.booker.m_factory.create.return_value = other
- self.booker._spawn_worker(self.apt.routing_key)
- self.publish_once()
- # Both fixtures start directly in the positive month; no month-click
- # adapter is needed for this two-thread test, only no-delay sleeps.
- with patch.object(self.booker.m_stop_event, "is_set", side_effect=[False, True]):
- self.booker._booking_trigger_loop()
- self.book_plugin.book.assert_called_once()
- other.book.assert_called_once()
- self.assertEqual(other.config.account.username, "second-applicant@example.test")
- self.assertIsNot(self.book_page, other_page)
- self.assertEqual(other.observed_approval.candidate.day, date(2026, 10, 14))
- self.assertEqual(self.booker._execute_book_job.call_count, 2)
- self.cloud.get_next_account.assert_called_once()
- self.assert_no_final_or_success_report()
- def test_later_negative_query_keeps_existing_signal_until_redis_expiry(self):
- self.spawn()
- self.publish_once()
- original = self.retained.payload
- self.query_page.outcomes = ["none"]
- self.clock["now"] += 2
- self.publish_once(positive=False)
- self.assertEqual(self.query.query.call_count, 2)
- self.redis.setex.assert_called_once()
- self.redis.delete.assert_not_called()
- self.assertEqual(self.retained.payload, original)
- class OfflineCliTests(unittest.TestCase):
- def test_old_live_flag_is_rejected_before_loading_tests(self):
- with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames") as load, \
- contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as caught:
- cli.main(["--run"])
- self.assertEqual(caught.exception.code, 2)
- load.assert_not_called()
- def test_cli_runs_only_existing_framework_suite_and_reports_offline(self):
- result = SimpleNamespace(testsRun=26, failures=[], errors=[], skipped=[], wasSuccessful=lambda: True)
- with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames") as load, \
- patch.object(cli.unittest, "TextTestRunner") as runner, \
- contextlib.redirect_stdout(io.StringIO()) as output:
- runner.return_value.run.return_value = result
- self.assertEqual(cli.main([]), 0)
- load.assert_called_once_with(cli.TEST_NAMES)
- summary = json.loads(output.getvalue().split("ITA_QUERY_BOOK_FRAMEWORK_RESULT=")[1])
- self.assertTrue(summary["passed"])
- self.assertFalse(summary["liveAcceptance"])
- self.assertEqual(summary["externalBoundaries"], "simulated")
- def test_empty_skipped_or_failed_suite_does_not_pass(self):
- for count, skipped, successful in ((0, [], True), (1, ["fixture"], True), (1, [], False)):
- result = SimpleNamespace(testsRun=count, failures=[], errors=[], skipped=skipped,
- wasSuccessful=lambda: successful)
- with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames"), \
- patch.object(cli.unittest, "TextTestRunner") as runner, \
- contextlib.redirect_stdout(io.StringIO()):
- runner.return_value.run.return_value = result
- self.assertEqual(cli.main(["--offline"]), 1)
- class LocalHarnessTests(unittest.TestCase):
- """Same real GCO fixtures; site/pool/Redis are synthetic in offline runs."""
- def setUp(self):
- from tools import ita_query_book_local as local
- self.local = local
- self.fixture = ExistingFrameworkJointTests()
- self.fixture.setUp()
- self.addCleanup(self.fixture.doCleanups)
- self.enterContext(contextlib.redirect_stdout(io.StringIO()))
- self.enterContext(patch.object(local, "validate_cloud_otp_environment"))
- f = self.fixture
- f.cloud.get_next_account.return_value.update(pool_name="fixture.query.pool", status="active")
- self.applicant = local.VSAccount(username=f.inputs["username"], password=f.inputs["password"])
- self.cloud = local.LocalCloudBoundary(f.cloud, f.query_config,
- SimpleNamespace(routing_key=f.route.routing_key, mail=None),
- SimpleNamespace(model_dump=lambda: {}), self.applicant,
- {key: f.inputs[key] for key in ("expected_start_date", "expected_end_date")})
- self.enterContext(patch.object(local, "CalendarRequestAudit", return_value=Mock(**{
- "settled_snapshot.return_value": {"otpRequests": 0, "avantiPosts": 0,
- "availabilityRequests": 1, "timeSlotRequests": 1, "finalRequests": 0}})))
- self.enterContext(patch.object(local.SentinelGCO, "_is_within_active_hours", return_value=True))
- self.enterContext(patch.object(local.OrderBookerGCO, "_is_within_active_hours", return_value=True))
- # Factories still belong to the GCO. Substitute only browser creation.
- real_observe = local.observe_factory
- def synthetic_factory(gco, role, stack, observed, on_created=None):
- gco.m_factory.create = Mock(return_value=f.query if role == "query" else f.book_plugin)
- return real_observe(gco, role, stack, observed, on_created=on_created)
- self.enterContext(patch.object(local, "observe_factory", side_effect=synthetic_factory))
- self.enterContext(book_flow.browser_navigation(f.book_page))
- def run_case(self):
- return self.local.run_framework_once(self.fixture.query_config, self.fixture.book_config,
- self.fixture.route, self.cloud, {})
- def test_one_real_framework_iteration_preserves_pool_order_signal_and_selection(self):
- report = self.run_case()
- self.assertTrue(report["passed"], report)
- self.assertEqual(report["outcome"], "pre_final")
- self.assertEqual((report["queryCalls"], report["bookCalls"]), (1, 1))
- self.assertTrue(report["signalPublished"])
- self.assertTrue(report["signalReadByBooker"])
- self.assertTrue(report["selectionVerified"])
- self.assertTrue(report["cleanupVerified"])
- self.assertFalse(report["cloudOrders"])
- self.fixture.cloud.get_next_account.assert_called_once_with("fixture.query.pool", 10800)
- self.fixture.cloud.get_vas_task_pop.assert_not_called()
- self.fixture.cloud.update_vas_task.assert_not_called()
- self.fixture.cloud.slot_snapshot_report.assert_not_called()
- self.assertNotEqual(self.fixture.query.config.account.username, self.fixture.book_plugin.config.account.username)
- self.assertEqual(self.fixture.book_plugin.config.account.username, self.applicant.username)
- self.assertEqual(self.fixture.book_plugin.book.call_args.args[1], self.cloud.order["user_inputs"])
- def test_no_availability_does_not_call_book(self):
- self.fixture.query_page.plans = [[(2026, 8, []), (2026, 9, []), (2026, 10, [])]] * 2
- report = self.run_case()
- self.assertFalse(report["passed"])
- self.assertEqual(report["outcome"], "no_availability")
- self.assertEqual(report["bookCalls"], 0)
- self.assertFalse(report["signalPublished"])
- self.assertTrue(report["cleanupVerified"])
- def test_failed_redis_write_is_not_a_successful_handoff(self):
- self.fixture.redis.setex.side_effect = lambda *_: False
- report = self.run_case()
- self.assertFalse(report["passed"])
- self.assertEqual(report["reason"], "redis_publication_failed")
- self.assertEqual(report["bookCalls"], 0)
- def test_expired_signal_does_not_trigger_or_get_republished(self):
- self.fixture.redis.get.side_effect = lambda *_: None
- report = self.run_case()
- self.assertTrue(report["signalPublished"])
- self.assertFalse(report["signalReadByBooker"])
- self.assertEqual(report["bookCalls"], 0)
- self.assertEqual(report["outcome"], "not_triggered_expired_or_date_filtered")
- self.fixture.redis.setex.assert_called_once()
- def test_order_date_range_filters_real_trigger_without_calling_book(self):
- self.cloud.order["user_inputs"]["expected_end_date"] = "2026-09-30"
- report = self.run_case()
- self.assertEqual(report["bookCalls"], 0)
- self.assertTrue(report["signalReadByBooker"])
- self.assertFalse(report["passed"])
- def test_pool_failure_is_redacted_and_does_not_retry(self):
- self.fixture.cloud.get_next_account.side_effect = RuntimeError("secret-password-and-body")
- report = self.run_case()
- self.assertEqual(report["reason"], "pool_allocation_failed")
- self.assertEqual(self.cloud.pool_calls, 1)
- self.assertNotIn("secret-password", json.dumps(report))
- self.assertTrue(report["cleanupVerified"])
- def test_same_account_cannot_masquerade_as_dual_account_acceptance(self):
- self.fixture.cloud.get_next_account.return_value["username"] = self.applicant.username
- report = self.run_case()
- self.assertFalse(report["passed"])
- self.assertEqual(report["reason"], "query_and_book_accounts_same_choose_other_applicant")
- self.assertEqual(report["queryCalls"], 0)
- def test_cloud_order_and_reporting_methods_are_not_forwarded(self):
- for name in ("update_vas_task", "push_weixin_text", "get_vas_task", "return_vas_task_to_queue"):
- with self.assertRaises(self.local.LocalAcceptanceError):
- getattr(self.cloud, name)
- getattr(self.fixture.cloud, name).assert_not_called()
- def test_unexpected_final_request_fails_even_after_selection(self):
- self.local.CalendarRequestAudit.return_value.settled_snapshot.return_value["finalRequests"] = 1
- report = self.run_case()
- self.assertFalse(report["passed"])
- self.assertEqual(report["reason"], "unexpected_final_request_do_not_rerun")
- def test_book_exception_does_not_escape_as_success_or_leak_body(self):
- self.fixture.book_plugin.book.side_effect = RuntimeError("secret-otp-body")
- report = self.run_case()
- self.assertEqual(report["reason"], "book_failed")
- self.assertEqual(report["bookErrorType"], "RuntimeError")
- self.assertNotIn("secret-otp", json.dumps(report))
- self.assertTrue(report["cleanupVerified"])
- def test_final_success_cannot_be_reported_by_prefinal_test(self):
- from vs_types import VSBookResult
- self.fixture.book_plugin.book.side_effect = None
- self.fixture.book_plugin.book.return_value = VSBookResult(success=True)
- report = self.run_case()
- self.assertFalse(report["passed"])
- self.assertEqual(report["reason"], "unexpected_book_success_before_final")
- self.fixture.cloud.update_vas_task.assert_not_called()
- self.assertGreater(self.cloud.forbidden_calls, 0)
- def test_book_login_failure_does_not_allocate_pool_account(self):
- self.fixture.book_plugin.create_session.side_effect = RuntimeError("secret-provider-response")
- report = self.run_case()
- self.assertEqual(report["reason"], "applicant_session_not_created")
- self.fixture.cloud.get_next_account.assert_not_called()
- self.assertTrue(report["cleanupVerified"])
- def test_interrupt_during_query_cleans_both_sessions_without_book(self):
- self.fixture.query.query.side_effect = KeyboardInterrupt()
- report = self.run_case()
- self.assertEqual(report["outcome"], "interrupted")
- self.assertTrue(report["cleanupVerified"])
- self.assertEqual(report["bookCalls"], 0)
- def test_cleanup_failure_invalidates_otherwise_successful_selection(self):
- self.fixture.book_plugin.cleanup.side_effect = RuntimeError("synthetic-cleanup-failure")
- report = self.run_case()
- self.assertTrue(report["selectionVerified"])
- self.assertFalse(report["passed"])
- self.assertFalse(report["cleanupVerified"])
- def test_repeated_otp_is_not_accepted_as_single_round(self):
- self.local.CalendarRequestAudit.return_value.settled_snapshot.return_value["otpRequests"] = 2
- report = self.run_case()
- self.assertFalse(report["passed"])
- self.assertEqual(report["reason"], "unexpected_repeated_preparation")
- class LocalFinalTests(unittest.TestCase):
- def setUp(self):
- from tools import ita_query_book_local as local
- self.local = local
- self.applicant = SimpleNamespace(
- username="Applicant@example.test", password="fixture-password")
- self.route = SimpleNamespace(
- service_id=9001, routing_key="slot.fixture.it.tourist",
- capability="single_schengen_tourism", lookahead_months=3)
- candidate = SimpleNamespace(
- day=date(2026, 10, 13), time_label="10:05 - 11:05", slots_free=1)
- self.approval = SimpleNamespace(candidate=candidate)
- self.plugin = SimpleNamespace(config=SimpleNamespace(account=self.applicant))
- self.audit = Mock()
- self.audit.settled_snapshot.return_value = {
- "otpRequests": 0, "avantiPosts": 0, "availabilityRequests": 0,
- "timeSlotRequests": 0, "finalRequests": 0,
- }
- self.observed = {
- "book": SimpleNamespace(plugin=self.plugin, audit=self.audit),
- "query": SimpleNamespace(plugin=object(), audit=self.audit),
- }
- self.control = local.LocalFinalSubmission(self.applicant, self.route)
- def submit(self, result):
- production = Mock(return_value=result)
- with patch.object(self.local, "verify_plugin_selection"):
- returned = self.control.submit(
- self.plugin, self.route, self.approval, self.observed, production)
- production.assert_called_once_with(self.plugin, self.route, self.approval)
- return returned
- def test_standard_success_delegates_once_without_private_fence(self):
- result = SimpleNamespace(success=True)
- self.assertIs(self.submit(result), result)
- self.assertTrue(self.control.used)
- self.assertTrue(self.control.dispatched)
- self.assertFalse(hasattr(self.control, "claim_path"))
- def test_standard_failure_remains_retryable_by_the_shared_booker(self):
- result = SimpleNamespace(success=False)
- self.assertIs(self.submit(result), result)
- self.assertTrue(self.control.dispatched)
- self.assertNotEqual(getattr(self.control, "failure_reason", None), "unknown_do_not_retry")
- def test_same_local_control_cannot_dispatch_twice_in_one_run(self):
- self.submit(SimpleNamespace(success=False))
- with self.assertRaises(self.local.LocalAcceptanceError):
- self.control.submit(
- self.plugin, self.route, self.approval, self.observed, Mock())
- def test_wrong_applicant_or_existing_final_request_is_rejected(self):
- production = Mock()
- self.plugin.config.account.username = "other@example.test"
- with self.assertRaises(self.local.LocalAcceptanceError):
- self.control.submit(
- self.plugin, self.route, self.approval, self.observed, production,
- )
- production.assert_not_called()
- class LocalFinalCompositionTests(unittest.TestCase):
- def setUp(self):
- from tools import ita_query_book_local as local
- self.local = local
- def test_noninteractive_failure_uses_ordinary_exit_code(self):
- args = SimpleNamespace(
- submit_once=True, local_run=True, local_preflight=False,
- book_account_file="fixture")
- group = SimpleNamespace(sentinel=SimpleNamespace(account_pool_id="fixture"))
- route = SimpleNamespace(routing_key="fixture", mail=None)
- applicant = SimpleNamespace(
- username="applicant@example.test", password="fixture-password")
- result = {
- "passed": False, "outcome": "book_failed_retryable",
- "finalDispatched": True,
- }
- with contextlib.redirect_stdout(io.StringIO()), \
- patch.object(self.local, "load_settings", return_value=(group, route, Mock(), {})), \
- patch("sys.stdin.isatty", return_value=False), \
- patch("builtins.input", side_effect=AssertionError("No interactive input")) as prompt, \
- patch.object(self.local, "check_dependencies", return_value=("fixture", "fixture")), \
- patch.object(self.local, "load_local_account", return_value=applicant), \
- patch.object(self.local, "validate_cloud_otp_environment"), \
- patch.object(self.local, "LocalFinalSubmission"), \
- patch.object(self.local, "build_groups", return_value=(Mock(), Mock())), \
- patch.object(self.local, "LocalCloudBoundary"), \
- patch.object(self.local.VSCloudApi, "Instance"), \
- patch.object(self.local, "private_redis", return_value=contextlib.nullcontext({})), \
- patch.object(self.local, "run_framework_once", return_value=result):
- self.assertEqual(self.local.main_local(args), 1)
- result.update(passed=True, outcome="confirmed")
- self.assertEqual(self.local.main_local(args), 0)
- prompt.assert_not_called()
- class LocalConfigurationTests(unittest.TestCase):
- def setUp(self):
- from tools import ita_query_book_local as local
- self.local = local
- self.enterContext(contextlib.redirect_stdout(io.StringIO()))
- def settings_fixture(self):
- args = SimpleNamespace(config="synthetic.json", group="synthetic-group", proxy="http://127.0.0.1:6268",
- expected_start_date=None, expected_end_date=None)
- group = {"identifier": args.group, "plugin_config": {"plugin_name": "ita_plugin"},
- "sentinel": {"account_pool_id": "synthetic-pool", "signal_ttl": 30},
- "appointment_types": [{"routing_key": "slot.other.it.tourist", "weight": 1}],
- "free_config": {"query_mode": "calendar", "otp_mode": "cloud", "final_submit_enabled": False,
- "apt_configs": {"slot.other.it.tourist": {
- "service_id": 9001, "capability": "single_schengen_tourism",
- "calendar_scan": {"lookahead_months": 3},
- "form": {"booking_type_control_id": "typeofbookingddl", "booking_type_value": "1",
- "booking_type_labels": ["Single booking"], "purpose_control_id": "ddls_0",
- "purpose_value": "42", "purpose_labels": ["Tourism"]},
- "mail": {"authorization_source": "account"}}}}}
- return args, group
- def test_real_settings_parser_accepts_other_region_without_fixed_mailbox(self):
- args, group = self.settings_fixture()
- with patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
- patch.object(self.local.configure, "TEST_ACCOUNT", None):
- source, route, proxy, preferences = self.local.load_settings(args)
- self.assertEqual(route.service_id, 9001)
- self.assertEqual(source.sentinel.account_pool_id, "synthetic-pool")
- self.assertEqual(route.mail.mailbox_for("second@example.test"), "second@example.test")
- self.assertEqual(proxy.port, 6268)
- self.assertEqual(preferences, {})
- def test_invalid_settings_cannot_reach_dependencies_or_pool(self):
- args, template = self.settings_fixture()
- for changes in ({"query_mode": "services_probe"}, {"otp_mode": "manual"}, {"final_submit_enabled": True}):
- group = copy.deepcopy(template)
- group["free_config"].update(changes)
- with self.subTest(changes=changes), \
- patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
- patch.object(self.local.configure, "TEST_ACCOUNT", None), \
- self.assertRaises(self.local.LocalAcceptanceError):
- self.local.load_settings(args)
- def test_public_proxy_and_reversed_date_range_are_rejected_before_run(self):
- args, group = self.settings_fixture()
- for proxy, start, end in (("http://remote.example.test:6268", None, None),
- (args.proxy, "2026-10-31", "2026-10-01")):
- args.proxy, args.expected_start_date, args.expected_end_date = proxy, start, end
- with patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
- patch.object(self.local.configure, "TEST_ACCOUNT", None), \
- self.assertRaises(Exception):
- self.local.load_settings(args)
- def test_successful_preflight_never_prompts_allocates_or_launches(self):
- args = SimpleNamespace(local_preflight=True)
- group = SimpleNamespace(sentinel=SimpleNamespace(account_pool_id="synthetic-pool"))
- route = SimpleNamespace(routing_key="synthetic-route")
- with patch.object(self.local, "load_settings", return_value=(group, route, Mock(), {})), \
- patch.object(self.local, "check_dependencies", return_value=("redis-server", "/synthetic/chrome")), \
- patch.object(self.local, "_get_credentials") as credentials, \
- patch.object(self.local.VSCloudApi, "Instance") as api, \
- patch.object(self.local, "private_redis") as private_redis:
- self.assertEqual(self.local.main_local(args), 0)
- credentials.assert_not_called()
- api.assert_not_called()
- private_redis.assert_not_called()
- def test_default_cli_never_starts_local_run_and_explicit_mode_is_forwarded(self):
- with patch.object(self.local, "main_local", return_value=7) as live:
- self.assertEqual(cli.main(["--local-run", "--group", "my-route-group"]), 7)
- self.assertEqual(live.call_args.args[0].group, "my-route-group")
- self.assertTrue(live.call_args.args[0].local_run)
- def test_preflight_checks_dependencies_before_api_or_credentials(self):
- args = SimpleNamespace(local_preflight=True)
- with patch.object(self.local, "load_settings", return_value=(Mock(), Mock(), Mock(), {})), \
- patch.object(self.local, "check_dependencies", side_effect=self.local.LocalAcceptanceError("missing_dependency")), \
- patch.object(self.local, "_get_credentials") as credentials, \
- patch.object(self.local.VSCloudApi, "Instance") as api:
- self.assertEqual(self.local.main_local(args), 1)
- credentials.assert_not_called()
- api.assert_not_called()
- def test_group_copy_preserves_service_and_ttl_not_production_config(self):
- group = GroupConfig(identifier="source", sentinel={"account_pool_id": "test-pool", "signal_ttl": 37},
- appointment_types=[{"routing_key": "slot.other.it.tourist", "weight": 1}],
- free_config={"query_mode": "calendar", "otp_mode": "cloud", "final_submit_enabled": False,
- "persistent_browser_profile_path": "/never-touch", "apt_configs": {"some-route": {"service_id": 999}}})
- before = group.model_dump()
- query, book = self.local.build_groups(group, "synthetic")
- self.assertEqual(group.model_dump(), before)
- self.assertEqual(query.sentinel.signal_ttl, 37)
- self.assertEqual(query.sentinel.account_pool_id, "test-pool")
- self.assertEqual(query.free_config["apt_configs"], before["free_config"]["apt_configs"])
- self.assertEqual(book.booker.account_source, "order")
- self.assertEqual(book.free_config["query_mode"], "services_probe")
- self.assertNotIn("persistent_browser_profile_path", query.free_config)
- self.assertFalse(book.free_config["final_submit_enabled"])
- def test_final_flag_only_enables_applicant_copy_and_requires_live_cli(self):
- group = GroupConfig(identifier="source", free_config={"final_submit_enabled": False})
- group.appointment_types = [SimpleNamespace(weight=1)]
- query, book = self.local.build_groups(group, "fixture", submit_once=True)
- self.assertFalse(group.free_config["final_submit_enabled"])
- self.assertFalse(query.free_config["final_submit_enabled"])
- self.assertTrue(book.free_config["final_submit_enabled"])
- with patch.object(self.local, "main_local", return_value=0) as live:
- for args in (["--submit-once"], ["--local-preflight", "--submit-once"], ["--offline", "--submit-once"]):
- with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
- cli.main(args)
- live.assert_not_called()
- self.assertEqual(cli.main(["--local-run", "--submit-once"]), 0)
- self.assertTrue(live.call_args.args[0].submit_once)
- def test_final_requires_explicit_live_mode_before_pool_or_browser(self):
- args = SimpleNamespace(submit_once=True, local_run=False)
- with patch.object(self.local, "load_settings", return_value=(Mock(), Mock(), Mock(), {})), \
- patch.object(self.local, "check_dependencies") as dependencies, \
- patch.object(self.local.VSCloudApi, "Instance") as api:
- self.assertEqual(self.local.main_local(args), 1)
- dependencies.assert_not_called()
- api.assert_not_called()
- def test_private_redis_is_owned_socket_only_no_shared_flush(self):
- process = Mock()
- process.poll.return_value = None
- with patch.object(self.local.subprocess, "Popen", return_value=process) as popen, \
- patch.object(self.local.redis, "Redis") as redis:
- redis.return_value.ping.return_value = True
- with self.local.private_redis("/synthetic/redis-server") as config:
- self.assertTrue(config["unix_socket_path"].startswith("/tmp/ita-qb-"))
- self.assertNotIn("host", config)
- command = popen.call_args.args[0]
- self.assertEqual(command[command.index("--port") + 1], "0")
- self.assertEqual(command[command.index("--save") + 1], "")
- self.assertEqual(command[command.index("--appendonly") + 1], "no")
- process.terminate.assert_called_once()
- process.wait.assert_called_once_with(timeout=5)
- redis.return_value.flushdb.assert_not_called()
- redis.return_value.flushall.assert_not_called()
- self.assertFalse(self.local.Path(config["unix_socket_path"]).parent.exists())
- def test_private_redis_cleanup_also_runs_when_test_fails(self):
- process = Mock()
- process.poll.return_value = None
- with patch.object(self.local.subprocess, "Popen", return_value=process), \
- patch.object(self.local.redis, "Redis") as redis:
- redis.return_value.ping.return_value = True
- with self.assertRaisesRegex(RuntimeError, "synthetic"):
- with self.local.private_redis("/synthetic/redis-server"):
- raise RuntimeError("synthetic")
- process.terminate.assert_called_once()
- def test_private_redis_startup_failure_closes_client_and_never_yields(self):
- process = Mock()
- process.poll.return_value = 1
- with patch.object(self.local.subprocess, "Popen", return_value=process), \
- patch.object(self.local.redis, "Redis") as redis:
- with self.assertRaisesRegex(self.local.LocalAcceptanceError, "private_redis_exited"):
- with self.local.private_redis("/synthetic/redis-server"):
- self.fail("Dead Redis cannot be used")
- redis.return_value.close.assert_called_once()
- class LocalRedisIntegrationTests(unittest.TestCase):
- """Opt-in class: real disposable Redis, synthetic website/account I/O.
- Not included in the CLI's --offline TEST_NAMES, which promises no subprocesses.
- """
- def run_real_redis_case(self, *, expire=False):
- import shutil
- import socket
- import time
- from tools import ita_query_book_local as local
- from utils.safe_redis_cli import SafeRedisClient
- executable = shutil.which("redis-server")
- if not executable:
- self.skipTest("redis-server is needed for the explicitly selected Redis integration test")
- original_connect = socket.socket.connect
- real_sleep = time.sleep
- with local.private_redis(executable) as config:
- case = LocalHarnessTests()
- case.setUp()
- try:
- def socket_only(connection, address):
- if address != config["unix_socket_path"]:
- raise AssertionError("Redis integration attempted non-owned socket")
- return original_connect(connection, address)
- case.enterContext(patch.object(socket.socket, "connect", socket_only))
- for cls in (local.SentinelGCO, local.OrderBookerGCO):
- case.enterContext(patch.dict(cls.__init__.__globals__, {"SafeRedisClient": SafeRedisClient}))
- if expire:
- case.fixture.query_config.sentinel.signal_ttl = 1
- read = SafeRedisClient.get
- def after_expiry(client, key):
- real_sleep(1.1) # Fixture mocks time.sleep; use actual server wall clock here.
- return read(client, key)
- case.enterContext(patch.object(SafeRedisClient, "get", after_expiry))
- report = local.run_framework_once(case.fixture.query_config, case.fixture.book_config,
- case.fixture.route, case.cloud, config)
- finally:
- case.doCleanups()
- self.assertFalse(local.Path(config["unix_socket_path"]).parent.exists())
- return report
- def test_real_framework_publishes_and_consumes_real_redis(self):
- report = self.run_real_redis_case()
- self.assertTrue(report["passed"], report)
- self.assertTrue(report["signalPublished"])
- self.assertTrue(report["signalReadByBooker"])
- self.assertEqual(report["bookCalls"], 1)
- def test_real_redis_expiry_prevents_book_without_republishing(self):
- report = self.run_real_redis_case(expire=True)
- self.assertTrue(report["signalPublished"])
- self.assertFalse(report["signalReadByBooker"])
- self.assertEqual(report["bookCalls"], 0)
- self.assertFalse(report["passed"])
- if __name__ == "__main__":
- unittest.main()
|