test_plugin_tester_ita_config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. """Offline checks for the Italy profile consumed by the existing public tester."""
  2. import copy
  3. from contextlib import redirect_stdout
  4. import io
  5. import json
  6. import logging
  7. from pathlib import Path
  8. import shlex
  9. from types import SimpleNamespace
  10. import unittest
  11. from unittest.mock import Mock, patch
  12. from plugins.ita_plugin import ItaCapability, resolve_route_config
  13. from sentinel import SentinelGCO
  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[1] / "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[1] / "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.calendar_scan.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 ItalyDocumentedPoolCommandTests(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_documented_command(self):
  157. path = Path(__file__).resolve().parents[1] / "docs/ita_query_book_acceptance.md"
  158. section = path.read_text().split("<!-- ITA_POOL_QUERY_COMMAND -->", 1)[1].split("<!-- /ITA_POOL_QUERY_COMMAND -->", 1)[0]
  159. shell = section.split("```bash", 1)[1].split("```", 1)[0]
  160. tokens = shlex.split(shell)
  161. code = tokens[tokens.index("-c") + 1]
  162. output = io.StringIO()
  163. with redirect_stdout(output), self.assertRaises(SystemExit) as result:
  164. exec(compile(code, str(path) + ":pool-query-command", "exec"), {"__name__": "__main__"})
  165. return result.exception.code, output.getvalue()
  166. def test_exact_documented_command_uses_existing_sdk_and_public_tester_query_only(self):
  167. code, output = self.run_documented_command()
  168. self.assertEqual(code, 0)
  169. self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
  170. self.pipeline.assert_called_once()
  171. self.assertEqual(self.pipeline.call_args.kwargs, {"test_book": False})
  172. tester = self.pipeline.call_args.args[0]
  173. self.assertEqual(tester.config.account.id, 71)
  174. self.assertEqual(tester.config.account.password, "synthetic-command-password")
  175. self.assertEqual(tester.config.free_config, hong_kong_group().free_config)
  176. self.assertEqual(tester.config.proxy.port, 6268)
  177. self.assertIsNone(tester.plugin)
  178. self.assertIn("ITA_POOL_QUERY_SOURCE=cloud_pool pool=hkg.it.sentinel book=false", output)
  179. self.assertNotIn("synthetic-command-password", output)
  180. self.assertIn("ITA_POOL_QUERY_CONTRACT=account-mailbox-v2", output)
  181. def test_second_pool_account_is_accepted_and_resolves_its_own_mailbox(self):
  182. for address in ("first-pool-account@example.test", "second-pool-account@example.test"):
  183. with self.subTest(address=address):
  184. self.pipeline.reset_mock()
  185. self.cloud.get_next_account.return_value["username"] = address
  186. code, _ = self.run_documented_command()
  187. self.assertEqual(code, 0)
  188. tester = self.pipeline.call_args.args[0]
  189. route = resolve_route_config(tester.config.free_config["apt_configs"],
  190. tester.appointment_types[0].routing_key)
  191. self.assertEqual(route.mail.mailbox_for(tester.config.account.username), address)
  192. self.assertIsNone(route.mail.authorization_email)
  193. def test_debug_payload_logging_stops_before_account_allocation(self):
  194. with patch("vs_log_macros._active_logger", logging.Logger("unsafe-fixture", level=logging.DEBUG)):
  195. with self.assertRaisesRegex(Exception, "DEBUG"):
  196. self.run_documented_command()
  197. self.cloud.get_next_account.assert_not_called()
  198. self.pipeline.assert_not_called()
  199. def test_test_account_override_stops_before_pool_allocation(self):
  200. with patch("configure.TEST_ACCOUNT", {"username": "fixture@example.test"}):
  201. code, _ = self.run_documented_command()
  202. self.assertIn("TEST_ACCOUNT", code)
  203. self.cloud.get_next_account.assert_not_called()
  204. self.pipeline.assert_not_called()
  205. def test_pool_failure_does_not_fall_back_or_print_backend_error_body(self):
  206. self.cloud.get_next_account.side_effect = RuntimeError("synthetic-sensitive-response")
  207. code, output = self.run_documented_command()
  208. self.assertEqual(code, 1)
  209. self.assertIn("ITA_POOL_QUERY_ACCOUNT_FAILED type=RuntimeError", output)
  210. self.assertNotIn("synthetic-sensitive-response", output)
  211. self.pipeline.assert_not_called()
  212. def test_wrong_pool_empty_password_or_disabled_account_stops_before_browser(self):
  213. original = self.cloud.get_next_account.return_value.copy()
  214. for field, value in (("pool_name", "other.pool"), ("password", ""), ("status", "disable")):
  215. with self.subTest(field=field):
  216. self.cloud.get_next_account.return_value = {**original, field: value}
  217. code, _ = self.run_documented_command()
  218. self.assertIsInstance(code, str)
  219. self.assertIn("Stop:", code)
  220. self.pipeline.assert_not_called()
  221. def test_invalid_account_email_stops_before_browser(self):
  222. self.cloud.get_next_account.return_value["username"] = "not-an-email"
  223. code, output = self.run_documented_command()
  224. self.assertEqual(code, 1)
  225. self.assertIn("ITA_POOL_QUERY_MAIL_CONFIG_FAILED", output)
  226. self.pipeline.assert_not_called()
  227. if __name__ == "__main__":
  228. unittest.main()