test_ita_calendar_query.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import json
  2. import shutil
  3. import subprocess
  4. import unittest
  5. from unittest.mock import Mock, patch
  6. from plugins.ita_plugin import (
  7. CalendarGateError,
  8. CalendarNextMonthUnavailableError,
  9. CalendarProbeResult,
  10. NEXT_MONTH_CONTROL_SCRIPT,
  11. scan_until_first_available_month,
  12. )
  13. from plugins.ita_plugin import parse_calendar_availability
  14. MONTH_CONTROL_HARNESS = r"""
  15. const vm = require('node:vm');
  16. const {source, mode} = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
  17. let clicks = 0;
  18. const node = {
  19. isConnected: mode !== 'detached',
  20. hasAttribute: name => name === 'disabled' && mode === 'disabled',
  21. getAttribute: name => name === 'aria-disabled' && mode === 'aria_disabled' ? 'true' : null,
  22. getBoundingClientRect: () => ({left: 20, right: mode === 'zero_size' ? 20 : 100,
  23. top: mode === 'offscreen' ? 2000 : 20, bottom: 100}),
  24. contains: item => item === node,
  25. click: () => clicks++,
  26. };
  27. const document = {
  28. querySelectorAll: selector => {
  29. if (selector !== '#datetimepicker th.dtpicker-next') throw Error('Unexpected selector');
  30. return mode === 'missing' ? [] : mode === 'duplicate' ? [node, node] : [node];
  31. },
  32. elementFromPoint: () => mode === 'occluded' ? {} : node,
  33. };
  34. const window = {
  35. location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it',
  36. pathname: mode === 'wrong_path' ? '/UserArea' : '/BookingCalendar'},
  37. innerWidth: 1000, innerHeight: 800,
  38. getComputedStyle: () => ({display: mode === 'hidden' ? 'none' : 'block',
  39. visibility: mode === 'invisible' ? 'hidden' : 'visible',
  40. pointerEvents: mode === 'pointer_blocked' ? 'none' : 'auto', opacity: mode === 'transparent' ? '0' : '1'}),
  41. };
  42. const run = click => vm.runInNewContext('(function(){' + source + '\n}).apply(null, args)',
  43. {document, window, args: [click]}, {timeout: 1000});
  44. const before = run(false), acted = run(true);
  45. process.stdout.write(JSON.stringify({before, acted, clicks}));
  46. """
  47. @unittest.skipUnless(shutil.which("node"), "Node is required for actual Calendar-control scripts")
  48. class MonthControlJavaScriptTests(unittest.TestCase):
  49. def run_case(self, mode):
  50. result = subprocess.run(
  51. [shutil.which("node"), "-e", MONTH_CONTROL_HARNESS],
  52. input=json.dumps({"source": NEXT_MONTH_CONTROL_SCRIPT, "mode": mode}),
  53. text=True, capture_output=True, timeout=10, check=True,
  54. )
  55. return json.loads(result.stdout)
  56. def test_shared_control_check_only_clicks_the_ready_month_control(self):
  57. result = self.run_case("ready")
  58. self.assertFalse(result["before"]["clicked"])
  59. self.assertEqual(result["before"]["actionableCount"], 1)
  60. self.assertTrue(result["acted"]["clicked"])
  61. self.assertEqual(result["clicks"], 1)
  62. def test_hidden_disabled_covered_duplicate_or_foreign_controls_are_not_clicked(self):
  63. for mode in ("detached", "disabled", "aria_disabled", "zero_size", "offscreen", "occluded",
  64. "missing", "duplicate", "hidden", "invisible", "pointer_blocked", "transparent",
  65. "wrong_origin", "wrong_path"):
  66. with self.subTest(mode=mode):
  67. result = self.run_case(mode)
  68. self.assertFalse(result["acted"]["clicked"])
  69. self.assertEqual(result["clicks"], 0)
  70. def double_json(items):
  71. return json.dumps(json.dumps(items))
  72. def probe(year, month, capacities):
  73. items = [
  74. {
  75. "DateLibere": f"{day:02d}/{month:02d}/{year:04d} 00:00:00",
  76. "SlotLiberi": slots_free,
  77. "SlotRimanenti": slots_remaining,
  78. }
  79. for day, slots_free, slots_remaining in capacities
  80. ]
  81. return CalendarProbeResult(
  82. days=parse_calendar_availability(double_json(items)),
  83. selected_day=f"01/{month:02d}/{year:04d}",
  84. )
  85. class CalendarProductionScanTests(unittest.TestCase):
  86. def test_selected_month_preserves_both_observed_date_formats(self):
  87. for selected_day in ("01/09/2026", "2026-09-01", " 01/09/2026 00:00:00 "):
  88. with self.subTest(selected_day=selected_day):
  89. result = CalendarProbeResult(days=(), selected_day=selected_day)
  90. self.assertEqual(result.selected_month, (2026, 9))
  91. for selected_day in ("not-a-date", "2026-13-01"):
  92. with self.subTest(selected_day=selected_day), self.assertRaises(CalendarGateError):
  93. CalendarProbeResult(days=(), selected_day=selected_day)
  94. def test_rejects_dates_outside_the_requested_month(self):
  95. october_days = parse_calendar_availability(
  96. double_json(
  97. [
  98. {
  99. "DateLibere": "01/10/2026 00:00:00",
  100. "SlotLiberi": 1,
  101. "SlotRimanenti": 0,
  102. }
  103. ]
  104. )
  105. )
  106. with self.assertRaisesRegex(
  107. CalendarGateError,
  108. "escaped the requested month",
  109. ):
  110. CalendarProbeResult(
  111. days=october_days,
  112. selected_day="01/09/2026",
  113. )
  114. def test_stops_on_the_initial_positive_month(self):
  115. august = probe(2026, 8, [(20, 2, 1), (12, 1, 0)])
  116. with patch("plugins.ita_plugin._capture_month", side_effect=[august]) as capture:
  117. result = scan_until_first_available_month(
  118. Mock(),
  119. lookahead_months=12,
  120. month_click_interval_seconds=0,
  121. )
  122. capture.assert_called_once()
  123. self.assertEqual(len(result), 1)
  124. self.assertEqual(
  125. result[-1].available_days[0].day.isoformat(),
  126. "2026-08-12",
  127. )
  128. def test_scans_sequentially_then_stops_at_the_first_positive_month(self):
  129. august = probe(2026, 8, [(31, 0, -1)])
  130. september = probe(2026, 9, [(30, 0, -1)])
  131. october = probe(
  132. 2026,
  133. 10,
  134. [(20, 8, 7), (12, 1, 0), (1, 0, -1)],
  135. )
  136. november = probe(2026, 11, [(2, 10, 9)])
  137. log = Mock()
  138. with patch(
  139. "plugins.ita_plugin._capture_month",
  140. side_effect=[august, september, october, november],
  141. ) as capture:
  142. result = scan_until_first_available_month(
  143. Mock(),
  144. lookahead_months=12,
  145. log=log,
  146. month_click_interval_seconds=0,
  147. )
  148. self.assertEqual(capture.call_count, 3)
  149. self.assertEqual(len(result), 3)
  150. self.assertEqual(
  151. result[-1].available_days[0].day.isoformat(),
  152. "2026-10-12",
  153. )
  154. self.assertEqual(
  155. [item.day.isoformat() for item in result[-1].available_days],
  156. ["2026-10-12", "2026-10-20"],
  157. )
  158. self.assertEqual(log.call_count, 3)
  159. def test_returns_none_only_after_the_complete_horizon(self):
  160. months = [
  161. probe(2026, month, [(1, 0, -1)])
  162. for month in (8, 9, 10)
  163. ]
  164. with patch("plugins.ita_plugin._capture_month", side_effect=months) as capture:
  165. result = scan_until_first_available_month(
  166. Mock(),
  167. lookahead_months=3,
  168. month_click_interval_seconds=0,
  169. )
  170. self.assertEqual(capture.call_count, 3)
  171. self.assertEqual(len(result), 3)
  172. self.assertEqual(result[-1].available_days, ())
  173. def test_accepts_an_exact_cross_year_transition(self):
  174. december = probe(2026, 12, [(1, 0, -1)])
  175. january = probe(2027, 1, [(4, 1, 0)])
  176. with patch("plugins.ita_plugin._capture_month", side_effect=[december, january]):
  177. result = scan_until_first_available_month(
  178. Mock(),
  179. lookahead_months=2,
  180. month_click_interval_seconds=0,
  181. )
  182. self.assertEqual(
  183. result[-1].available_days[0].day.isoformat(),
  184. "2027-01-04",
  185. )
  186. def test_rejects_a_skipped_month_instead_of_publishing_a_signal(self):
  187. august = probe(2026, 8, [(1, 0, -1)])
  188. october = probe(2026, 10, [(1, 1, 0)])
  189. with patch("plugins.ita_plugin._capture_month", side_effect=[august, october]):
  190. with self.assertRaisesRegex(
  191. CalendarGateError,
  192. "exactly one month",
  193. ):
  194. scan_until_first_available_month(
  195. Mock(),
  196. lookahead_months=2,
  197. month_click_interval_seconds=0,
  198. )
  199. def test_incomplete_native_navigation_is_not_misreported_as_no_slots(self):
  200. august = probe(2026, 8, [(1, 0, -1)])
  201. with patch(
  202. "plugins.ita_plugin._capture_month",
  203. side_effect=[august, CalendarNextMonthUnavailableError("bounded")],
  204. ):
  205. with self.assertRaisesRegex(
  206. CalendarGateError,
  207. "before the configured horizon",
  208. ):
  209. scan_until_first_available_month(
  210. Mock(),
  211. lookahead_months=2,
  212. month_click_interval_seconds=0,
  213. )
  214. def test_rejects_invalid_scan_bounds(self):
  215. for value in (True, 0, 121):
  216. with self.subTest(value=value):
  217. with self.assertRaisesRegex(
  218. CalendarGateError,
  219. "lookahead_months",
  220. ):
  221. scan_until_first_available_month(
  222. Mock(),
  223. lookahead_months=value,
  224. month_click_interval_seconds=0,
  225. )
  226. def test_invalid_scan_interval_never_touches_the_browser(self):
  227. for value in (True, None, "1", -1, float("nan"), float("inf")):
  228. with self.subTest(value=value):
  229. page = Mock()
  230. with self.assertRaisesRegex(CalendarGateError, "interval"):
  231. scan_until_first_available_month(
  232. page, lookahead_months=3, month_click_interval_seconds=value
  233. )
  234. self.assertEqual(page.mock_calls, [])
  235. if __name__ == "__main__":
  236. unittest.main()