"""Offline one-shot discovery; no credentials, browser launch or website calls.""" import json import os import tempfile import unittest from concurrent.futures import ThreadPoolExecutor from contextlib import redirect_stdout from io import StringIO from pathlib import Path from unittest.mock import Mock, patch from plugins.ita_plugin import FinalBookingError, SubmissionSignal from test import test_ita_final_read_port as port_fixtures from test.test_ita_reservation import listing, detail from tools import ita_final_evidence as evidence class ClaimTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.path = Path(self.temp.name) / "private" / "once.claim" def test_preflight_does_not_create_directory(self): evidence.require_unused_claim(self.path) self.assertFalse(self.path.parent.exists()) def test_claim_is_exclusive_private_and_contains_no_identity(self): evidence.claim_once(self.path) self.assertEqual(json.loads(self.path.read_text()), { "schema": 1, "state": "possibly_submitted", "automaticRetry": False}) self.assertEqual(self.path.stat().st_mode & 0o777, 0o600) self.assertEqual(self.path.parent.stat().st_mode & 0o777, 0o700) with self.assertRaises(FileExistsError): evidence.claim_once(self.path) with self.assertRaises(FinalBookingError): evidence.require_unused_claim(self.path) def test_partial_claim_blocks_and_is_not_removed_after_fsync_failure(self): with patch.object(evidence.os, "fsync", side_effect=OSError("synthetic")): with self.assertRaises(OSError): evidence.claim_once(self.path) with self.assertRaises(FinalBookingError): evidence.require_unused_claim(self.path) def test_dangling_symlink_and_directory_are_blocked(self): self.path.parent.mkdir() self.path.symlink_to(self.path.parent / "missing") with self.assertRaises(FinalBookingError): evidence.require_unused_claim(self.path) with self.assertRaises(FileExistsError): evidence.claim_once(self.path) self.assertFalse((self.path.parent / "missing").exists()) def test_symlink_parent_is_not_written_through(self): other = Path(self.temp.name) / "other" other.mkdir() self.path.parent.symlink_to(other, target_is_directory=True) with self.assertRaises(ValueError): evidence.claim_once(self.path) self.assertEqual(list(other.iterdir()), []) def test_concurrent_claims_have_one_winner(self): def claim(_): try: evidence.claim_once(self.path) return True except FileExistsError: return False with ThreadPoolExecutor(max_workers=4) as pool: self.assertEqual(sum(pool.map(claim, range(4))), 1) class FinalEvidenceTests(unittest.TestCase): def setUp(self): port_fixtures.FinalReadPortTests.setUp(self) self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.path = Path(self.temp.name) / "private" / "once.claim" self.check = patch.object(evidence, "verify_precommit_selection").start() self.native = Mock(return_value=SubmissionSignal.ACCEPTED) self.factory = patch.object(evidence, "NativeFinalSubmitter", return_value=self.native).start() self.output = StringIO() patcher = redirect_stdout(self.output) patcher.__enter__() self.addCleanup(lambda: patcher.__exit__(None, None, None)) def run_object(self): return evidence.FinalEvidenceRun(self.plugin, self.route, claim_path=self.path) def confirm(self, _prompt): slot = self.plugin.last_booking_precommit.candidate return f"BOOK {slot.day.isoformat()} {slot.time_label}" def test_decline_never_reads_or_submits_or_claims(self): run = self.run_object() report = run.execute(confirm=lambda _: "no") self.assertEqual(report["outcome"], "confirmation_declined") self.assertFalse(self.path.exists()) self.native.assert_not_called() self.browser.new_tab.assert_not_called() with self.assertRaises(FinalBookingError): run.execute(confirm=self.confirm) def test_existing_fence_blocks_before_prompt(self): evidence.claim_once(self.path) prompt = Mock() with self.assertRaises(FinalBookingError): self.run_object().execute(confirm=prompt) prompt.assert_not_called() self.native.assert_not_called() def test_unknown_response_uses_core_and_persists_fence_before_click(self): def native(): self.assertTrue(self.path.exists()) return SubmissionSignal.UNKNOWN self.native.side_effect = native run = self.run_object() report = run.execute(confirm=self.confirm) self.native.assert_called_once() self.assertTrue(report["attempted"]) self.assertEqual(report["outcome"], "unknown_do_not_retry") self.assertTrue(report["receiptEvidence"]["readVerified"]) self.assertTrue(report["receiptEvidence"]["historicalRecordsUnchanged"]) self.assertFalse(report["bookingConfirmed"]) with self.assertRaises(FinalBookingError): self.run_object().execute(confirm=self.confirm) self.assertTrue(self.path.exists()) def test_rejection_is_not_a_retry_instruction(self): self.native.return_value = SubmissionSignal.REJECTED report = self.run_object().execute(confirm=self.confirm) self.assertEqual(report["outcome"], "rejected_do_not_retry") self.assertTrue(self.path.exists()) self.native.assert_called_once() def test_native_exception_or_interrupt_still_leaves_fence(self): for error in (RuntimeError("SECRET"), KeyboardInterrupt()): with self.subTest(error=type(error).__name__): path = Path(self.temp.name) / type(error).__name__ / "claim" self.native.side_effect = error run = evidence.FinalEvidenceRun(self.plugin, self.route, claim_path=path) if isinstance(error, KeyboardInterrupt): with self.assertRaises(KeyboardInterrupt): run.execute(confirm=self.confirm) else: run.execute(confirm=self.confirm) self.assertTrue(path.exists()) self.assertTrue(run.possibly_submitted) self.assertFalse(run.report["bookingConfirmed"]) self.assertNotIn("SECRET", self.output.getvalue()) def test_claim_failure_never_calls_native(self): with patch.object(evidence, "claim_once", side_effect=OSError("PRIVATE")): with self.assertRaises(FinalBookingError): self.run_object().execute(confirm=self.confirm) self.native.assert_not_called() self.assertNotIn("PRIVATE", self.output.getvalue()) def test_unknown_old_receipt_blocks_before_claim(self): self.browser.raw["tables"][0]["rows"][0]["status"] = "Unverified" with self.assertRaises(FinalBookingError): self.run_object().execute(confirm=self.confirm) self.native.assert_not_called() self.assertFalse(self.path.exists()) def test_selection_changes_during_confirmation_blocks_before_claim(self): def confirm(prompt): answer = self.confirm(prompt) self.check.side_effect = RuntimeError("changed") return answer with self.assertRaises(FinalBookingError): self.run_object().execute(confirm=confirm) self.assertFalse(self.path.exists()) self.native.assert_not_called() def test_new_unknown_receipt_is_observed_without_assigning_success_or_leaking_reference(self): # Empty initial baseline, then one new unknown receipt. Values are # synthetic evidence shapes, NOT an asserted mapping for the live site. table = self.browser.raw["tables"][0] table["rows"], table["count"] = [], 0 table["info"].update(pages=0, end=0, recordsTotal=0, recordsDisplay=0) def native(): self.browser.raw = listing() self.browser.receipt = detail() self.browser.raw["tables"][0]["rows"][0]["status"] = "SYNTHETIC-NEW-STATE" self.browser.receipt["fields"]["Stato"] = "SYNTHETIC-NEW-STATE" self.browser.receipt["statusCode"] = "999" return SubmissionSignal.ACCEPTED self.native.side_effect = native run = self.run_object() report = run.execute(confirm=self.confirm) observation = report["receiptEvidence"] self.assertTrue(observation["readVerified"]) self.assertEqual(observation["newRecordCount"], 1) self.assertEqual(observation["newRecords"][0]["classifiedState"], "unknown") self.assertEqual(observation["newRecords"][0]["statusCode"], "999") self.assertFalse(report["bookingConfirmed"]) self.assertNotIn("SYNTHETIC-REFERENCE", json.dumps(report)) self.assertNotIn("synthetic-link", json.dumps(report)) self.assertEqual(self.main.url, "https://prenotami.esteri.it/BookingCalendar") self.assertTrue(all(p.close.call_count == 1 for p in self.browser.pages)) def test_unknown_observation_does_not_relax_strict_read_port(self): self.browser.raw["tables"][0]["rows"][0]["status"] = "Unverified" self.browser.receipt["fields"]["Stato"] = "Unverified" self.browser.receipt["statusCode"] = "999" observation = self.port.observe_receipts() self.assertEqual(observation.records[0][1].state.value, "unknown") with self.assertRaises(FinalBookingError): self.port() def test_observation_mismatch_and_context_change_are_blocked(self): self.browser.receipt["fields"]["Ora"] = "12:00" with self.assertRaises(FinalBookingError): self.port.observe_receipts() self.browser.new_tab.reset_mock() self.plugin.is_healthy = False with self.assertRaises(FinalBookingError): self.port.observe_receipts() self.browser.new_tab.assert_not_called() def test_review_keeps_browser_until_reader_returns(self): reader = Mock(return_value="") evidence.wait_for_receipt_review(reader=reader) reader.assert_called_once() self.assertIn("Do NOT rerun", self.output.getvalue()) self.main.close.assert_not_called() if __name__ == "__main__": unittest.main()