test_ita_calendar_query.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """Query uses current browser-fetch and public plugin contracts; no live I/O."""
  2. import unittest
  3. from datetime import date
  4. from types import SimpleNamespace
  5. from unittest.mock import Mock, patch
  6. from plugins import ita_plugin as ita
  7. from test.ita.test_ita_compact import Response, day, encoded, route_config
  8. from vs_types import AppointmentType, AvailabilityStatus, VSAccount, VSPlgConfig
  9. class CalendarQueryTests(unittest.TestCase):
  10. def setUp(self):
  11. self.context = {"path": ita.CALENDAR_PATH, "service": "7002", "day": "2026-08-31"}
  12. self.page = SimpleNamespace(url="https://prenotami.esteri.it/BookingCalendar",
  13. tab_id="query-tab", run_js=Mock(side_effect=self.dom))
  14. self.months = {}
  15. self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch", side_effect=self.response))
  16. self.sleep = self.enterContext(patch.object(ita.time, "sleep"))
  17. def dom(self, script, *args):
  18. if script == "return 1;":
  19. return 1
  20. self.assertEqual(script, ita.CALENDAR_DOM_SCRIPT)
  21. self.assertEqual(args[0], "context")
  22. return dict(self.context)
  23. def response(self, page, method, path, **kwargs):
  24. self.assertIs(page, self.page)
  25. self.assertEqual((method, path), ("POST", ita.AVAILABILITY_PATH))
  26. payload = kwargs["json_data"]
  27. self.assertEqual(payload["_Servizio"], self.context["service"])
  28. self.assertEqual(set(payload), {"_Servizio", "selectedDay"})
  29. return Response(200, encoded(self.months.get(payload["selectedDay"], [])),
  30. "https://prenotami.esteri.it" + path)
  31. def scan(self, count=12):
  32. return ita.scan_until_first_available_month(self.page, lookahead_months=count,
  33. month_click_interval_seconds=0)
  34. def requested_months(self):
  35. return [call.kwargs["json_data"]["selectedDay"] for call in self.fetch.call_args_list]
  36. def plugin(self, *, service=7002, horizon=12):
  37. plugin = object.__new__(ita.ItaPlugin)
  38. config = route_config(service)
  39. config["calendar_scan"]["lookahead_months"] = horizon
  40. plugin.config = VSPlgConfig(account=VSAccount(username="pool@example.test", password="fixture"),
  41. session_max_life=0, free_config={"query_mode": "calendar", "otp_mode": "cloud",
  42. "apt_configs": {"route": config}})
  43. plugin.free_config = plugin.config.free_config
  44. plugin.page, plugin.is_healthy = self.page, True
  45. plugin._log = Mock()
  46. plugin._prepared_calendar = None
  47. route = plugin._resolve_route(AppointmentType(routing_key="route"))
  48. plugin._record_calendar_prepared_route(route, role="query")
  49. return plugin
  50. def test_initial_positive_month_stops_and_sorts_last_slot_correctly(self):
  51. self.months["01/08/2026"] = [day("20/08/2026 00:00:00", 8, 7), day("12/08/2026 00:00:00")]
  52. scans = self.scan()
  53. self.assertEqual(self.requested_months(), ["01/08/2026"])
  54. self.assertEqual([item.day for item in ita.available_calendar_days(scans[0])],
  55. [date(2026, 8, 12), date(2026, 8, 20)])
  56. def test_sequential_months_stop_before_later_inventory(self):
  57. self.months.update({"01/08/2026": [day("31/08/2026 00:00:00", 0, -1)],
  58. "01/10/2026": [day("20/10/2026 00:00:00", 8, 7),
  59. day("12/10/2026 00:00:00")],
  60. "01/11/2026": [day("02/11/2026 00:00:00", 10, 9)]})
  61. scans = self.scan()
  62. self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026", "01/10/2026"])
  63. self.assertEqual(ita.available_calendar_days(scans[-1])[0].day, date(2026, 10, 12))
  64. def test_empty_requires_complete_configured_horizon(self):
  65. self.assertEqual(self.scan(3), ((), (), ()))
  66. self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026", "01/10/2026"])
  67. def test_cross_year_requests_exact_next_month(self):
  68. self.context["day"] = "2026-12-20"
  69. self.months["01/01/2027"] = [day("04/01/2027 00:00:00")]
  70. self.assertEqual(ita.available_calendar_days(self.scan(2)[-1])[0].day, date(2027, 1, 4))
  71. self.assertEqual(self.requested_months(), ["01/12/2026", "01/01/2027"])
  72. def test_response_for_skipped_or_previous_month_is_not_availability(self):
  73. for wrong_day in ("01/10/2026 00:00:00", "01/08/2026 00:00:00"):
  74. with self.subTest(wrong_day=wrong_day):
  75. self.fetch.reset_mock()
  76. self.months["01/09/2026"] = [day(wrong_day)]
  77. with self.assertRaisesRegex(ita.BizLogicError, "another month"):
  78. self.scan(3)
  79. self.assertEqual(len(self.fetch.call_args_list), 2)
  80. def test_wrong_month_is_rejected_even_when_all_its_days_are_sold_out(self):
  81. self.months["01/08/2026"] = [day("01/09/2026 00:00:00", 0, -1)]
  82. with self.assertRaisesRegex(ita.BizLogicError, "another month"):
  83. self.scan()
  84. self.fetch.assert_called_once()
  85. def test_transport_failure_mid_horizon_is_not_no_availability(self):
  86. self.fetch.side_effect = [self.response(self.page, "POST", ita.AVAILABILITY_PATH,
  87. json_data={"_Servizio": "7002", "selectedDay": "01/08/2026"}),
  88. ita.RateLimiteddError("synthetic rate limit")]
  89. with self.assertRaises(ita.RateLimiteddError):
  90. self.scan(3)
  91. self.assertEqual(len(self.fetch.call_args_list), 2)
  92. def test_html_or_malformed_json_is_not_an_empty_month(self):
  93. for body in ("<html>unavailable</html>", "[]", '"not-json"'):
  94. with self.subTest(body=body):
  95. self.fetch.side_effect = None
  96. self.fetch.return_value = Response(200, body, "https://prenotami.esteri.it" + ita.AVAILABILITY_PATH)
  97. with self.assertRaises(ita.BizLogicError):
  98. self.scan()
  99. def test_invalid_scan_horizons_never_make_network_requests(self):
  100. for value in (True, 0, -1, 121):
  101. with self.subTest(value=value), self.assertRaises(ita.ItaProtocolError):
  102. self.scan(value)
  103. self.fetch.assert_not_called()
  104. def test_interval_applies_between_months_only(self):
  105. ita.scan_until_first_available_month(self.page, lookahead_months=3, month_click_interval_seconds=1.5)
  106. self.assertEqual([call.args for call in self.sleep.call_args_list], [(1.5,), (1.5,)])
  107. def test_wrong_calendar_path_or_runtime_id_prevents_requests(self):
  108. for service in ("", None, True, "0"):
  109. with self.subTest(service=service), self.assertRaises(ita.BizLogicError):
  110. self.context["service"] = service
  111. self.scan()
  112. self.page.url = "https://prenotami.esteri.it/UserArea"
  113. with self.assertRaises(ita.BizLogicError):
  114. self.scan()
  115. self.fetch.assert_not_called()
  116. def test_public_query_returns_earliest_date_without_slot_ids_or_times(self):
  117. self.months["01/09/2026"] = [day("20/09/2026 00:00:00", 8, 7), day("12/09/2026 00:00:00")]
  118. result = self.plugin().query(AppointmentType(routing_key="route"))
  119. self.assertTrue(result.success)
  120. self.assertEqual(result.availability_status, AvailabilityStatus.Available)
  121. self.assertEqual(result.earliest_date.date(), date(2026, 9, 12))
  122. self.assertEqual(len(result.availability), 1)
  123. self.assertEqual(result.availability[0].times, [])
  124. self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026"])
  125. def test_repeated_public_query_reuses_calendar_but_reads_fresh_inventory(self):
  126. plugin = self.plugin()
  127. self.months["01/08/2026"] = [day("31/08/2026 00:00:00")]
  128. first = plugin.query(AppointmentType(routing_key="route"))
  129. self.months["01/08/2026"] = []
  130. self.months["01/09/2026"] = [day("12/09/2026 00:00:00")]
  131. second = plugin.query(AppointmentType(routing_key="route"))
  132. self.assertNotEqual(first.earliest_date, second.earliest_date)
  133. self.assertEqual(self.requested_months(), ["01/08/2026", "01/08/2026", "01/09/2026"])
  134. def test_public_query_empty_horizon_returns_false_not_success(self):
  135. result = self.plugin(horizon=3).query(AppointmentType(routing_key="route"))
  136. self.assertFalse(result.success)
  137. self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
  138. self.assertEqual(len(self.fetch.call_args_list), 3)
  139. def test_region_uses_its_own_runtime_service(self):
  140. self.context["service"] = "9012"
  141. self.months["01/08/2026"] = [day("31/08/2026 00:00:00")]
  142. result = self.plugin(service=9012).query(AppointmentType(routing_key="route"))
  143. self.assertTrue(result.success)
  144. self.assertEqual(self.fetch.call_args.kwargs["json_data"]["_Servizio"], "9012")
  145. def test_identity_drift_during_request_never_publishes_a_result(self):
  146. self.months["01/08/2026"] = [day("31/08/2026 00:00:00")]
  147. for drift in ("account", "tab", "service", "unhealthy"):
  148. with self.subTest(drift=drift):
  149. self.context["service"], self.page.tab_id = "7002", "query-tab"
  150. plugin = self.plugin()
  151. self.fetch.reset_mock()
  152. def response(*args, **kwargs):
  153. reply = self.response(*args, **kwargs)
  154. if drift == "account":
  155. plugin.config.account.username = "other@example.test"
  156. elif drift == "tab":
  157. self.page.tab_id = "other-tab"
  158. elif drift == "service":
  159. self.context["service"] = "9012"
  160. else:
  161. plugin.is_healthy = False
  162. return reply
  163. self.fetch.side_effect = response
  164. with self.assertRaises(ita.BizLogicError):
  165. plugin.query(AppointmentType(routing_key="route"))
  166. self.fetch.assert_called_once()
  167. if __name__ == "__main__":
  168. unittest.main()