| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212 |
- import copy
- import ast
- import json
- import shutil
- import subprocess
- import tempfile
- import unittest
- from contextlib import ExitStack, redirect_stdout
- from io import StringIO
- from pathlib import Path
- from types import SimpleNamespace
- from unittest.mock import Mock, patch
- from plugins import ita_plugin as calendar_book
- from plugins.ita_plugin import AVAILABILITY_PATH, CALENDAR_PATH
- from plugins.ita_plugin import ItaPlugin
- from test.ita import test_debug_ita_calendar_gate as prep_fixtures
- from test.ita import test_debug_ita_production_query_gate as audit_fixtures
- from test.ita import test_ita_calendar_book_flow as flow_fixtures
- from tools import debug_ita_book_gate as gate
- from tools import debug_ita_calendar_gate as preparation
- from vs_types import AvailabilityStatus, VSBookResult, VSQueryResult
- ORIGIN = "https://prenotami.esteri.it"
- USERNAME = "applicant@example.test"
- PASSWORD = "private-test-pass"
- OTP = "012345"
- def gate_env():
- env = prep_fixtures.gate_env()
- env.update(ITA_BOOK_USERNAME=USERNAME, ITA_BOOK_PASSWORD=PASSWORD)
- return env
- class GateListener(flow_fixtures.FakeListener):
- def stop(self):
- # Installed DrissionPage stop() dereferences None on a repeated stop.
- if not self.listening:
- raise AttributeError("Fixture listener already stopped")
- super().stop()
- def start(self, targets, method):
- # The same listener is used for preparation and the real Book scanner.
- if targets in (preparation.OTP_PATH, self.page.booking_path):
- self.starts += 1
- self.target = targets
- self.queue.clear()
- self.listening = True
- self.page.events.append("listen-start")
- else:
- super().start(targets, method)
- class GateElement:
- def __init__(self, page, selector):
- self.page, self.selector = page, selector
- def input(self, value, *, clear):
- if self.selector != "#otp-input" or clear is not True:
- raise AssertionError("Unexpected input")
- self.page.otp_value = value if self.page.otp_write_matches else ""
- def run_js(self, script, value):
- if script != "return this.value === arguments[0];":
- raise AssertionError("Unexpected OTP readback")
- return self.page.otp_value == value
- def click(self):
- if self.selector == "#otp-input":
- return
- if self.selector == "#otp-send":
- self.page.otp_clicks += 1
- packet = self.page.preparation_packet(preparation.OTP_PATH, "GET")
- packet.url += "?ServiceID=" + str(self.page.service_id)
- packet.response.raw_body = json.dumps("SENT")
- self.page.emit(preparation.OTP_PATH, "GET")
- if self.page.duplicate_otp:
- self.page.emit(preparation.OTP_PATH, "GET")
- elif self.selector == "#btnAvanti":
- self.page.avanti_clicks += 1
- if self.page.auto_accept is not True:
- raise AssertionError("AVANTI confirmation was not enabled")
- packet = self.page.preparation_packet(self.page.booking_path, "POST")
- packet.response.status = self.page.avanti_status
- packet.response.url = ORIGIN + CALENDAR_PATH
- packet.response.headers = {"Location": CALENDAR_PATH + "?selectedService=fixture"}
- self.page.url = ORIGIN + CALENDAR_PATH
- self.page.emit(self.page.booking_path, "POST")
- if self.page.duplicate_avanti:
- self.page.emit(self.page.booking_path, "POST")
- # The original page's Calendar bootstrap is not Book's fresh scan.
- self.page.emit(AVAILABILITY_PATH, "POST")
- else:
- raise AssertionError("The gate must not click any other control")
- if self.page.preparation_mutator:
- self.page.preparation_mutator(packet, self.selector)
- self.page.listen.queue.append(packet)
- class GatePage(flow_fixtures.FlowPage):
- def __init__(self, months=None):
- super().__init__(months)
- self.url = ORIGIN + "/UserArea"
- self.service_id = 4937
- self.booking_path = "/Services/Booking/4937"
- self.driver = audit_fixtures.FakeDriver()
- self.listen = GateListener(self)
- self.set = SimpleNamespace(auto_handle_alert=self.auto_handle_alert)
- self.auto_accept = False
- self.alert_settings = []
- self.otp_value = ""
- self.otp_write_matches = True
- self.otp_clicks = self.avanti_clicks = 0
- self.duplicate_otp = self.duplicate_avanti = False
- self.avanti_status = 302
- self.preparation_mutator = None
- self.preflight_changes = {}
- self.preflight_hook = None
- self.commands = []
- def auto_handle_alert(self, on_off=True, accept=True):
- self.auto_accept = accept if on_off else False
- self.alert_settings.append(self.auto_accept)
- def run_cdp(self, name):
- self.commands.append(name)
- return {}
- def emit(self, path, method="POST"):
- if path.endswith("InsertNewBooking"):
- self.guard_final_count += 1
- callback = self.driver.immediate_event_handlers.get(preparation.CalendarRequestAudit.EVENT)
- if callback:
- callback(request={"url": ORIGIN + path, "method": method})
- def preparation_packet(self, path, method):
- return SimpleNamespace(
- tab_id=self.tab_id, is_failed=False, url=ORIGIN + path, method=method,
- response=SimpleNamespace(status=200, raw_body="", url=ORIGIN + path, headers={}),
- )
- def response_packet(self, path, body, items, day=None):
- self.emit(path)
- return super().response_packet(path, body, items, day)
- def ele(self, selector, timeout=None):
- if selector in ("#otp-send", "#otp-input", "#btnAvanti"):
- return GateElement(self, selector)
- return None
- def run_js(self, script, *args):
- if "coordinate:ita-book-gate-form-boundary" in script:
- if self.preflight_hook:
- self.preflight_hook()
- return prep_fixtures.booking_preflight_snapshot(
- formReady=self.url == ORIGIN + self.booking_path,
- otpValuePresent=bool(self.otp_value), otpSendEnabled=self.otp_clicks == 0,
- **self.preflight_changes,
- )
- if script == preparation.AVANTI_FAILURE_DIAGNOSTIC_SCRIPT:
- return {"path": self.url.removeprefix(ORIGIN), "otpValuePresent": bool(self.otp_value),
- "bookingFormPresent": self.url == ORIGIN + self.booking_path}
- return super().run_js(script, *args)
- def make_plugin(page):
- # No constructor, files, browser, real credentials, mail or external service.
- plugin = ItaPlugin.__new__(ItaPlugin)
- plugin.group_id = "offline-book-gate"
- plugin.logger = None
- plugin.page = page
- plugin._transient_user_data_path = "/unused/ita-book-gate-test"
- plugin.mouse = SimpleNamespace(human_click_ele=lambda element: element.click())
- plugin.session_create_time = 0
- plugin.is_healthy = False
- def create():
- plugin.session_create_time = 123.0
- plugin.is_healthy = True
- plugin.create_session = Mock(side_effect=create)
- plugin.cleanup = Mock()
- def enter(apt_type, **kwargs):
- page.url = ORIGIN + page.booking_path
- return VSQueryResult(success=True, apt_type=apt_type, availability_status=AvailabilityStatus.NoneAvailable)
- plugin._enter_service = Mock(side_effect=enter)
- plugin.query = Mock(side_effect=AssertionError("Book must not call public Query"))
- plugin.book = Mock(wraps=plugin.book)
- plugin._record_calendar_prepared_route = Mock(wraps=plugin._record_calendar_prepared_route)
- return plugin
- class BookGateFlowTests(unittest.TestCase):
- def run_gate(self, page=None, *, env=None, execute=True, inputs=None, configure=None,
- otp_reader=None, before=None, after=None, reservation_hook=None,
- use_local_query_account=False, verify_receipts=False, submit_once=False,
- final_confirm=lambda _: "no", review_reader=lambda _: ""):
- page = page or GatePage()
- plugin = make_plugin(page)
- # __del__ invokes cleanup again. Keep a fault-injection mock from raising
- # an unraisable exception after this test has already asserted its result.
- self.addCleanup(lambda: setattr(plugin.cleanup, "side_effect", None))
- if configure:
- configure(plugin, page)
- captured = StringIO()
- reservation_calls = []
- def reservations(_page):
- self.assertIs(_page, page)
- reservation_calls.append(True)
- if reservation_hook:
- reservation_hook(plugin, page, len(reservation_calls))
- return (before if len(reservation_calls) == 1 else after) or preparation.ReservationSnapshot(0, 0)
- with ExitStack() as stack:
- factory = stack.enter_context(patch.object(gate, "ItaPlugin", return_value=plugin))
- stack.enter_context(patch.object(gate, "resolve_chrome_path", return_value=Path("/fixture/Chrome")))
- stack.enter_context(patch.object(preparation, "read_reservation_snapshot", side_effect=reservations))
- stack.enter_context(patch.object(preparation.CalendarRequestAudit, "settled_snapshot", lambda audit: audit.snapshot()))
- stack.enter_context(patch.object(calendar_book, "click_next_month", side_effect=lambda _page: page.next_month()))
- stack.enter_context(patch.object(calendar_book.time, "sleep"))
- stack.enter_context(patch.dict(gate.os.environ, {}, clear=True))
- stack.enter_context(redirect_stdout(captured))
- code = gate.run_book_gate(env or gate_env(), execute=execute, user_inputs=inputs,
- otp_reader=otp_reader or (lambda: OTP),
- use_local_query_account=use_local_query_account,
- verify_receipts=verify_receipts, submit_once=submit_once,
- final_confirm=final_confirm, review_reader=review_reader)
- output = captured.getvalue()
- lines = [line for line in output.splitlines() if line.startswith("ITA_BOOK_GATE_RESULT=")]
- report = json.loads(lines[-1].split("=", 1)[1]) if lines else None
- return SimpleNamespace(code=code, report=report, output=output, plugin=plugin,
- page=page, factory=factory, reservation_calls=reservation_calls)
- def assert_clean(self, result):
- result.plugin.cleanup.assert_called_once()
- self.assertFalse(result.page.listen.listening)
- self.assertNotIn(preparation.CalendarRequestAudit.EVENT, result.page.driver.immediate_event_handlers)
- self.assertFalse(result.page.auto_accept)
- self.assertEqual(result.page.guard_final_count, 0)
- def test_production_failures_are_distinct_and_diagnostic_precedes_reconciliation(self):
- cases = (
- ("Book date control was not ready before timeout", "date_control_timeout"),
- ("Book TimeSlots request does not match the current service", "timeslot_service_mismatch"),
- ("Book slot DOM did not match the response before timeout", "slot_dom_timeout"),
- ("Book precommit rejected (precommit_rejected)", "precommit_readback_rejected"),
- )
- for message, reason in cases:
- with self.subTest(reason=reason):
- page = GatePage()
- seen = []
- original = page.run_js
- def read(script, *args):
- if script == gate.BOOK_FAILURE_STATE_SCRIPT:
- seen.append(True)
- return book_failure_state()
- return original(script, *args)
- def reconcile(plugin, page, count):
- if count == 2:
- self.assertEqual(seen, [True])
- page.run_js = read
- with patch.object(calendar_book, "_try_day", side_effect=calendar_book.CalendarBookError(message)):
- result = self.run_gate(page, reservation_hook=reconcile)
- self.assertEqual(result.code, 1, result.output)
- self.assertIn(f'"reason": "{reason}"', result.output)
- self.assertIn('"readSucceeded": true', result.output)
- self.assertEqual(result.report["calendarBookCalls"], 1)
- self.assertEqual(result.report["requests"]["finalRequests"], 0)
- self.assertEqual(result.report["requests"]["otpRequests"], 1)
- self.assertEqual(result.report["requests"]["avantiPosts"], 1)
- self.assertEqual(page.clicks, 0)
- self.assert_clean(result)
- def test_production_diagnostic_failure_does_not_replace_original_reason(self):
- # GatePage deliberately has no implementation of this diagnostic script.
- with patch.object(calendar_book, "_try_day", side_effect=calendar_book.CalendarBookError(
- "Book slot click was not acknowledged",
- )):
- result = self.run_gate()
- self.assertEqual(result.code, 1)
- self.assertIn('"reason": "slot_click_not_acknowledged"', result.output)
- self.assertIn('"readSucceeded": false', result.output)
- self.assert_clean(result)
- def test_full_gate_uses_real_book_and_stops_before_final(self):
- result = self.run_gate()
- self.assertEqual(result.code, 0, result.output)
- report = result.report
- self.assertIs(report["passed"], True)
- self.assertEqual(report["outcome"], "pre_final")
- self.assertEqual((report["entryBookCalls"], report["calendarBookCalls"]), (1, 1))
- self.assertEqual(report["requests"], {"otpRequests": 1, "avantiPosts": 1,
- "availabilityRequests": 2, "finalRequests": 0})
- self.assertEqual(report["bookRequestDelta"], {"otpRequests": 0, "avantiPosts": 0,
- "availabilityRequests": 1, "finalRequests": 0})
- self.assertEqual(report["selectedDate"], "2026-10-13")
- self.assertEqual(report["selectedTime"], "10:05 - 11:05")
- self.assertIs(report["bookResultSuccess"], False)
- self.assertEqual(result.plugin.book.call_count, 2)
- result.plugin._enter_service.assert_called_once()
- result.plugin.query.assert_not_called()
- self.assertEqual(result.page.clicks, 1)
- self.assertEqual(result.page.otp_value, OTP)
- self.assertEqual(result.page.alert_settings, [True, False])
- self.assertEqual(result.plugin._prepared_calendar.role, "book")
- self.assertEqual(result.plugin._record_calendar_prepared_route.call_count, 1)
- self.assertEqual(len(result.reservation_calls), 2)
- self.assert_clean(result)
- for secret in (USERNAME, PASSWORD, OTP, "80000113"):
- self.assertNotIn(secret, result.output)
- def test_receipt_baseline_mode_is_retired_before_browser_creation(self):
- with patch.object(gate, "_book_credentials") as credentials:
- result = self.run_gate(execute=False, verify_receipts=True)
- self.assertEqual(result.code, 1)
- self.assertIn("Receipt-baseline mode is no longer", result.output)
- credentials.assert_not_called()
- result.factory.assert_not_called()
- def test_submit_once_preflight_is_local_and_needs_no_persistent_fence(self):
- with patch.object(gate, "_book_credentials") as credentials:
- result = self.run_gate(execute=False, submit_once=True)
- self.assertEqual(result.code, 0, result.output)
- credentials.assert_not_called()
- result.factory.assert_not_called()
- def test_submit_once_delegates_to_one_production_result(self):
- page = GatePage()
- class FinalRun:
- def __init__(self, plugin, route, **_kwargs):
- self.plugin, self.route = plugin, route
- self.possibly_submitted = False
- self.result = None
- self.report = {
- "attempted": False, "automaticRetry": True,
- "bookingConfirmed": False, "outcome": "not_submitted",
- }
- def execute(self, **_kwargs):
- self.possibly_submitted = True
- page.emit("/BookingCalendar/InsertNewBooking", "POST")
- self.result = VSBookResult(
- success=True, account=USERNAME, book_date="2026-10-13",
- book_time="10:05 - 11:05",
- )
- self.report.update(
- attempted=True, bookingConfirmed=True, outcome="confirmed",
- confirmedDate=self.result.book_date, confirmedTime=self.result.book_time,
- )
- return self.report
- with patch.object(gate.final_evidence, "FinalEvidenceRun", FinalRun):
- result = self.run_gate(
- page, submit_once=True,
- before=preparation.ReservationSnapshot(1, 0),
- after=preparation.ReservationSnapshot(1, 0),
- )
- self.assertEqual(result.code, 0, result.output)
- self.assertTrue(result.report["passed"])
- self.assertTrue(result.report["bookResultSuccess"])
- self.assertEqual(result.report["requests"]["finalRequests"], 1)
- self.assertTrue(result.report["finalEvidence"]["automaticRetry"])
- result.plugin.cleanup.assert_called_once()
- self.assertFalse(result.page.listen.listening)
- self.assertFalse(result.page.driver.immediate_event_handlers)
- self.assertEqual(result.page.guard_final_count, 1)
- def test_final_cli_flag_is_forwarded_without_receipt_requirement(self):
- with patch.object(gate, "run_book_gate", return_value=0) as runner:
- self.assertEqual(gate.main(["--preflight", "--submit-once"]), 0)
- self.assertIs(runner.call_args.kwargs["submit_once"], True)
- self.assertIs(runner.call_args.kwargs["verify_receipts"], False)
- self.assertIs(runner.call_args.kwargs["execute"], False)
- def test_followed_redirect_200_is_accepted(self):
- page = GatePage()
- page.avanti_status = 200
- result = self.run_gate(page)
- self.assertEqual(result.code, 0, result.output)
- self.assertIn("followed_redirect_200", result.output)
- self.assert_clean(result)
- def test_config_not_geography_controls_route(self):
- env = gate_env()
- env.update(ITA_ROUTING_KEY="slot.other.it.tourist", ITA_CITY="Another City", ITA_SERVICE_ID="9001")
- page = GatePage()
- page.service_id, page.booking_path = 9001, "/Services/Booking/9001"
- result = self.run_gate(page, env=env)
- self.assertEqual(result.code, 0, result.output)
- self.assertEqual(result.plugin._prepared_calendar.route.service_id, 9001)
- def test_default_preflight_does_not_load_credentials_or_create_browser(self):
- for reuse in (False, True):
- with self.subTest(reuse=reuse), patch.object(
- gate, "_book_credentials", side_effect=AssertionError("No credential access")
- ), patch.object(gate, "load_local_account") as loader:
- result = self.run_gate(execute=False, use_local_query_account=reuse)
- self.assertEqual(result.code, 0, result.output)
- loader.assert_not_called()
- result.factory.assert_not_called()
- result.plugin.create_session.assert_not_called()
- self.assertEqual(result.reservation_calls, [])
- def test_local_account_reuse_still_uses_independent_prefinal_book_flow(self):
- with patch.object(gate, "load_local_account", return_value=SimpleNamespace(
- username=USERNAME, password=PASSWORD,
- )) as loader, patch.object(gate, "_get_credentials") as prompt:
- result = self.run_gate(use_local_query_account=True)
- loader.assert_called_once_with(gate.ITA_QUERY_ACCOUNT_FILE)
- prompt.assert_not_called()
- self.assertEqual(result.code, 0, result.output)
- self.assertTrue(result.report["passed"])
- self.assertFalse(result.report["bookResultSuccess"])
- self.assertEqual(result.report["requests"]["finalRequests"], 0)
- self.assertEqual(result.plugin.config.account.username, USERNAME)
- self.assertEqual(result.plugin._prepared_calendar.role, "book")
- self.assertIsNone(result.plugin.free_config.get(gate.PERSISTENT_BROWSER_PROFILE_KEY))
- self.assertEqual(result.plugin.book.call_count, 2)
- self.assertIn("source=local_query_file", result.output)
- for secret in (USERNAME, PASSWORD, OTP):
- self.assertNotIn(secret, result.output)
- self.assert_clean(result)
- def test_invalid_local_account_stops_before_browser_without_fallback(self):
- with patch.object(gate, "load_local_account", side_effect=gate.LocalAccountConfigurationError(
- f"untrusted loader detail {USERNAME} {PASSWORD}",
- )), patch.object(gate, "_get_credentials") as prompt:
- result = self.run_gate(use_local_query_account=True)
- self.assertEqual(result.code, 1)
- self.assertFalse(result.report["passed"])
- result.factory.assert_not_called()
- result.plugin.create_session.assert_not_called()
- prompt.assert_not_called()
- self.assertEqual(result.page.otp_clicks, 0)
- self.assertEqual(result.page.avanti_clicks, 0)
- self.assertEqual(result.reservation_calls, [])
- self.assertIn("applicant_credentials", result.output)
- for secret in (USERNAME, PASSWORD, "untrusted loader detail"):
- self.assertNotIn(secret, result.output)
- def test_calendar_service_failure_retains_business_exit_and_safe_diagnostic(self):
- page = GatePage()
- page.context_count = 0
- result = self.run_gate(page)
- self.assertEqual(result.code, 1, result.output)
- self.assertFalse(result.report["passed"])
- self.assertEqual(result.report["calendarBookCalls"], 0)
- self.assertEqual(result.report["requests"], {
- "otpRequests": 1, "avantiPosts": 1, "availabilityRequests": 1, "finalRequests": 0,
- })
- diagnostic = json.loads(next(line.split("=", 1)[1] for line in result.output.splitlines()
- if line.startswith("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=")))
- self.assertEqual(diagnostic["controlCount"], 0)
- self.assertTrue(diagnostic["readSucceeded"])
- self.assertTrue(diagnostic["afterFailure"])
- self.assertIn('"reason": "calendar_service_unidentified"', result.output)
- self.assertNotIn("cleanup_listener", result.output)
- self.assertEqual(page.listen.stops, 2) # OTP and AVANTI; no third stop.
- self.assert_clean(result)
- def test_calendar_identifier_shapes_stay_rejected_without_logging_values(self):
- for value in ("", " ", "x" * 129, 7002, None):
- with self.subTest(value_type=type(value).__name__), patch.object(
- gate, "CALENDAR_READY_TIMEOUT_SECONDS", 0,
- ):
- page = GatePage()
- page.service = value
- result = self.run_gate(page)
- self.assertEqual(result.code, 1, result.output)
- self.assertEqual(result.report["calendarBookCalls"], 0)
- reason = "calendar_service_not_ready" if value == "" else "calendar_service_unidentified"
- self.assertIn(f'"reason": "{reason}"', result.output)
- diagnostic = json.loads(next(line.split("=", 1)[1] for line in result.output.splitlines()
- if line.startswith("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=")))
- self.assertEqual(diagnostic["valueType"], type(value).__name__)
- self.assertEqual(diagnostic["valueLength"], len(value) if isinstance(value, str) else None)
- self.assertFalse(diagnostic["valueAccepted"])
- self.assertNotIn("value", diagnostic)
- self.assertNotIn("x" * 129, result.output)
- self.assert_clean(result)
- def test_calendar_initialization_can_finish_after_document_loaded(self):
- page = GatePage()
- original_run_js = page.run_js
- reads = []
- def delayed(script, *args):
- result = original_run_js(script, *args)
- if script == calendar_book.RUNTIME_SERVICE_SCRIPT:
- reads.append(True)
- if len(reads) == 1:
- return {**result, "value": ""}
- return result
- page.run_js = delayed
- result = self.run_gate(page)
- self.assertEqual(result.code, 0, result.output)
- self.assertGreater(len(reads), 1)
- self.assertEqual(result.report["calendarBookCalls"], 1)
- self.assertEqual(result.report["requests"]["otpRequests"], 1)
- self.assertEqual(result.report["requests"]["avantiPosts"], 1)
- self.assertEqual(result.report["requests"]["finalRequests"], 0)
- self.assert_clean(result)
- def test_diagnostic_read_failure_does_not_replace_the_primary_error(self):
- page = GatePage()
- original_run_js = page.run_js
- def run_js(script, *args):
- if script == calendar_book.RUNTIME_SERVICE_SCRIPT:
- raise RuntimeError(f"{USERNAME} {PASSWORD} private-response")
- return original_run_js(script, *args)
- page.run_js = run_js
- result = self.run_gate(page)
- self.assertEqual(result.code, 1, result.output)
- self.assertIn('"readSucceeded": false', result.output)
- self.assertIn('"reason": "calendar_service_unidentified"', result.output)
- for secret in (USERNAME, PASSWORD, "private-response"):
- self.assertNotIn(secret, result.output)
- self.assert_clean(result)
- def test_active_listener_cleanup_failure_is_not_silenced(self):
- def reservation_hook(plugin, page, count):
- if count == 2:
- page.listen.listening = True
- page.listen.stop = Mock(side_effect=AttributeError("active listener failed"))
- result = self.run_gate(reservation_hook=reservation_hook)
- self.assertEqual(result.code, 3)
- self.assertFalse(result.report["passed"])
- self.assertIn("cleanup_listener", result.output)
- result.page.listen.stop.assert_called_once()
- result.plugin.cleanup.assert_called_once()
- self.assertNotIn(preparation.CalendarRequestAudit.EVENT,
- result.page.driver.immediate_event_handlers)
- self.assertEqual(result.page.guard_final_count, 0)
- def test_no_route_fallback_is_allowed(self):
- for name in prep_fixtures.gate_env():
- with self.subTest(missing=name):
- env = gate_env()
- del env[name]
- result = self.run_gate(env=env)
- self.assertEqual(result.code, 1)
- result.factory.assert_not_called()
- def test_bad_preferences_fail_before_credentials(self):
- for inputs in ({"expected_start_date": "20260230"}, {"username": "query@example.test"},
- {"expected_start_date": "2026-11-01", "expected_end_date": "2026-10-01"}):
- with self.subTest(inputs=inputs), patch.object(gate, "_book_credentials") as credentials:
- result = self.run_gate(inputs=inputs)
- self.assertEqual(result.code, 1)
- credentials.assert_not_called()
- result.factory.assert_not_called()
- def test_preferences_reach_real_book_without_changing_input(self):
- page = GatePage([flow_fixtures.month("2026-10", {13: 1, 14: 1})])
- inputs = {"expected_start_date": "2026-10-14", "expected_end_date": "2026-10-14"}
- original = copy.deepcopy(inputs)
- result = self.run_gate(page, inputs=inputs)
- self.assertEqual(result.code, 0, result.output)
- self.assertEqual(result.report["selectedDate"], "2026-10-14")
- self.assertEqual(page.date_clicks, ["2026-10-14"])
- self.assertEqual(inputs, original)
- def test_entry_unavailable_does_not_send_otp(self):
- def configure(plugin, page):
- plugin._enter_service = Mock(return_value=VSQueryResult(success=False))
- result = self.run_gate(configure=configure)
- self.assertEqual(result.code, 2, result.output)
- self.assertFalse(result.report["passed"])
- self.assertEqual(result.report["calendarBookCalls"], 0)
- self.assertEqual(result.page.otp_clicks, 0)
- self.assert_clean(result)
- def test_calendar_no_inventory_is_not_a_positive_gate(self):
- page = GatePage([flow_fixtures.month("2026-10", {13: 0})])
- result = self.run_gate(page, inputs={"expected_end_date": "2026-10-31"})
- self.assertEqual(result.code, 2, result.output)
- self.assertFalse(result.report["selectionVerified"])
- self.assertFalse(result.report["passed"])
- self.assertEqual(page.clicks, 0)
- self.assert_clean(result)
- def test_form_preflight_failure_does_not_send_otp(self):
- page = GatePage()
- page.preflight_changes = {"formReady": False}
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- self.assertEqual(page.otp_clicks, 0)
- self.assert_clean(result)
- def test_otp_must_really_be_written_before_avanti(self):
- page = GatePage()
- page.otp_write_matches = False
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- self.assertEqual((page.otp_clicks, page.avanti_clicks), (1, 0))
- self.assert_clean(result)
- def test_bad_manual_code_never_retries_or_reaches_avanti(self):
- for value in ("", "123456", "123 abc", None):
- with self.subTest(value=value):
- result = self.run_gate(otp_reader=lambda: value)
- self.assertEqual(result.code, 1)
- self.assertEqual((result.page.otp_clicks, result.page.avanti_clicks), (1, 0))
- self.assert_clean(result)
- def test_cancel_at_manual_otp_reconciles_and_cleans_without_retry(self):
- reader = Mock(side_effect=KeyboardInterrupt)
- result = self.run_gate(otp_reader=reader)
- self.assertEqual(result.code, 130)
- self.assertEqual((result.page.otp_clicks, result.page.avanti_clicks), (1, 0))
- self.assertEqual(len(result.reservation_calls), 2)
- self.assert_clean(result)
- def test_eof_at_manual_otp_is_safe_cancellation(self):
- result = self.run_gate(otp_reader=Mock(side_effect=EOFError))
- self.assertEqual(result.code, 130)
- self.assert_clean(result)
- def test_duplicate_otp_is_detected_before_reading_code(self):
- page = GatePage()
- page.duplicate_otp = True
- reader = Mock(return_value=OTP)
- result = self.run_gate(page, otp_reader=reader)
- self.assertEqual(result.code, 1)
- reader.assert_not_called()
- self.assertEqual(page.avanti_clicks, 0)
- self.assertEqual(result.report["requests"]["otpRequests"], 2)
- self.assert_clean(result)
- def test_duplicate_avanti_never_records_prepared_context(self):
- page = GatePage()
- page.duplicate_avanti = True
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- result.plugin._record_calendar_prepared_route.assert_not_called()
- self.assertEqual(page.refreshes, 0)
- self.assert_clean(result)
- def test_preparation_packets_are_bound_to_tab_service_and_response(self):
- changes = (
- lambda packet: setattr(packet, "tab_id", "old-query-tab"),
- lambda packet: setattr(packet, "is_failed", True),
- lambda packet: setattr(packet.response, "status", True),
- lambda packet: setattr(packet, "url", ORIGIN + preparation.OTP_PATH + "?ServiceID=9001"),
- lambda packet: setattr(packet.response, "raw_body", json.dumps("NOT_SENT")),
- )
- for index, mutate in enumerate(changes):
- with self.subTest(index=index):
- page = GatePage()
- page.preparation_mutator = lambda packet, selector: mutate(packet) if selector == "#otp-send" else None
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- self.assertEqual(page.avanti_clicks, 0)
- self.assert_clean(result)
- def test_avanti_wrong_tab_or_transition_does_not_attest_calendar(self):
- for variant in ("wrong-tab", "wrong-target", "bad-status", "response-form"):
- with self.subTest(variant=variant):
- page = GatePage()
- def mutate(packet, selector):
- if selector != "#btnAvanti":
- return
- if variant == "wrong-tab":
- packet.tab_id = "another-tab"
- elif variant == "wrong-target":
- packet.response.headers["Location"] = "https://other.example/BookingCalendar"
- elif variant == "bad-status":
- packet.response.status = 500
- else:
- packet.response.status = 200
- packet.response.url = ORIGIN + page.booking_path
- page.preparation_mutator = mutate
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- result.plugin._record_calendar_prepared_route.assert_not_called()
- self.assertEqual(page.refreshes, 0)
- self.assert_clean(result)
- def test_avanti_timeout_does_not_repeat_and_disables_auto_accept(self):
- with patch.object(preparation, "_wait_for_calendar", side_effect=preparation.CalendarGateError("timeout")):
- result = self.run_gate()
- self.assertEqual(result.code, 1)
- self.assertEqual(result.page.avanti_clicks, 1)
- self.assertEqual(result.page.alert_settings, [True, False])
- self.assert_clean(result)
- def test_account_route_tab_and_login_drift_stop_before_otp(self):
- mutations = (
- lambda plugin, page: setattr(plugin.config.account, "username", "other@example.test"),
- lambda plugin, page: setattr(page, "tab_id", "other-tab"),
- lambda plugin, page: setattr(plugin, "session_create_time", 124.0),
- lambda plugin, page: plugin.free_config.update(final_submit_enabled=True),
- lambda plugin, page: setattr(plugin, "_prepared_calendar", SimpleNamespace(role="query")),
- lambda plugin, page: plugin.free_config["apt_configs"]["slot.hkg.it.tourist"].update(service_id=9001),
- )
- for index, mutate in enumerate(mutations):
- with self.subTest(index=index):
- def configure(plugin, page):
- page.preflight_hook = lambda: mutate(plugin, page)
- result = self.run_gate(configure=configure)
- self.assertEqual(result.code, 1)
- self.assertEqual(result.page.otp_clicks, 0)
- self.assert_clean(result)
- def test_account_change_while_reading_otp_does_not_write_code(self):
- state = {}
- def configure(plugin, page):
- state["plugin"] = plugin
- def reader():
- state["plugin"].config.account.username = "another@example.test"
- return OTP
- result = self.run_gate(configure=configure, otp_reader=reader)
- self.assertEqual(result.code, 1)
- self.assertEqual(result.page.otp_value, "")
- self.assertEqual(result.page.avanti_clicks, 0)
- self.assert_clean(result)
- def test_existing_calendar_is_not_accepted_as_a_fresh_login(self):
- page = GatePage()
- page.url = ORIGIN + CALENDAR_PATH
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- result.plugin.book.assert_not_called()
- self.assertEqual(page.otp_clicks, 0)
- def test_unexpected_book_success_is_never_reported_as_gate_success(self):
- def configure(plugin, page):
- plugin.book = Mock(return_value=VSBookResult(success=True, urn="private-reservation"))
- result = self.run_gate(configure=configure)
- self.assertEqual(result.code, 1)
- self.assertEqual(result.page.otp_clicks, 0)
- self.assertNotIn("private-reservation", result.output)
- self.assert_clean(result)
- def test_lost_selection_after_book_is_not_clicked_again(self):
- def configure(plugin, page):
- original = plugin.book
- def call(*args, **kwargs):
- result = original(*args, **kwargs)
- if page.url.endswith(CALENDAR_PATH):
- page.active = False
- return result
- plugin.book = Mock(side_effect=call)
- result = self.run_gate(configure=configure)
- self.assertEqual(result.code, 1)
- self.assertEqual(result.page.clicks, 1)
- self.assert_clean(result)
- def test_otp_during_book_fails_audit_without_repeating_preparation(self):
- page = GatePage()
- original = page.refresh
- def refresh():
- original()
- page.emit(preparation.OTP_PATH, "GET")
- page.refresh = refresh
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- self.assertEqual((page.otp_clicks, page.avanti_clicks), (1, 1))
- self.assertFalse(result.report["passed"])
- self.assert_clean(result)
- def test_final_request_after_avanti_is_detected_before_book(self):
- page = GatePage()
- page.preparation_mutator = lambda packet, selector: (
- page.emit("/BookingCalendar/InsertNewBooking") if selector == "#btnAvanti" else None
- )
- result = self.run_gate(page)
- self.assertEqual(result.code, 1)
- result.plugin._record_calendar_prepared_route.assert_not_called()
- self.assertEqual(page.refreshes, 0)
- self.assertEqual(result.report["requests"]["finalRequests"], 1)
- self.assertFalse(page.auto_accept)
- def test_reservation_change_prevents_positive_gate(self):
- result = self.run_gate(after=preparation.ReservationSnapshot(1, 0))
- self.assertEqual(result.code, 1)
- self.assertFalse(result.report["passed"])
- self.assert_clean(result)
- def test_waitlist_change_prevents_positive_gate(self):
- result = self.run_gate(after=preparation.ReservationSnapshot(0, 1))
- self.assertEqual(result.code, 1)
- self.assertFalse(result.report["passed"])
- def test_late_business_request_during_reconciliation_is_detected(self):
- def hook(plugin, page, count):
- if count == 2:
- page.emit(AVAILABILITY_PATH)
- result = self.run_gate(reservation_hook=hook)
- self.assertEqual(result.code, 1)
- self.assertFalse(result.report["passed"])
- self.assert_clean(result)
- def test_failed_read_only_reconciliation_does_not_publish_passed(self):
- def hook(plugin, page, count):
- if count == 2:
- raise RuntimeError("private-state")
- result = self.run_gate(reservation_hook=hook)
- self.assertEqual(result.code, 1)
- self.assertNotIn("private-state", result.output)
- self.assert_clean(result)
- def test_cleanup_failure_has_distinct_return_code(self):
- def configure(plugin, page):
- plugin.cleanup.side_effect = RuntimeError("private browser details")
- result = self.run_gate(configure=configure)
- self.assertEqual(result.code, 3)
- self.assertFalse(result.report["passed"])
- self.assertNotIn("private browser details", result.output)
- def test_provider_exception_does_not_log_credentials_code_or_body(self):
- def configure(plugin, page):
- plugin.create_session.side_effect = RuntimeError(f"{USERNAME} {PASSWORD} {OTP} BODY private")
- result = self.run_gate(configure=configure)
- self.assertEqual(result.code, 1)
- for secret in (USERNAME, PASSWORD, OTP, "BODY private"):
- self.assertNotIn(secret, result.output)
- result.plugin.cleanup.assert_called_once()
- class BookGateInputTests(unittest.TestCase):
- def test_cleanup_avoids_installed_sdk_duplicate_stop_failure(self):
- from DrissionPage._units.listener import Listener
- listener = Listener.__new__(Listener)
- listener.listening = False
- driver = listener._driver = Mock()
- listener.stop()
- driver.stop.assert_called_once()
- self.assertIsNone(listener._driver)
- # Prove the actual SDK failure, then exercise our guarded cleanup.
- with self.assertRaises(AttributeError):
- listener.stop()
- gate._stop_listener_if_active(SimpleNamespace(listen=listener))
- driver.stop.assert_called_once()
- def test_cleanup_stops_an_active_listener(self):
- listener = SimpleNamespace(listening=True, stop=Mock())
- gate._stop_listener_if_active(SimpleNamespace(listen=listener))
- listener.stop.assert_called_once()
- def test_diagnostic_only_reads_the_calendar_and_never_emits_service_value(self):
- for path in ("/BookingCalendar", "/Services"):
- with self.subTest(path=path):
- page = SimpleNamespace(url=ORIGIN + path, run_js=Mock(return_value={
- "path": path, "count": 1, "value": PASSWORD,
- }))
- captured = StringIO()
- with redirect_stdout(captured):
- gate._print_calendar_preparation_diagnostic(page)
- self.assertNotIn(PASSWORD, captured.getvalue())
- diagnostic = json.loads(captured.getvalue().split("=", 1)[1])
- if path == "/BookingCalendar":
- self.assertEqual(diagnostic["valueLength"], len(PASSWORD))
- page.run_js.assert_called_once_with(calendar_book.RUNTIME_SERVICE_SCRIPT)
- else:
- self.assertFalse(diagnostic["pathMatches"])
- page.run_js.assert_not_called()
- def test_preparation_reasons_only_allow_exact_known_messages(self):
- for message, reason in (*gate._PREPARATION_FAILURES.items(), (PASSWORD, None)):
- with self.subTest(reason=reason):
- captured = StringIO()
- with redirect_stdout(captured):
- gate._failure("calendar_preparation", gate.BizLogicError(message))
- failure = json.loads(captured.getvalue().split("=", 1)[1])
- self.assertEqual(failure.get("reason"), reason)
- self.assertNotIn(PASSWORD, captured.getvalue())
- def test_credentials_project_only_book_fields(self):
- env = {"ITA_USERNAME": "query@example.test", "ITA_PASSWORD": "query-secret",
- "ITA_BOOK_USERNAME": USERNAME, "ITA_BOOK_PASSWORD": PASSWORD}
- with patch.object(gate, "_get_credentials", return_value=(USERNAME, PASSWORD)) as helper, \
- patch.object(gate, "load_local_account") as loader, redirect_stdout(StringIO()):
- self.assertEqual(gate._book_credentials(env), (USERNAME, PASSWORD))
- helper.assert_called_once_with({"ITA_USERNAME": USERNAME, "ITA_PASSWORD": PASSWORD}, non_interactive=False)
- loader.assert_not_called()
- def test_query_credentials_do_not_supply_fallback(self):
- with patch.object(gate, "_get_credentials", return_value=(USERNAME, PASSWORD)) as helper, \
- patch.object(gate, "load_local_account") as loader, redirect_stdout(StringIO()):
- gate._book_credentials({"ITA_USERNAME": "query@example.test", "ITA_PASSWORD": "query-secret"})
- helper.assert_called_once_with({"ITA_USERNAME": "", "ITA_PASSWORD": ""}, non_interactive=False)
- loader.assert_not_called()
- def test_local_account_opt_in_uses_complete_saved_pair_and_never_prompts(self):
- env = {"ITA_BOOK_USERNAME": "other@example.test", "ITA_BOOK_PASSWORD": "other-pass",
- "ITA_USERNAME": "general@example.test", "ITA_PASSWORD": "general-pass"}
- captured = StringIO()
- with patch.object(gate, "load_local_account", return_value=SimpleNamespace(
- username=USERNAME, password=PASSWORD,
- )) as loader, patch.object(gate, "_get_credentials") as prompt, redirect_stdout(captured):
- self.assertEqual(
- gate._book_credentials(env, use_local_query_account=True), (USERNAME, PASSWORD),
- )
- loader.assert_called_once_with(gate.ITA_QUERY_ACCOUNT_FILE)
- prompt.assert_not_called()
- self.assertIn("source=local_query_file", captured.getvalue())
- for secret in (USERNAME, PASSWORD, *env.values()):
- self.assertNotIn(secret, captured.getvalue())
- def test_local_loader_errors_are_safe_and_never_switch_credentials(self):
- for reason in ("missing file", "unsafe permissions", "invalid JSON", "missing password"):
- with self.subTest(reason=reason), patch.object(
- gate, "load_local_account",
- side_effect=gate.LocalAccountConfigurationError(f"{reason} {PASSWORD}"),
- ), patch.object(gate, "_get_credentials") as prompt:
- with self.assertRaises(gate.BookGateError) as caught:
- gate._book_credentials(gate_env(), use_local_query_account=True)
- prompt.assert_not_called()
- self.assertNotIn(PASSWORD, str(caught.exception))
- self.assertIn("config/ita_query_account.local.json", str(caught.exception))
- def test_local_secrets_are_not_part_of_source_fingerprint(self):
- self.assertNotIn(gate.ITA_QUERY_ACCOUNT_FILE, gate.BOOK_GATE_SOURCE_PATHS)
- self.assertIn(gate.REPO_ROOT / "utils" / "local_account.py", gate.BOOK_GATE_SOURCE_PATHS)
- def test_cli_defaults_to_no_external_actions(self):
- with patch.object(gate, "run_book_gate", return_value=0) as runner:
- self.assertEqual(gate.main([]), 0)
- self.assertIs(runner.call_args.kwargs["execute"], False)
- self.assertIs(runner.call_args.kwargs["use_local_query_account"], False)
- def test_cli_forwards_explicit_local_account_selection(self):
- for mode, execute in (("--preflight", False), ("--run", True)):
- with self.subTest(mode=mode), patch.object(gate, "run_book_gate", return_value=0) as runner:
- self.assertEqual(gate.main(["--use-local-query-account", mode]), 0)
- self.assertIs(runner.call_args.kwargs["execute"], execute)
- self.assertIs(runner.call_args.kwargs["use_local_query_account"], True)
- def test_cli_maps_vfs_preferences_to_real_inputs(self):
- with patch.object(gate, "run_book_gate", return_value=0) as runner:
- gate.main(["--run", "--expected-start-date", "2026-10-01", "--expected-end-date", "2026-12-31"])
- self.assertIs(runner.call_args.kwargs["execute"], True)
- self.assertEqual(runner.call_args.kwargs["user_inputs"],
- {"expected_start_date": "2026-10-01", "expected_end_date": "2026-12-31"})
- def test_audit_rejects_non_integer_counts(self):
- audit = Mock()
- for value in (True, -1, "0", None):
- audit.settled_snapshot.return_value = {
- "otpRequests": value, "avantiPosts": 0, "availabilityRequests": 0, "finalRequests": 0,
- }
- with self.subTest(value=value), self.assertRaises(gate.BookGateError):
- gate._counts(audit)
- def test_no_query_session_loader_or_profile_setup_or_final_click_in_tool(self):
- source = Path(gate.__file__).read_text()
- # Only the explicitly read-only diagnostic may mention the final button.
- self.assertEqual(source.count(gate.BOOK_FAILURE_STATE_SCRIPT), 1)
- source = source.replace(gate.BOOK_FAILURE_STATE_SCRIPT, "")
- for forbidden in ("_get_query_credentials(", "_prepare_query_profile(", "prepare_ita_query_profile(",
- "#btnPrenotaNoOtp", "InsertNewBooking"):
- self.assertNotIn(forbidden, source)
- registrations = [node for node in ast.walk(ast.parse(source))
- if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
- and node.func.attr == "_record_calendar_prepared_route"]
- self.assertEqual(len(registrations), 1)
- self.assertEqual({kw.arg: ast.literal_eval(kw.value) for kw in registrations[0].keywords}, {"role": "book"})
- self.assertIn("preparation.OneShotAction", source)
- self.assertIn("plugin.book(trigger", source)
- def book_failure_state():
- result = {key: False for key in gate._BOOK_STATE_BOOLS}
- result.update({key: 0 for key in gate._BOOK_STATE_COUNTS})
- result.update(pathMatches=True, serviceValuePresent=True, serviceControlCount=1,
- finalButtonCount=1, finalGuarded=True, slotStates=[])
- return result
- class BookProductionDiagnosticTests(unittest.TestCase):
- def test_static_reason_messages_exist_in_the_current_producer_source(self):
- source = Path(calendar_book.__file__).read_text() + (gate.REPO_ROOT / "plugins/ita_plugin.py").read_text()
- for message in gate._PRODUCTION_BOOK_FAILURES:
- if message in {"Book precommit rejected (precommit_rejected)",
- "Book TimeSlots request fields changed"}:
- continue # Produced by the shared protocol/request formatters and covered by packet tests.
- with self.subTest(message=message):
- self.assertIn(message, source)
- def test_plugin_internal_failure_keeps_its_classification(self):
- output = StringIO()
- with redirect_stdout(output):
- gate._failure("production_book", gate.BizLogicError(
- "Italy Book Calendar failed before final confirmation",
- ))
- failure = json.loads(output.getvalue().split("=", 1)[1])
- self.assertEqual(failure["reason"], "calendar_internal_failure")
- def capture_state(self, raw):
- page = SimpleNamespace(url=ORIGIN + CALENDAR_PATH, run_js=Mock(return_value=raw))
- output = StringIO()
- with redirect_stdout(output):
- gate._print_production_book_diagnostic(page)
- page.run_js.assert_called_once_with(gate.BOOK_FAILURE_STATE_SCRIPT)
- return output.getvalue(), json.loads(output.getvalue().split("=", 1)[1])
- def test_all_allowlisted_failures_publish_only_the_fixed_reason(self):
- for message, reason in gate._PRODUCTION_BOOK_FAILURES.items():
- with self.subTest(reason=reason):
- output = StringIO()
- with redirect_stdout(output):
- gate._failure("production_book", gate.BizLogicError(message))
- result = json.loads(output.getvalue().split("=", 1)[1])
- self.assertEqual(result["reason"], reason)
- self.assertNotEqual(result["message"], message)
- def test_unknown_body_and_wrong_stage_or_exception_type_are_not_exposed(self):
- secret = f"Book slot DOM did not match the response before timeout {USERNAME} {PASSWORD} {OTP}"
- for stage, error in (("production_book", gate.BizLogicError(secret)),
- ("production_book", RuntimeError(secret)),
- ("calendar_preparation", gate.BizLogicError(secret))):
- with self.subTest(stage=stage, error_type=type(error).__name__):
- output = StringIO()
- with redirect_stdout(output):
- gate._failure(stage, error)
- for value in (USERNAME, PASSWORD, OTP):
- self.assertNotIn(value, output.getvalue())
- self.assertNotIn('"reason": "slot_dom_timeout"', output.getvalue())
- def test_protocol_messages_emit_a_category_without_echoing_dynamic_code(self):
- for label, expected in (("TimeSlots protocol", "timeslot_protocol_rejected"),
- ("Calendar protocol", "calendar_protocol_rejected"),
- ("precommit", "precommit_readback_rejected")):
- output = StringIO()
- with redirect_stdout(output):
- gate._failure("production_book", gate.BizLogicError(f"Book {label} rejected (synthetic_code)"))
- self.assertIn(f'"reason": "{expected}"', output.getvalue())
- self.assertNotIn("synthetic_code", output.getvalue())
- def test_valid_shape_is_reported_as_after_failure_not_original_error_state(self):
- state = book_failure_state()
- state["slotStates"] = [{**{key: False for key in gate._BOOK_SLOT_BOOLS}, "hiddenInputCount": 1}]
- state["slotCount"] = 1
- _, result = self.capture_state(state)
- self.assertTrue(result["afterFailure"])
- self.assertTrue(result["readSucceeded"])
- self.assertEqual(result["state"], state)
- def test_unexpected_fields_and_types_fail_closed_without_partial_values(self):
- bad = []
- state = book_failure_state()
- bad.append({**state, "serviceValue": PASSWORD})
- bad.append({**state, "serviceValuePresent": PASSWORD})
- bad.append({**state, "slotCount": PASSWORD})
- bad.append({**state, "slotCount": True})
- bad.append({**state, "slotStates": [{"body": PASSWORD}]})
- bad.append({**state, "slotStates": [{}] * 13})
- bad.append({**state, "timeSlotResourceEntries": -1})
- for raw in bad:
- with self.subTest(raw_keys=tuple(raw)):
- output, result = self.capture_state(raw)
- self.assertFalse(result["readSucceeded"])
- self.assertNotIn("state", result)
- self.assertNotIn(PASSWORD, output)
- def test_non_calendar_page_is_not_read(self):
- page = SimpleNamespace(url=ORIGIN + "/Reservation", run_js=Mock())
- output = StringIO()
- with redirect_stdout(output):
- gate._print_production_book_diagnostic(page)
- page.run_js.assert_not_called()
- self.assertIn('"readSucceeded": false', output.getvalue())
- @unittest.skipUnless(shutil.which("node"), "Node is required for the read-only JS fixture")
- def test_readonly_script_distinguishes_offscreen_and_obscured_slots(self):
- fixture = r"""
- const script = process.argv[1], mode = process.argv[2];
- let measured = [];
- const makeSlot = (index) => ({
- index,
- classList: {contains: value => index === 0 && value === 'notAvailableFascia'},
- querySelector: () => null,
- querySelectorAll: () => [{get value() {throw Error('must not read slot identity');}}],
- getBoundingClientRect: () => {
- measured.push(index);
- const left = index === 1 ? 1100 : 10;
- return {left, right:left+100, top:20, bottom:60, width:100, height:40};
- },
- contains: () => false,
- get innerText() {throw Error('must not read slot text');},
- click: () => {throw Error('must not click');},
- });
- const slots = Array.from({length:mode === 'many' ? 13 : 3}, (_, index) => makeSlot(index));
- const timelineLink = {dataset:{date:'2026-10-13'}};
- const document = {
- querySelector: selector => selector === '.selected' ? timelineLink : null,
- querySelectorAll: selector => {
- if (selector === '#idServizio') return [{value:'private-runtime-identifier'}];
- if (selector === '.events a.selected') return [timelineLink];
- if (selector === '.events-content li.selected') return [{dataset:{date:'2026-10-13'},querySelectorAll:()=>slots}];
- if (selector === '#btnPrenotaNoOtp') return [Object.freeze({disabled:true,dataset:{coordinateFinalGuard:'enabled'}})];
- if (selector === '.fascia.act') return [];
- throw Error('unexpected selector');
- },
- elementFromPoint: () => slots[0],
- };
- const window = {innerWidth:1000, innerHeight:800,
- getComputedStyle:()=>({display:'block',visibility:'visible',pointerEvents:'auto',opacity:'1'})};
- const location = {origin:'https://prenotami.esteri.it',pathname:'/BookingCalendar'};
- const performance = {getEntriesByType:()=>[
- {name:location.origin+'/BookingCalendar/RetrieveTimeSlots'},
- {name:'https://other.example.test/BookingCalendar/RetrieveTimeSlots'},
- {name:'not-a-url'},
- ]};
- const result = new Function('document','window','location','performance',script)(document,window,location,performance);
- console.log(JSON.stringify({result,measured}));
- """
- for mode in ("normal", "many"):
- with self.subTest(mode=mode):
- result = subprocess.run([shutil.which("node"), "-e", fixture, gate.BOOK_FAILURE_STATE_SCRIPT, mode],
- text=True, capture_output=True, timeout=10)
- self.assertEqual(result.returncode, 0, result.stderr)
- self.assertNotIn("private-runtime-identifier", result.stdout)
- raw = json.loads(result.stdout)["result"]
- self.assertTrue(raw["selectedDatesMatch"])
- self.assertTrue(raw["firstSelectedIsTimeline"])
- self.assertTrue(raw["finalGuarded"])
- self.assertEqual(raw["timeSlotResourceEntries"], 1)
- self.assertFalse(raw["slotStates"][1]["inViewport"])
- self.assertTrue(raw["slotStates"][1]["cssVisible"])
- self.assertTrue(raw["slotStates"][2]["inViewport"])
- self.assertFalse(raw["slotStates"][2]["centerHit"])
- self.assertEqual(len(raw["slotStates"]), 12 if mode == "many" else 3)
- self.assertEqual(raw["slotStatesTruncated"], mode == "many")
- _, accepted = self.capture_state(raw)
- self.assertTrue(accepted["readSucceeded"])
- class BookGateFormBoundaryScriptTests(unittest.TestCase):
- def test_valid_boundary_uses_original_preflight_and_native_hidden_sync(self):
- node = shutil.which("node")
- if node is None:
- self.fail("Node is required to validate the real preparation script")
- config = preparation.build_calendar_gate_config(gate_env(), username=USERNAME, password=PASSWORD)
- route = gate.resolve_route_config(config.free_config["apt_configs"], "slot.hkg.it.tourist")
- script = gate._guarded_preflight_script(route, "/Services/Booking/4937")
- harness = r"""
- const location = {origin: 'https://prenotami.esteri.it', pathname: '/Services/Booking/4937',
- href: 'https://prenotami.esteri.it/Services/Booking/4937'};
- const hidden = {value: '0'}, companions = {value: '1'}, purposeHidden = {value: '0'};
- const booking = {value: '0', options: [{value: '1', textContent: 'Single booking'}],
- dispatchEvent: () => { hidden.value = '1'; companions.value = '0'; }};
- const purpose = {value: '0', options: [{value: '42', textContent: 'Tourism'}], dispatchEvent: () => {}};
- const privacy = {checked: false, click() { this.checked = true; }};
- const form = {action: location.href, method: 'post', enctype: 'multipart/form-data', querySelectorAll: () => []};
- const ids = {typeofbookingddl: booking, ddls_0: purpose, PrivacyCheck: privacy,
- hiddenTipoPrenotazione: hidden, numAccSelected: companions, hiddenSelezionato_0: purposeHidden};
- const selectors = {'#bookingForm': [form], '#otp-input': [{value: ''}], '#otp-send': [{disabled: false}],
- '#btnAvanti': [{disabled: false}], 'input[name="cf-turnstile-response"]': [{value: 'fixture-only'}]};
- const document = {getElementById: (id) => ids[id], querySelector: () => form,
- querySelectorAll: (selector) => selectors[selector] || []};
- const output = new Function('document', 'location', 'window', SCRIPT)(document, location, {location});
- if (purposeHidden.value !== '0') throw Error('Must not write purpose hidden before native AVANTI');
- process.stdout.write(JSON.stringify(output));
- """.replace("SCRIPT", json.dumps(script))
- completed = subprocess.run([node, "-e", harness], capture_output=True, text=True, timeout=10)
- self.assertEqual(completed.returncode, 0, completed.stderr)
- preparation.validate_booking_preflight(json.loads(completed.stdout))
- def test_actual_script_checks_scope_before_reused_form_mutations(self):
- node = shutil.which("node")
- if node is None:
- self.fail("Node is required to validate the real preparation boundary script")
- config = preparation.build_calendar_gate_config(gate_env(), username=USERNAME, password=PASSWORD)
- route = gate.resolve_route_config(config.free_config["apt_configs"], "slot.hkg.it.tourist")
- script = gate._guarded_preflight_script(route, "/Services/Booking/4937")
- harness = r"""
- const script = SCRIPT;
- const scenarios = ['wrongOrigin', 'wrongPath', 'noForm', 'twoForms', 'getForm',
- 'wrongAction', 'queryAction', 'changedEnctype', 'upload'];
- for (const scenario of scenarios) {
- let mutationReads = 0;
- const location = {origin: 'https://prenotami.esteri.it', pathname: '/Services/Booking/4937',
- href: 'https://prenotami.esteri.it/Services/Booking/4937'};
- const form = {method: 'post', enctype: 'multipart/form-data', action: location.href,
- querySelectorAll: () => scenario === 'upload' ? [{}] : []};
- if (scenario === 'wrongOrigin') location.origin = 'https://other.example';
- if (scenario === 'wrongPath') location.pathname = '/BookingCalendar';
- if (scenario === 'getForm') form.method = 'get';
- if (scenario === 'wrongAction') form.action = 'https://other.example/Services/Booking/4937';
- if (scenario === 'queryAction') form.action += '?changed=1';
- if (scenario === 'changedEnctype') form.enctype = 'text/plain';
- const document = {
- querySelectorAll: () => scenario === 'noForm' ? [] : scenario === 'twoForms' ? [form, form] : [form],
- querySelector: () => { mutationReads++; throw Error('Must stop before preflight'); }
- };
- const result = new Function('document', 'location', script)(document, location);
- if (result.formReady !== false || mutationReads !== 0) throw Error(scenario);
- }
- process.stdout.write('FORM_BOUNDARY_OK');
- """.replace("SCRIPT", json.dumps(script))
- completed = subprocess.run([node, "-e", harness], capture_output=True, text=True, timeout=10)
- self.assertEqual(completed.returncode, 0, completed.stderr)
- self.assertEqual(completed.stdout, "FORM_BOUNDARY_OK")
- if __name__ == "__main__":
- unittest.main()
|