| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271 |
- import json
- import shutil
- import subprocess
- import unittest
- from unittest.mock import Mock, patch
- from plugins.ita_plugin import (
- CalendarGateError,
- CalendarNextMonthUnavailableError,
- CalendarProbeResult,
- NEXT_MONTH_CONTROL_SCRIPT,
- scan_until_first_available_month,
- )
- from plugins.ita_plugin import parse_calendar_availability
- MONTH_CONTROL_HARNESS = r"""
- const vm = require('node:vm');
- const {source, mode} = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
- let clicks = 0;
- const node = {
- isConnected: mode !== 'detached',
- hasAttribute: name => name === 'disabled' && mode === 'disabled',
- getAttribute: name => name === 'aria-disabled' && mode === 'aria_disabled' ? 'true' : null,
- getBoundingClientRect: () => ({left: 20, right: mode === 'zero_size' ? 20 : 100,
- top: mode === 'offscreen' ? 2000 : 20, bottom: 100}),
- contains: item => item === node,
- click: () => clicks++,
- };
- const document = {
- querySelectorAll: selector => {
- if (selector !== '#datetimepicker th.dtpicker-next') throw Error('Unexpected selector');
- return mode === 'missing' ? [] : mode === 'duplicate' ? [node, node] : [node];
- },
- elementFromPoint: () => mode === 'occluded' ? {} : node,
- };
- const window = {
- location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it',
- pathname: mode === 'wrong_path' ? '/UserArea' : '/BookingCalendar'},
- innerWidth: 1000, innerHeight: 800,
- getComputedStyle: () => ({display: mode === 'hidden' ? 'none' : 'block',
- visibility: mode === 'invisible' ? 'hidden' : 'visible',
- pointerEvents: mode === 'pointer_blocked' ? 'none' : 'auto', opacity: mode === 'transparent' ? '0' : '1'}),
- };
- const run = click => vm.runInNewContext('(function(){' + source + '\n}).apply(null, args)',
- {document, window, args: [click]}, {timeout: 1000});
- const before = run(false), acted = run(true);
- process.stdout.write(JSON.stringify({before, acted, clicks}));
- """
- @unittest.skipUnless(shutil.which("node"), "Node is required for actual Calendar-control scripts")
- class MonthControlJavaScriptTests(unittest.TestCase):
- def run_case(self, mode):
- result = subprocess.run(
- [shutil.which("node"), "-e", MONTH_CONTROL_HARNESS],
- input=json.dumps({"source": NEXT_MONTH_CONTROL_SCRIPT, "mode": mode}),
- text=True, capture_output=True, timeout=10, check=True,
- )
- return json.loads(result.stdout)
- def test_shared_control_check_only_clicks_the_ready_month_control(self):
- result = self.run_case("ready")
- self.assertFalse(result["before"]["clicked"])
- self.assertEqual(result["before"]["actionableCount"], 1)
- self.assertTrue(result["acted"]["clicked"])
- self.assertEqual(result["clicks"], 1)
- def test_hidden_disabled_covered_duplicate_or_foreign_controls_are_not_clicked(self):
- for mode in ("detached", "disabled", "aria_disabled", "zero_size", "offscreen", "occluded",
- "missing", "duplicate", "hidden", "invisible", "pointer_blocked", "transparent",
- "wrong_origin", "wrong_path"):
- with self.subTest(mode=mode):
- result = self.run_case(mode)
- self.assertFalse(result["acted"]["clicked"])
- self.assertEqual(result["clicks"], 0)
- def double_json(items):
- return json.dumps(json.dumps(items))
- def probe(year, month, capacities):
- items = [
- {
- "DateLibere": f"{day:02d}/{month:02d}/{year:04d} 00:00:00",
- "SlotLiberi": slots_free,
- "SlotRimanenti": slots_remaining,
- }
- for day, slots_free, slots_remaining in capacities
- ]
- return CalendarProbeResult(
- days=parse_calendar_availability(double_json(items)),
- selected_day=f"01/{month:02d}/{year:04d}",
- )
- class CalendarProductionScanTests(unittest.TestCase):
- def test_selected_month_preserves_both_observed_date_formats(self):
- for selected_day in ("01/09/2026", "2026-09-01", " 01/09/2026 00:00:00 "):
- with self.subTest(selected_day=selected_day):
- result = CalendarProbeResult(days=(), selected_day=selected_day)
- self.assertEqual(result.selected_month, (2026, 9))
- for selected_day in ("not-a-date", "2026-13-01"):
- with self.subTest(selected_day=selected_day), self.assertRaises(CalendarGateError):
- CalendarProbeResult(days=(), selected_day=selected_day)
- def test_rejects_dates_outside_the_requested_month(self):
- october_days = parse_calendar_availability(
- double_json(
- [
- {
- "DateLibere": "01/10/2026 00:00:00",
- "SlotLiberi": 1,
- "SlotRimanenti": 0,
- }
- ]
- )
- )
- with self.assertRaisesRegex(
- CalendarGateError,
- "escaped the requested month",
- ):
- CalendarProbeResult(
- days=october_days,
- selected_day="01/09/2026",
- )
- def test_stops_on_the_initial_positive_month(self):
- august = probe(2026, 8, [(20, 2, 1), (12, 1, 0)])
- with patch("plugins.ita_plugin._capture_month", side_effect=[august]) as capture:
- result = scan_until_first_available_month(
- Mock(),
- lookahead_months=12,
- month_click_interval_seconds=0,
- )
- capture.assert_called_once()
- self.assertEqual(len(result), 1)
- self.assertEqual(
- result[-1].available_days[0].day.isoformat(),
- "2026-08-12",
- )
- def test_scans_sequentially_then_stops_at_the_first_positive_month(self):
- august = probe(2026, 8, [(31, 0, -1)])
- september = probe(2026, 9, [(30, 0, -1)])
- october = probe(
- 2026,
- 10,
- [(20, 8, 7), (12, 1, 0), (1, 0, -1)],
- )
- november = probe(2026, 11, [(2, 10, 9)])
- log = Mock()
- with patch(
- "plugins.ita_plugin._capture_month",
- side_effect=[august, september, october, november],
- ) as capture:
- result = scan_until_first_available_month(
- Mock(),
- lookahead_months=12,
- log=log,
- month_click_interval_seconds=0,
- )
- self.assertEqual(capture.call_count, 3)
- self.assertEqual(len(result), 3)
- self.assertEqual(
- result[-1].available_days[0].day.isoformat(),
- "2026-10-12",
- )
- self.assertEqual(
- [item.day.isoformat() for item in result[-1].available_days],
- ["2026-10-12", "2026-10-20"],
- )
- self.assertEqual(log.call_count, 3)
- def test_returns_none_only_after_the_complete_horizon(self):
- months = [
- probe(2026, month, [(1, 0, -1)])
- for month in (8, 9, 10)
- ]
- with patch("plugins.ita_plugin._capture_month", side_effect=months) as capture:
- result = scan_until_first_available_month(
- Mock(),
- lookahead_months=3,
- month_click_interval_seconds=0,
- )
- self.assertEqual(capture.call_count, 3)
- self.assertEqual(len(result), 3)
- self.assertEqual(result[-1].available_days, ())
- def test_accepts_an_exact_cross_year_transition(self):
- december = probe(2026, 12, [(1, 0, -1)])
- january = probe(2027, 1, [(4, 1, 0)])
- with patch("plugins.ita_plugin._capture_month", side_effect=[december, january]):
- result = scan_until_first_available_month(
- Mock(),
- lookahead_months=2,
- month_click_interval_seconds=0,
- )
- self.assertEqual(
- result[-1].available_days[0].day.isoformat(),
- "2027-01-04",
- )
- def test_rejects_a_skipped_month_instead_of_publishing_a_signal(self):
- august = probe(2026, 8, [(1, 0, -1)])
- october = probe(2026, 10, [(1, 1, 0)])
- with patch("plugins.ita_plugin._capture_month", side_effect=[august, october]):
- with self.assertRaisesRegex(
- CalendarGateError,
- "exactly one month",
- ):
- scan_until_first_available_month(
- Mock(),
- lookahead_months=2,
- month_click_interval_seconds=0,
- )
- def test_incomplete_native_navigation_is_not_misreported_as_no_slots(self):
- august = probe(2026, 8, [(1, 0, -1)])
- with patch(
- "plugins.ita_plugin._capture_month",
- side_effect=[august, CalendarNextMonthUnavailableError("bounded")],
- ):
- with self.assertRaisesRegex(
- CalendarGateError,
- "before the configured horizon",
- ):
- scan_until_first_available_month(
- Mock(),
- lookahead_months=2,
- month_click_interval_seconds=0,
- )
- def test_rejects_invalid_scan_bounds(self):
- for value in (True, 0, 121):
- with self.subTest(value=value):
- with self.assertRaisesRegex(
- CalendarGateError,
- "lookahead_months",
- ):
- scan_until_first_available_month(
- Mock(),
- lookahead_months=value,
- month_click_interval_seconds=0,
- )
- def test_invalid_scan_interval_never_touches_the_browser(self):
- for value in (True, None, "1", -1, float("nan"), float("inf")):
- with self.subTest(value=value):
- page = Mock()
- with self.assertRaisesRegex(CalendarGateError, "interval"):
- scan_until_first_available_month(
- page, lookahead_months=3, month_click_interval_seconds=value
- )
- self.assertEqual(page.mock_calls, [])
- if __name__ == "__main__":
- unittest.main()
|