test_plugin_tester_ita_config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. """Offline checks for the Italy profile consumed by the existing public tester."""
  2. import copy
  3. from contextlib import redirect_stderr, redirect_stdout
  4. import io
  5. import json
  6. import logging
  7. from pathlib import Path
  8. from types import SimpleNamespace
  9. import unittest
  10. from unittest.mock import Mock, patch
  11. from plugins.ita_plugin import ItaCapability, resolve_route_config
  12. from sentinel import SentinelGCO
  13. from tools import debug_ita_query_book as query_book_cli
  14. from tools.plugin_tester import PluginTester
  15. from vs_types import GroupConfig
  16. def hong_kong_group():
  17. groups = json.loads((Path(__file__).resolve().parents[2] / "config/config_sentinel.json").read_text())
  18. matches = [group for group in groups if group["identifier"] == "ita.hong_kong"]
  19. if len(matches) != 1:
  20. raise AssertionError("Expected exactly one Hong Kong Sentinel profile")
  21. return GroupConfig.from_json(matches[0])
  22. class ItalyPublicTesterConfigTests(unittest.TestCase):
  23. def setUp(self):
  24. # Exercise the actual JSON loader and registration, never create a plugin,
  25. # open a browser, or use the configured credentials in an assertion.
  26. with patch("vs_plg_factory.VSC_INFO"), patch(
  27. "tools.plugin_tester.VSPlgFactory.create",
  28. side_effect=AssertionError("Offline configuration check must not create a plugin"),
  29. ):
  30. self.tester = PluginTester.from_json_config(
  31. "ita_plugin",
  32. str(Path(__file__).resolve().parents[2] / "config/test_conf.json"),
  33. user_override="query@example.test",
  34. password_override="synthetic-not-a-secret",
  35. proxy_override="http://127.0.0.1:9999",
  36. )
  37. def test_existing_loader_resolves_one_hong_kong_appointment(self):
  38. self.assertIsNone(self.tester.plugin)
  39. self.assertEqual(self.tester.group_id, "ita.hong_kong")
  40. self.assertEqual(len(self.tester.appointment_types), 1)
  41. appointment = self.tester.appointment_types[0]
  42. self.assertEqual(appointment.routing_key, "slot.hkg.it.tourist")
  43. self.assertEqual(appointment.city, "Hong Kong")
  44. self.assertEqual(appointment.country, "Italy")
  45. self.assertEqual(appointment.visa_type, "Tourist")
  46. def test_query_profile_uses_cloud_preparation_and_disables_final_submission(self):
  47. config = self.tester.config
  48. self.assertIs(config.debug, False)
  49. self.assertEqual(config.free_config["query_mode"], "calendar")
  50. self.assertEqual(config.free_config["otp_mode"], "cloud")
  51. self.assertIs(config.free_config["final_submit_enabled"], False)
  52. def test_existing_protocol_parser_accepts_evidenced_form_and_scan_settings(self):
  53. route = resolve_route_config(
  54. self.tester.config.free_config["apt_configs"],
  55. self.tester.appointment_types[0].routing_key,
  56. )
  57. self.assertEqual(route.service_id, 4937)
  58. self.assertIs(route.capability, ItaCapability.SINGLE_SCHENGEN_TOURISM)
  59. self.assertEqual(route.lookahead_months, 12)
  60. self.assertEqual(route.booking_type.control_id, "typeofbookingddl")
  61. self.assertEqual(route.booking_type.value, "1")
  62. self.assertEqual(route.booking_type.labels, ("Prenotazione Singola", "Single booking"))
  63. self.assertEqual(route.purpose.control_id, "ddls_0")
  64. self.assertEqual(route.purpose.value, "42")
  65. self.assertEqual(route.purpose.labels, ("Turismo", "Tourism"))
  66. self.assertIsNotNone(route.mail)
  67. self.assertEqual(route.mail.authorization_source, "account")
  68. self.assertIsNone(route.mail.authorization_email)
  69. self.assertEqual(route.mail.mailbox_for("query@example.test"), "query@example.test")
  70. def test_public_tester_and_sentinel_share_route_and_otp_contract(self):
  71. group = hong_kong_group()
  72. config = self.tester.config.free_config
  73. self.assertEqual(group.appointment_types, self.tester.appointment_types)
  74. for key in ("website", "query_mode", "otp_mode", "final_submit_enabled", "apt_configs"):
  75. self.assertEqual(group.free_config[key], config[key])
  76. class ItalySingleAccountPoolConfigTests(unittest.TestCase):
  77. def setUp(self):
  78. self.group = hong_kong_group()
  79. # Do not create browsers, read account secrets or call a live backend.
  80. for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
  81. "requests.sessions.Session.request", "subprocess.Popen"):
  82. self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
  83. self.cloud = Mock()
  84. self.cloud.get_next_account.return_value = {
  85. "id": 71, "pool_name": "hkg.it.sentinel", "username": "pooled@example.test",
  86. "password": "synthetic-pool-password", "status": "active",
  87. }
  88. self.cloud.get_next_proxy.return_value = {"id": 72, "ip": "127.0.0.1", "port": 9999}
  89. self.redis = Mock()
  90. self.enterContext(patch.dict(SentinelGCO.__init__.__globals__, {
  91. "SafeRedisClient": Mock(return_value=self.redis),
  92. "VSCloudApi": SimpleNamespace(Instance=lambda: self.cloud),
  93. }))
  94. self.sentinel = SentinelGCO(self.group, {}, Mock())
  95. self.plugin = Mock()
  96. self.sentinel.m_factory.create = Mock(return_value=self.plugin)
  97. self.addCleanup(self.sentinel.stop)
  98. def test_profile_is_disabled_single_instance_cloud_query_without_local_credentials(self):
  99. group = self.group
  100. self.assertFalse(group.enable)
  101. self.assertFalse(group.debug)
  102. self.assertTrue(group.need_account)
  103. self.assertEqual(group.sentinel.account_source, "built-in")
  104. self.assertEqual(group.sentinel.account_pool_id, "hkg.it.sentinel")
  105. self.assertEqual(group.sentinel.target_instances, 1)
  106. self.assertEqual(group.sentinel.account_cd, group.session_max_life)
  107. self.assertEqual(group.sentinel.account_cd, 1800)
  108. self.assertEqual(group.free_config["otp_mode"], "cloud")
  109. self.assertIs(group.free_config["final_submit_enabled"], False)
  110. for key in ("account", "password", "local_account_file", "authorization_code"):
  111. self.assertNotIn(key, group.free_config)
  112. self.sentinel.start()
  113. self.sentinel.m_factory.create.assert_not_called()
  114. self.cloud.get_next_account.assert_not_called()
  115. def test_existing_sentinel_spawner_binds_pool_account_and_mail_configuration(self):
  116. before = copy.deepcopy(self.group)
  117. self.sentinel._spawn_sentinel_worker()
  118. self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
  119. self.cloud.get_next_proxy.assert_called_once_with(self.group.proxy_pool, self.group.proxy_cd)
  120. self.plugin.set_config.assert_called_once()
  121. config = self.plugin.set_config.call_args.args[0]
  122. self.assertEqual(config.account.id, 71)
  123. self.assertEqual(config.account.username, "pooled@example.test")
  124. self.assertEqual(config.account.password, "synthetic-pool-password")
  125. self.assertEqual(config.free_config, self.group.free_config)
  126. self.assertEqual(self.group, before)
  127. self.plugin.create_session.assert_called_once()
  128. self.assertEqual(len(self.sentinel.m_tasks), 1)
  129. self.assertFalse(self.sentinel.m_tasks[0].book_allowed)
  130. self.plugin.book.assert_not_called()
  131. self.redis.setex.assert_not_called()
  132. def test_empty_or_cooling_pool_does_not_fall_back_to_a_local_account(self):
  133. self.cloud.get_next_account.side_effect = RuntimeError("synthetic unavailable pool")
  134. self.sentinel._spawn_sentinel_worker()
  135. self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
  136. self.sentinel.m_factory.create.assert_not_called()
  137. self.plugin.create_session.assert_not_called()
  138. self.assertEqual(self.sentinel.m_tasks, [])
  139. class ItalyPoolQueryCommandTests(unittest.TestCase):
  140. def setUp(self):
  141. for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
  142. "requests.sessions.Session.request", "subprocess.Popen"):
  143. self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
  144. logger = logging.Logger("ita-pool-command-offline", level=logging.INFO)
  145. self.enterContext(patch("vs_log_macros._active_logger", logger))
  146. self.enterContext(patch("configure.TEST_ACCOUNT", None))
  147. self.cloud = Mock()
  148. self.cloud.get_next_account.return_value = {
  149. "id": 71, "username": "first-pool-account@example.test",
  150. "password": "synthetic-command-password", "pool_name": "hkg.it.sentinel", "status": "active",
  151. }
  152. self.enterContext(patch("toolkit.vs_cloud_api.VSCloudApi.Instance", return_value=self.cloud))
  153. self.pipeline = self.enterContext(patch.object(PluginTester, "run_pipeline", autospec=True, return_value=True))
  154. self.enterContext(patch("utils.local_account.load_local_account",
  155. side_effect=AssertionError("Pool test must not load a local account")))
  156. def run_pool_query(self):
  157. output = io.StringIO()
  158. with redirect_stdout(output):
  159. code = query_book_cli.main(["--pool-query"])
  160. return code, output.getvalue()
  161. def test_supported_command_uses_existing_sdk_and_public_tester_query_only(self):
  162. code, output = self.run_pool_query()
  163. self.assertEqual(code, 0)
  164. self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
  165. self.pipeline.assert_called_once()
  166. self.assertEqual(self.pipeline.call_args.kwargs, {"test_book": False})
  167. tester = self.pipeline.call_args.args[0]
  168. self.assertEqual(tester.config.account.id, 71)
  169. self.assertEqual(tester.config.account.password, "synthetic-command-password")
  170. self.assertEqual(tester.config.free_config, hong_kong_group().free_config)
  171. self.assertEqual(tester.config.proxy.port, 6268)
  172. self.assertIsNone(tester.plugin)
  173. self.assertIn("ITA_POOL_QUERY_SOURCE=cloud_pool pool=hkg.it.sentinel book=false", output)
  174. self.assertNotIn("synthetic-command-password", output)
  175. self.assertIn("ITA_POOL_QUERY_CONTRACT=account-mailbox-v3", output)
  176. def test_second_pool_account_is_accepted_and_resolves_its_own_mailbox(self):
  177. for address in ("first-pool-account@example.test", "second-pool-account@example.test"):
  178. with self.subTest(address=address):
  179. self.pipeline.reset_mock()
  180. self.cloud.get_next_account.return_value["username"] = address
  181. code, _ = self.run_pool_query()
  182. self.assertEqual(code, 0)
  183. tester = self.pipeline.call_args.args[0]
  184. route = resolve_route_config(tester.config.free_config["apt_configs"],
  185. tester.appointment_types[0].routing_key)
  186. self.assertEqual(route.mail.mailbox_for(tester.config.account.username), address)
  187. self.assertIsNone(route.mail.authorization_email)
  188. def test_debug_payload_logging_is_not_an_italy_allocation_gate(self):
  189. with patch("vs_log_macros._active_logger", logging.Logger("unsafe-fixture", level=logging.DEBUG)):
  190. code, output = self.run_pool_query()
  191. self.assertEqual(code, 0)
  192. self.assertIn("ITA_POOL_QUERY_SOURCE=cloud_pool", output)
  193. self.cloud.get_next_account.assert_called_once()
  194. self.pipeline.assert_called_once()
  195. def test_test_account_override_stops_before_pool_allocation(self):
  196. with patch("configure.TEST_ACCOUNT", {"username": "fixture@example.test"}):
  197. code, output = self.run_pool_query()
  198. self.assertEqual(code, 1)
  199. self.assertIn("ITA_POOL_QUERY_ACCOUNT_REJECTED reason=test_account_override_enabled", output)
  200. self.cloud.get_next_account.assert_not_called()
  201. self.pipeline.assert_not_called()
  202. def test_pool_failure_does_not_fall_back_or_print_backend_error_body(self):
  203. self.cloud.get_next_account.side_effect = RuntimeError("synthetic-sensitive-response")
  204. code, output = self.run_pool_query()
  205. self.assertEqual(code, 1)
  206. self.assertIn("ITA_POOL_QUERY_ACCOUNT_FAILED type=RuntimeError", output)
  207. self.assertNotIn("synthetic-sensitive-response", output)
  208. self.pipeline.assert_not_called()
  209. def test_wrong_pool_empty_password_or_disabled_account_stops_before_browser(self):
  210. original = self.cloud.get_next_account.return_value.copy()
  211. for field, value in (("pool_name", "other.pool"), ("password", ""), ("status", "disable")):
  212. with self.subTest(field=field):
  213. self.cloud.get_next_account.return_value = {**original, field: value}
  214. code, output = self.run_pool_query()
  215. self.assertEqual(code, 1)
  216. self.assertIn("ITA_POOL_QUERY_ACCOUNT_REJECTED", output)
  217. self.pipeline.assert_not_called()
  218. def test_invalid_account_email_stops_before_browser(self):
  219. self.cloud.get_next_account.return_value["username"] = "not-an-email"
  220. code, output = self.run_pool_query()
  221. self.assertEqual(code, 1)
  222. self.assertIn("ITA_POOL_QUERY_MAIL_CONFIG_FAILED", output)
  223. self.pipeline.assert_not_called()
  224. def test_pool_query_rejects_final_submission_before_account_allocation(self):
  225. with self.assertRaises(SystemExit) as raised, redirect_stderr(io.StringIO()):
  226. query_book_cli.main(["--pool-query", "--submit-once"])
  227. self.assertEqual(raised.exception.code, 2)
  228. self.cloud.get_next_account.assert_not_called()
  229. self.pipeline.assert_not_called()
  230. if __name__ == "__main__":
  231. unittest.main()