import ast import json import shutil import subprocess import traceback import unittest from datetime import date, datetime from pathlib import Path from types import SimpleNamespace from unittest.mock import patch from plugins import ita_plugin as book_calendar from plugins.ita_plugin import ( RUNTIME_SERVICE_SCRIPT, SLOT_SELECTION_SCRIPT, TIME_SLOTS_PATH, CalendarBookError, parse_book_time_slots, select_slot_before_final, ) from plugins.ita_plugin import AVAILABILITY_PATH, CALENDAR_GUARD_SCRIPT from test.ita.test_ita_protocol import availability_item, double_json, slot_item DAY = date(2026, 10, 13) SERVICE = "7002" DAILY_ID = 80001001 def packet(path, body, items): return SimpleNamespace( url="https://prenotami.esteri.it" + path, method="POST", request=SimpleNamespace(postData=body), response=SimpleNamespace(status=200, raw_body=double_json(items)), ) def packets(*, free=1, remaining=0): availability = packet( AVAILABILITY_PATH, {"_Servizio": "month-runtime-key", "selectedDay": "01/10/2026"}, [availability_item("13/10/2026 00:00:00", free, remaining)], ) times = packet( TIME_SLOTS_PATH, {"selectedDay": DAY.isoformat(), "idService": SERVICE}, [slot_item("13/10/2026 00:00:00", (10, 5), (11, 5), free, remaining, DAILY_ID)], ) return availability, times class FakePage: def __init__(self): self.url = "https://prenotami.esteri.it/BookingCalendar" self.service = SERVICE self.context_count = 1 self.active = False self.events = [] self.overrides = {} self.after_overrides = {} self.click_ack = True self.browser_error = None self.guard_final_count = 0 self.last_candidate = None @property def clicks(self): return self.events.count("slot-click") def run_js(self, script, *args): if self.browser_error: raise RuntimeError(self.browser_error) if script == RUNTIME_SERVICE_SCRIPT: return {"path": "/BookingCalendar", "count": self.context_count, "value": self.service} if script == CALENDAR_GUARD_SCRIPT: self.events.append("guard") return { "path": "/BookingCalendar", "calendarFunctionPresent": True, "finalButtonCount": 1, "allFinalButtonsGuarded": True, "finalRequestCount": self.guard_final_count, } if script != SLOT_SELECTION_SCRIPT: raise AssertionError("Unknown browser action") service, day, daily_id, label, capacity, click = args self.last_candidate = (daily_id, label, capacity) if click and self.click_ack: self.events.append("slot-click") self.active = True raw = { "contextReady": service == self.service, "candidateCount": 1, "candidateReady": True, "selected": self.active, "clicked": click and self.click_ack, } raw.update(self.overrides) if self.clicks: raw.update(self.after_overrides) return raw def select(page, pair=None): availability, times = pair or packets() service = SERVICE # The caller's service binding at inventory capture time. return select_slot_before_final( page, target_day=DAY, runtime_service=service, probe=book_calendar.parse_availability_packet(availability), slots=book_calendar.parse_book_time_slots(times, target_day=DAY, runtime_service_id=service), ) class PrecommitReadbackTests(unittest.TestCase): """Migrate the old pure-state checks to the actual read-only browser boundary.""" def setUp(self): self.page = FakePage() self.page.active = True self.day = book_calendar.parse_calendar_availability( double_json([availability_item("09/10/2026 00:00:00", 1, 0)]) )[0] self.negative_candidate, self.candidate = book_calendar.parse_time_slots(double_json([ slot_item("09/10/2026 00:00:00", (9, 15), (10, 0), 0, -1, 301), slot_item("09/10/2026 00:00:00", (10, 5), (11, 5), 1, 0, 302), ])) def readback(self, *, calendar_day=None, candidate=None): approval = book_calendar.PrecommitApproval(calendar_day or self.day, candidate or self.candidate) return book_calendar.verify_precommit_selection( self.page, runtime_service=SERVICE, approval=approval, ) def reject(self, **kwargs): with self.assertRaises(CalendarBookError): self.readback(**kwargs) self.assertEqual(self.page.clicks, 0) def test_e44_positive_selection_approves_precommit(self): approval = self.readback() self.assertIs(approval.calendar_day, self.day) self.assertIs(approval.candidate, self.candidate) self.assertNotIn(self.candidate.daily_calendar_id, repr(approval)) self.assertEqual(self.page.clicks, 0) def test_readback_rejects_wrong_types_and_extra_fields(self): for mutation in ( {"candidateCount": True}, {"candidateCount": 1.0}, {"contextReady": 1}, {"candidateReady": 1}, {"selected": 1}, {"clicked": 0}, {"extra": "unexpected"}, ): with self.subTest(mutation=mutation): self.page.overrides = mutation self.reject() def test_rejects_every_unsafe_control_semantic(self): for mutation in ( {"contextReady": False}, {"candidateCount": 0}, {"candidateCount": 2}, {"candidateReady": False}, {"selected": False}, {"clicked": True}, ): with self.subTest(mutation=mutation): self.page.overrides = mutation self.reject() def test_rejects_negative_candidate_even_if_dom_marks_it_active(self): self.reject(candidate=self.negative_candidate) def test_rejects_negative_calendar_day(self): negative = book_calendar.parse_calendar_availability( double_json([availability_item("09/10/2026 00:00:00", 0, -1)]) )[0] self.reject(calendar_day=negative) def test_calendar_and_slot_must_belong_to_the_same_day(self): other = book_calendar.parse_calendar_availability( double_json([availability_item("10/10/2026 00:00:00", 1, 0)]) )[0] self.reject(calendar_day=other) class CalendarServiceReadinessTests(unittest.TestCase): def setUp(self): self.page = FakePage() self.page.tab_id = "book-tab" self.now = 0.0 self.sleeps = [] self.sleep_hook = None self.enterContext(patch.object(book_calendar.time, "monotonic", side_effect=lambda: self.now)) self.enterContext(patch.object(book_calendar.time, "sleep", side_effect=self.advance)) def advance(self, seconds): self.sleeps.append(seconds) self.now += seconds if self.sleep_hook: self.sleep_hook() def wait(self, **kwargs): options = {"session_is_current": lambda: True, "timeout": 0.25} options.update(kwargs) return book_calendar.wait_for_calendar_service(self.page, **options) def test_ready_returns_immediately_without_network_or_clicks(self): self.assertEqual(self.wait(), SERVICE) self.assertEqual(self.sleeps, []) self.assertEqual(self.page.events, ["guard"]) def test_empty_then_ready_uses_actual_value_without_full_delay(self): self.page.service = "" self.sleep_hook = lambda: setattr(self.page, "service", "synthetic-runtime-key") self.assertEqual(self.wait(), "synthetic-runtime-key") self.assertEqual(self.sleeps, [0.1]) self.assertEqual(self.page.clicks, 0) def test_empty_timeout_is_bounded_and_does_not_supply_a_default_id(self): self.page.service = "" with self.assertRaises(book_calendar.CalendarServiceNotReadyError): self.wait() self.assertAlmostEqual(sum(self.sleeps), 0.25) self.assertEqual(self.page.service, "") self.assertEqual(self.page.clicks, 0) def test_stable_phase_strict_read_does_not_wait(self): self.page.service = "" with self.assertRaises(CalendarBookError): book_calendar.read_calendar_service(self.page) self.assertEqual(self.sleeps, []) def test_zero_budget_accepts_ready_but_rejects_empty_without_sleep(self): self.assertEqual(self.wait(timeout=0), SERVICE) self.page.service = "" with self.assertRaises(book_calendar.CalendarServiceNotReadyError): self.wait(timeout=0) self.assertEqual(self.sleeps, []) def test_invalid_structure_or_value_is_not_treated_as_pending(self): for attribute, value in (("context_count", 0), ("context_count", 2), ("context_count", True), ("service", None), ("service", 4937), ("service", " "), ("service", "x" * 129)): with self.subTest(attribute=attribute, value_type=type(value).__name__): original = getattr(self.page, attribute) setattr(self.page, attribute, value) with self.assertRaises(CalendarBookError) as caught: self.wait() self.assertNotIsInstance(caught.exception, book_calendar.CalendarServiceNotReadyError) self.assertEqual(self.sleeps, []) setattr(self.page, attribute, original) def test_service_change_after_refresh_is_not_accepted(self): self.page.service = "" self.sleep_hook = lambda: setattr(self.page, "service", "other-service") with self.assertRaisesRegex(CalendarBookError, "runtime service changed"): self.wait(expected_service=SERVICE) def test_tab_or_path_drift_during_wait_stops(self): for attribute, value in (("tab_id", "other-tab"), ("url", "https://prenotami.esteri.it/UserArea")): with self.subTest(attribute=attribute): original = getattr(self.page, attribute) self.page.service = "" self.sleep_hook = lambda: setattr(self.page, attribute, value) with self.assertRaises(CalendarBookError): self.wait() setattr(self.page, attribute, original) def test_session_change_during_dom_read_is_checked_before_accepting_value(self): checks = iter([True, False]) with self.assertRaisesRegex(CalendarBookError, "Session changed"): self.wait(session_is_current=lambda: next(checks)) self.assertEqual(self.sleeps, []) def test_guard_violation_and_transport_failure_are_not_retried(self): self.page.guard_final_count = 1 with self.assertRaises(book_calendar.CalendarGateError): self.wait() self.page.guard_final_count = 0 self.page.browser_error = "browser offline" with self.assertRaises(RuntimeError): self.wait() self.assertEqual(self.sleeps, []) def test_invalid_wait_contract_is_rejected(self): for timeout in (-1, True, "1", float("inf"), float("nan")): with self.subTest(timeout=timeout), self.assertRaises(CalendarBookError): self.wait(timeout=timeout) with self.assertRaises(CalendarBookError): self.wait(session_is_current=None) self.assertEqual(self.page.events, []) class BookPacketTests(unittest.TestCase): def test_positive_one_zero_uses_current_runtime_service(self): _, times = packets() result = parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE) self.assertEqual(len(result), 1) self.assertTrue(result[0].is_available) self.assertNotIn(str(DAILY_ID), repr(result)) def test_accepts_json_request_and_day_month_year_date(self): _, times = packets() times.request.postData = json.dumps({"selectedDay": "13/10/2026", "idService": int(SERVICE)}) self.assertEqual(len(parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE)), 1) def test_rejects_wrong_metadata_without_disclosing_packet(self): mutations = [ lambda p: setattr(p, "url", "https://other.example.test" + TIME_SLOTS_PATH), lambda p: setattr(p, "url", "https://prenotami.esteri.it/BookingCalendar/Other"), lambda p: setattr(p, "method", "GET"), lambda p: setattr(p.response, "status", 302), lambda p: setattr(p.response, "status", True), lambda p: p.request.postData.update(idService="4937"), lambda p: p.request.postData.update(idService=True), lambda p: p.request.postData.update(idService=None), lambda p: p.request.postData.update(selectedDay="2026-10-14"), lambda p: p.request.postData.update(selectedDay="2026-10-13-unverified"), lambda p: p.request.postData.update(unexpected="secret-body-marker"), lambda p: setattr(p.request, "postData", "secret-body-marker"), lambda p: setattr(p.response, "raw_body", "secret-body-marker"), lambda p: setattr(p.response, "raw_body", json.dumps([])), ] for mutate in mutations: with self.subTest(mutation=mutations.index(mutate)): _, times = packets() mutate(times) try: parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE) except CalendarBookError: self.assertNotIn("secret-body-marker", traceback.format_exc()) else: self.fail("Invalid packet was accepted") def test_rejects_wrong_response_day_before_capacity_filtering(self): _, times = packets() times.response.raw_body = double_json([ slot_item("14/10/2026 00:00:00", (10, 5), (11, 5), 0, -1, DAILY_ID), ]) with self.assertRaisesRegex(CalendarBookError, "another day"): parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE) def test_capacity_conflict_is_not_no_availability(self): _, times = packets(free=1, remaining=-1) with self.assertRaises(CalendarBookError): parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE) class BookSelectionTests(unittest.TestCase): def test_selects_once_and_returns_only_precommit_approval(self): page = FakePage() result = select(page) self.assertEqual(result.candidate.day, DAY) self.assertEqual(result.candidate.time_label, "10:05 - 11:05") self.assertFalse(hasattr(result, "success")) self.assertNotIn(str(DAILY_ID), repr(result)) self.assertEqual(page.events, ["guard", "slot-click", "guard"]) def test_repeated_selection_does_not_repeat_native_click(self): page = FakePage() select(page) select(page) self.assertEqual(page.clicks, 1) def test_no_slots_returns_none_and_never_clicks(self): page = FakePage() self.assertIsNone(select(page, packets(free=0, remaining=-1))) self.assertEqual(page.events, ["guard", "guard"]) def test_slots_disappearing_after_positive_day_is_safe_none(self): page = FakePage() availability, _ = packets() _, times = packets(free=0, remaining=-1) self.assertIsNone(select(page, (availability, times))) self.assertEqual(page.clicks, 0) def test_positive_slots_with_negative_day_is_conflict(self): page = FakePage() availability, _ = packets(free=0, remaining=-1) _, times = packets() with self.assertRaisesRegex(CalendarBookError, "disagree"): select(page, (availability, times)) self.assertEqual(page.clicks, 0) def test_uses_earliest_time_even_if_later_slots_have_more_capacity(self): page = FakePage() availability, times = packets(free=8, remaining=7) times.response.raw_body = double_json([ slot_item("13/10/2026 00:00:00", (9, 0), (10, 0), 1, 0, 80001002), slot_item("13/10/2026 00:00:00", (12, 0), (13, 0), 4, 3, 80001003), slot_item("13/10/2026 00:00:00", (10, 0), (11, 0), 4, 3, 80001004), ]) result = select(page, (availability, times)) self.assertEqual(result.candidate.time_label, "09:00 - 10:00") self.assertEqual(page.last_candidate, ("80001002", "09:00 - 10:00", 1)) def test_rejects_bad_context_before_any_click(self): for field, value in (("url", "https://other.example.test/BookingCalendar"), ("url", "https://prenotami.esteri.it/UserArea"), ("context_count", 2), ("context_count", True), ("service", ""), ("service", None)): with self.subTest(field=field, value=value): page = FakePage() setattr(page, field, value) with self.assertRaises(CalendarBookError): select(page) self.assertEqual(page.clicks, 0) def test_rejects_wrong_availability_month(self): page = FakePage() availability, times = packets() availability.request.postData["selectedDay"] = "01/11/2026" availability.response.raw_body = double_json([]) with self.assertRaisesRegex(CalendarBookError, "another month"): select(page, (availability, times)) self.assertEqual(page.clicks, 0) def test_preclick_invariants_reject_without_clicking(self): mutations = [ {"contextReady": False}, {"candidateCount": 2}, {"candidateReady": False}, {"clicked": True}, {"candidateCount": True}, {"candidateReady": 1}, {"extra": "unexpected"}, ] for changes in mutations: with self.subTest(changes=changes): page = FakePage() page.overrides = changes with self.assertRaises(CalendarBookError): select(page) self.assertEqual(page.clicks, 0) self.assertEqual(page.events[-1], "guard") def test_failed_click_is_not_retried(self): page = FakePage() page.click_ack = False with self.assertRaisesRegex(CalendarBookError, "acknowledged"): select(page) self.assertEqual(page.clicks, 0) def test_postclick_drift_is_rejected_and_not_retried(self): mutations = [ {"contextReady": False}, {"candidateCount": 2}, {"candidateReady": False}, {"selected": False}, ] for changes in mutations: with self.subTest(changes=changes): page = FakePage() page.after_overrides = changes with self.assertRaises(CalendarBookError): select(page) self.assertEqual(page.clicks, 1) self.assertEqual(page.events[-1], "guard") def test_observed_final_request_is_never_accepted(self): page = FakePage() page.guard_final_count = 1 with self.assertRaises(CalendarBookError): select(page) self.assertEqual(page.clicks, 0) def test_browser_exception_does_not_leak_content(self): page = FakePage() page.browser_error = "secret-browser-body-marker" try: select(page) except CalendarBookError: self.assertNotIn("secret-browser-body-marker", traceback.format_exc()) else: self.fail("Browser failure was accepted") def test_requires_date_not_datetime_or_string(self): for target in (DAY.isoformat(), datetime(2026, 10, 13), None): with self.subTest(target=target): page = FakePage() with self.assertRaises(CalendarBookError): select_slot_before_final(page, target_day=target, probe=None, slots=(), runtime_service=SERVICE) self.assertEqual(page.events, []) def test_adapter_has_no_query_tool_network_or_final_action(self): from test.ita.ita_source_sections import section source = section("calendar_book") module = ast.parse(source) imports = [node.module or "" for node in ast.walk(module) if isinstance(node, ast.ImportFrom)] self.assertFalse(any(name.startswith("tools") or name == "plugins.ita_plugin" for name in imports)) for token in ("GenerateOTP", "btnAvanti", "InsertNewBooking", "fetch(", "XMLHttpRequest", ".submit("): self.assertNotIn(token, source) self.assertEqual(SLOT_SELECTION_SCRIPT.count("candidate.click()"), 1) JS_HARNESS = r""" const vm = require('node:vm'); const payload = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); const mode = payload.mode; const day = '2026-10-13'; let slotClicks = 0, finalClicks = 0; function element(classes = [], extras = {}) { const set = new Set(classes); return Object.assign({ dataset: {}, isConnected: true, children: [], style: {}, classList: {contains: (c) => set.has(c), add: (c) => set.add(c), remove: (c) => set.delete(c)}, hasAttribute: () => false, getAttribute: () => null, getBoundingClientRect: () => ({left: 20, right: 200, top: 20, bottom: 100}), contains(other) {return other === this || this.children.some((c) => c.contains(other));}, }, extras); } const timeline = element(['input-async-abilitato', 'selected'], {dataset: {date: day}}); const content = element(['selected'], {dataset: {date: day}}); const input = element([], {type: 'hidden', id: 'idHiddenFasciaServizio', value: '80001001'}); const spans = [element([], {textContent: '10:05 - 11:05'}), element([], {textContent: '(1)'})]; const candidate = element([], {children: [input, ...spans]}); const fields = [input]; let red = false; candidate.querySelectorAll = (selector) => selector === 'input' ? fields : selector === 'span' ? spans : []; candidate.querySelector = (selector) => selector === '.dotRed' && red ? element(['dotRed']) : null; const slots = [candidate]; content.children = slots; content.querySelectorAll = (selector) => selector === '.fascia' ? slots : []; const finalButton = element([], {disabled: true, dataset: {coordinateFinalGuard: 'enabled'}, click: () => finalClicks++}); const service = {value: '7002'}; let occluded = false; candidate.click = () => { slotClicks++; slots.forEach((slot) => slot.classList.remove('act')); candidate.classList.add('act'); if (mode === 'drift') content.dataset.date = '2026-10-14'; if (mode === 'drift_origin') window.location.origin = 'https://other.example.test'; }; if (mode === 'already_active') candidate.classList.add('act'); if (mode === 'negative') candidate.classList.add('notAvailableFascia'); if (mode === 'red') red = true; if (mode === 'wrong_time') spans[0].textContent = '09:00 - 10:00'; if (mode === 'wrong_capacity') spans[1].textContent = '(0)'; if (mode === 'wrong_id') input.value = '80009999'; if (mode === 'extra_input') fields.push(element([], {type: 'hidden', value: 'extra'})); if (mode === 'duplicate_slot') slots.push(candidate); if (mode === 'wrong_date') content.dataset.date = '2026-10-14'; if (mode === 'wrong_service') service.value = '7003'; if (mode === 'unguarded_final') finalButton.disabled = false; if (mode === 'hidden') candidate.style.display = 'none'; if (mode === 'occluded') occluded = true; if (mode === 'disabled_day') timeline.classList.add('input-async-disabilitato'); const document = { querySelectorAll(selector) { if (selector === '#idServizio') return [service]; if (selector === '#btnPrenotaNoOtp') return [finalButton]; if (selector === '.events a.selected') return [timeline]; if (selector === '.events-content li.selected') return [content]; if (selector === '.events a[data-date]') return [timeline]; if (selector === '.fascia.act') return slots.filter((slot) => slot.classList.contains('act')); throw Error('Unexpected selector ' + selector); }, querySelector(selector) { if (selector === '.selected') return mode === 'foreign_selected_first' ? element(['selected']) : timeline; throw Error('Unexpected selector ' + selector); }, elementFromPoint: () => occluded ? element() : candidate, }; const window = { location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it', pathname: '/BookingCalendar'}, innerWidth: 1000, innerHeight: 800, getComputedStyle: (item) => Object.assign({display: 'block', visibility: 'visible', pointerEvents: 'auto', opacity: '1'}, item.style), }; const run = (click) => vm.runInNewContext('(function(){' + payload.source + '\n}).apply(null, args)', {document, window, args: ['7002', day, '80001001', '10:05 - 11:05', 1, click]}, {timeout: 1000}); const before = run(false), acted = run(true), after = run(false); process.stdout.write(JSON.stringify({before, acted, after, slotClicks, finalClicks})); """ @unittest.skipUnless(shutil.which("node"), "Node is required for offline JavaScript DOM-contract checks") class BookJavaScriptContractTests(unittest.TestCase): def run_case(self, mode): result = subprocess.run( [shutil.which("node"), "-e", JS_HARNESS], input=json.dumps({"source": SLOT_SELECTION_SCRIPT, "mode": mode}), text=True, capture_output=True, timeout=10, check=True, ) return json.loads(result.stdout) def test_actual_script_clicks_only_positive_candidate(self): result = self.run_case("positive") self.assertTrue(result["before"]["candidateReady"]) self.assertEqual(result["slotClicks"], 1) self.assertEqual(result["finalClicks"], 0) self.assertTrue(result["after"]["selected"]) def test_actual_script_does_not_click_again_when_already_selected(self): result = self.run_case("already_active") self.assertEqual(result["slotClicks"], 0) self.assertTrue(result["after"]["selected"]) def test_actual_script_rejects_unsafe_dom_before_click(self): modes = ("negative", "red", "wrong_time", "wrong_capacity", "wrong_id", "extra_input", "duplicate_slot", "wrong_date", "wrong_service", "unguarded_final", "hidden", "occluded", "disabled_day", "foreign_selected_first", "wrong_origin") for mode in modes: with self.subTest(mode=mode): result = self.run_case(mode) self.assertEqual(result["slotClicks"], 0) self.assertEqual(result["finalClicks"], 0) def test_actual_script_readback_exposes_postclick_date_drift(self): result = self.run_case("drift") self.assertEqual(result["slotClicks"], 1) self.assertFalse(result["after"]["contextReady"]) self.assertFalse(result["after"]["selected"]) self.assertEqual(result["finalClicks"], 0) def test_actual_script_readback_exposes_postclick_origin_drift(self): result = self.run_case("drift_origin") self.assertEqual(result["slotClicks"], 1) self.assertFalse(result["after"]["contextReady"]) self.assertEqual(result["finalClicks"], 0) if __name__ == "__main__": unittest.main()